From fe2c6c105f56b106c029536c079fa295c52c1053 Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Mon, 25 Nov 2024 16:35:29 +0100 Subject: [PATCH 1/4] vendor: remove the vendored dependencies Similar to what we did in `images` in PR#861 (thanks to @achilleas-k) this commit removes the vendoring from image-builder. We don't package image-builder so just like with images we don't need the vendor dir (go.{mod,sum} is fine to re-create the environment). --- vendor/github.com/BurntSushi/toml/.gitignore | 2 - vendor/github.com/BurntSushi/toml/COPYING | 21 - vendor/github.com/BurntSushi/toml/README.md | 120 - vendor/github.com/BurntSushi/toml/decode.go | 613 - .../github.com/BurntSushi/toml/deprecated.go | 29 - vendor/github.com/BurntSushi/toml/doc.go | 8 - vendor/github.com/BurntSushi/toml/encode.go | 778 - vendor/github.com/BurntSushi/toml/error.go | 356 - .../github.com/BurntSushi/toml/internal/tz.go | 36 - vendor/github.com/BurntSushi/toml/lex.go | 1281 - vendor/github.com/BurntSushi/toml/meta.go | 148 - vendor/github.com/BurntSushi/toml/parse.go | 844 - .../github.com/BurntSushi/toml/type_fields.go | 238 - .../github.com/BurntSushi/toml/type_toml.go | 65 - .../Masterminds/semver/v3/.gitignore | 1 - .../Masterminds/semver/v3/.golangci.yml | 26 - .../Masterminds/semver/v3/CHANGELOG.md | 194 - .../Masterminds/semver/v3/LICENSE.txt | 19 - .../github.com/Masterminds/semver/v3/Makefile | 37 - .../Masterminds/semver/v3/README.md | 244 - .../Masterminds/semver/v3/collection.go | 24 - .../Masterminds/semver/v3/constraints.go | 568 - .../github.com/Masterminds/semver/v3/doc.go | 184 - .../github.com/Masterminds/semver/v3/fuzz.go | 22 - .../Masterminds/semver/v3/version.go | 606 - .../Unleash/unleash-client-go/v4/.gitignore | 46 - .../Unleash/unleash-client-go/v4/LICENSE | 201 - .../Unleash/unleash-client-go/v4/Makefile | 28 - .../Unleash/unleash-client-go/v4/README.md | 349 - .../unleash-client-go/v4/api/constraint.go | 87 - .../unleash-client-go/v4/api/feature.go | 156 - .../unleash-client-go/v4/api/response.go | 5 - .../unleash-client-go/v4/api/strategy.go | 43 - .../unleash-client-go/v4/api/variant.go | 98 - .../unleash-client-go/v4/bootstrap_storage.go | 55 - .../Unleash/unleash-client-go/v4/client.go | 549 - .../Unleash/unleash-client-go/v4/config.go | 269 - .../unleash-client-go/v4/context/context.go | 75 - .../unleash-client-go/v4/debuglistener.go | 40 - .../v4/demo_app_toggles.json | 4509 -- .../Unleash/unleash-client-go/v4/doc.go | 43 - .../v4/internal/api/event.go | 36 - .../v4/internal/api/metrics.go | 19 - .../v4/internal/constraints/check.go | 68 - .../v4/internal/constraints/operator_date.go | 48 - .../v4/internal/constraints/operator_in.go | 22 - .../v4/internal/constraints/operator_num.go | 57 - .../internal/constraints/operator_semver.go | 45 - .../v4/internal/constraints/operator_str.go | 43 - .../strategies/application_hostname.go | 41 - .../v4/internal/strategies/default.go | 17 - .../internal/strategies/flexible_rollout.go | 67 - .../strategies/gradual_rollout_random.go | 35 - .../strategies/gradual_rollout_session_id.go | 44 - .../strategies/gradual_rollout_user_id.go | 44 - .../v4/internal/strategies/helpers.go | 104 - .../v4/internal/strategies/remote_addresss.go | 46 - .../v4/internal/strategies/user_with_id.go | 36 - .../Unleash/unleash-client-go/v4/metrics.go | 343 - .../unleash-client-go/v4/nooplistener.go | 28 - .../unleash-client-go/v4/repository.go | 228 - .../Unleash/unleash-client-go/v4/storage.go | 102 - .../unleash-client-go/v4/strategy/strategy.go | 37 - .../Unleash/unleash-client-go/v4/unleash.go | 74 - .../unleash-client-go/v4/unleash_mock.go | 49 - .../Unleash/unleash-client-go/v4/utils.go | 80 - .../apapsch/go-jsonmerge/v2/.editorconfig | 6 - .../apapsch/go-jsonmerge/v2/.gitattributes | 175 - .../apapsch/go-jsonmerge/v2/.gitignore | 11 - .../apapsch/go-jsonmerge/v2/.gitlab-ci.yml | 42 - .../apapsch/go-jsonmerge/v2/.travis.yml | 19 - .../apapsch/go-jsonmerge/v2/LICENSE | 21 - .../apapsch/go-jsonmerge/v2/README.md | 81 - .../apapsch/go-jsonmerge/v2/build.cmd | 25 - .../apapsch/go-jsonmerge/v2/build.sh | 19 - .../github.com/apapsch/go-jsonmerge/v2/doc.go | 52 - .../apapsch/go-jsonmerge/v2/merge.go | 167 - vendor/github.com/aws/aws-sdk-go/LICENSE.txt | 202 - vendor/github.com/aws/aws-sdk-go/NOTICE.txt | 3 - .../aws/aws-sdk-go/aws/auth/bearer/token.go | 50 - .../aws/aws-sdk-go/aws/awserr/error.go | 164 - .../aws/aws-sdk-go/aws/awserr/types.go | 221 - .../aws/aws-sdk-go/aws/awsutil/copy.go | 108 - .../aws/aws-sdk-go/aws/awsutil/equal.go | 27 - .../aws/aws-sdk-go/aws/awsutil/path_value.go | 221 - .../aws/aws-sdk-go/aws/awsutil/prettify.go | 123 - .../aws-sdk-go/aws/awsutil/string_value.go | 90 - .../aws/aws-sdk-go/aws/client/client.go | 94 - .../aws-sdk-go/aws/client/default_retryer.go | 177 - .../aws/aws-sdk-go/aws/client/logger.go | 206 - .../aws/client/metadata/client_info.go | 15 - .../aws-sdk-go/aws/client/no_op_retryer.go | 28 - .../github.com/aws/aws-sdk-go/aws/config.go | 670 - .../aws/aws-sdk-go/aws/context_1_5.go | 38 - .../aws/aws-sdk-go/aws/context_1_9.go | 12 - .../aws-sdk-go/aws/context_background_1_5.go | 23 - .../aws-sdk-go/aws/context_background_1_7.go | 21 - .../aws/aws-sdk-go/aws/context_sleep.go | 24 - .../aws/aws-sdk-go/aws/convert_types.go | 918 - .../aws/corehandlers/awsinternal.go | 4 - .../aws-sdk-go/aws/corehandlers/handlers.go | 232 - .../aws/corehandlers/param_validator.go | 17 - .../aws-sdk-go/aws/corehandlers/user_agent.go | 47 - .../aws/credentials/chain_provider.go | 100 - .../credentials/context_background_go1.5.go | 23 - .../credentials/context_background_go1.7.go | 21 - .../aws/credentials/context_go1.5.go | 40 - .../aws/credentials/context_go1.9.go | 14 - .../aws-sdk-go/aws/credentials/credentials.go | 383 - .../ec2rolecreds/ec2_role_provider.go | 188 - .../aws/credentials/endpointcreds/provider.go | 255 - .../aws/credentials/env_provider.go | 74 - .../aws-sdk-go/aws/credentials/example.ini | 12 - .../aws/credentials/processcreds/provider.go | 438 - .../shared_credentials_provider.go | 151 - .../aws/credentials/ssocreds/doc.go | 60 - .../aws-sdk-go/aws/credentials/ssocreds/os.go | 10 - .../aws/credentials/ssocreds/os_windows.go | 7 - .../aws/credentials/ssocreds/provider.go | 187 - .../credentials/ssocreds/sso_cached_token.go | 237 - .../credentials/ssocreds/token_provider.go | 148 - .../aws/credentials/static_provider.go | 57 - .../stscreds/assume_role_provider.go | 371 - .../stscreds/web_identity_provider.go | 182 - .../github.com/aws/aws-sdk-go/aws/csm/doc.go | 69 - .../aws/aws-sdk-go/aws/csm/enable.go | 89 - .../aws/aws-sdk-go/aws/csm/metric.go | 109 - .../aws/aws-sdk-go/aws/csm/metric_chan.go | 55 - .../aws-sdk-go/aws/csm/metric_exception.go | 26 - .../aws/aws-sdk-go/aws/csm/reporter.go | 264 - .../aws/aws-sdk-go/aws/defaults/defaults.go | 252 - .../aws-sdk-go/aws/defaults/shared_config.go | 27 - vendor/github.com/aws/aws-sdk-go/aws/doc.go | 56 - .../aws/aws-sdk-go/aws/ec2metadata/api.go | 250 - .../aws/aws-sdk-go/aws/ec2metadata/service.go | 245 - .../aws/ec2metadata/token_provider.go | 99 - .../aws/aws-sdk-go/aws/endpoints/decode.go | 193 - .../aws/aws-sdk-go/aws/endpoints/defaults.go | 48609 ---------------- .../aws/endpoints/dep_service_ids.go | 141 - .../aws/aws-sdk-go/aws/endpoints/doc.go | 65 - .../aws/aws-sdk-go/aws/endpoints/endpoints.go | 708 - .../aws/endpoints/legacy_regions.go | 24 - .../aws/aws-sdk-go/aws/endpoints/v3model.go | 594 - .../aws/endpoints/v3model_codegen.go | 412 - .../github.com/aws/aws-sdk-go/aws/errors.go | 13 - .../aws/aws-sdk-go/aws/jsonvalue.go | 12 - .../github.com/aws/aws-sdk-go/aws/logger.go | 121 - .../aws/request/connection_reset_error.go | 19 - .../aws/aws-sdk-go/aws/request/handlers.go | 346 - .../aws-sdk-go/aws/request/http_request.go | 24 - .../aws-sdk-go/aws/request/offset_reader.go | 65 - .../aws/aws-sdk-go/aws/request/request.go | 722 - .../aws/aws-sdk-go/aws/request/request_1_7.go | 40 - .../aws/aws-sdk-go/aws/request/request_1_8.go | 37 - .../aws-sdk-go/aws/request/request_context.go | 15 - .../aws/request/request_context_1_6.go | 15 - .../aws/request/request_pagination.go | 266 - .../aws/aws-sdk-go/aws/request/retryer.go | 309 - .../aws/request/timeout_read_closer.go | 94 - .../aws/aws-sdk-go/aws/request/validation.go | 286 - .../aws/aws-sdk-go/aws/request/waiter.go | 304 - .../aws/aws-sdk-go/aws/session/credentials.go | 333 - .../aws/session/custom_transport.go | 28 - .../aws/session/custom_transport_go1.12.go | 27 - .../aws/session/custom_transport_go1.5.go | 23 - .../aws/session/custom_transport_go1.6.go | 24 - .../aws/aws-sdk-go/aws/session/doc.go | 367 - .../aws/aws-sdk-go/aws/session/env_config.go | 499 - .../aws/aws-sdk-go/aws/session/session.go | 1005 - .../aws-sdk-go/aws/session/shared_config.go | 856 - .../aws-sdk-go/aws/signer/v4/header_rules.go | 81 - .../aws/aws-sdk-go/aws/signer/v4/options.go | 7 - .../aws/signer/v4/request_context_go1.5.go | 14 - .../aws/signer/v4/request_context_go1.7.go | 14 - .../aws/aws-sdk-go/aws/signer/v4/stream.go | 63 - .../aws/aws-sdk-go/aws/signer/v4/uri_path.go | 25 - .../aws/aws-sdk-go/aws/signer/v4/v4.go | 857 - vendor/github.com/aws/aws-sdk-go/aws/types.go | 264 - vendor/github.com/aws/aws-sdk-go/aws/url.go | 13 - .../github.com/aws/aws-sdk-go/aws/url_1_7.go | 30 - .../github.com/aws/aws-sdk-go/aws/version.go | 8 - .../internal/context/background_go1.5.go | 41 - .../aws/aws-sdk-go/internal/ini/ast.go | 120 - .../aws-sdk-go/internal/ini/comma_token.go | 11 - .../aws-sdk-go/internal/ini/comment_token.go | 35 - .../aws/aws-sdk-go/internal/ini/doc.go | 42 - .../aws-sdk-go/internal/ini/empty_token.go | 4 - .../aws/aws-sdk-go/internal/ini/expression.go | 24 - .../aws/aws-sdk-go/internal/ini/fuzz.go | 18 - .../aws/aws-sdk-go/internal/ini/ini.go | 51 - .../aws/aws-sdk-go/internal/ini/ini_lexer.go | 165 - .../aws/aws-sdk-go/internal/ini/ini_parser.go | 350 - .../aws-sdk-go/internal/ini/literal_tokens.go | 337 - .../aws-sdk-go/internal/ini/newline_token.go | 30 - .../aws-sdk-go/internal/ini/number_helper.go | 152 - .../aws/aws-sdk-go/internal/ini/op_tokens.go | 39 - .../aws-sdk-go/internal/ini/parse_error.go | 43 - .../aws-sdk-go/internal/ini/parse_stack.go | 60 - .../aws/aws-sdk-go/internal/ini/sep_tokens.go | 41 - .../aws/aws-sdk-go/internal/ini/skipper.go | 45 - .../aws/aws-sdk-go/internal/ini/statement.go | 35 - .../aws/aws-sdk-go/internal/ini/value_util.go | 284 - .../aws/aws-sdk-go/internal/ini/visitor.go | 169 - .../aws/aws-sdk-go/internal/ini/walker.go | 25 - .../aws/aws-sdk-go/internal/ini/ws_token.go | 24 - .../aws/aws-sdk-go/internal/sdkio/byte.go | 12 - .../aws/aws-sdk-go/internal/sdkio/io_go1.6.go | 11 - .../aws/aws-sdk-go/internal/sdkio/io_go1.7.go | 13 - .../aws/aws-sdk-go/internal/sdkmath/floor.go | 16 - .../internal/sdkmath/floor_go1.9.go | 57 - .../internal/sdkrand/locked_source.go | 29 - .../aws/aws-sdk-go/internal/sdkrand/read.go | 12 - .../aws-sdk-go/internal/sdkrand/read_1_5.go | 25 - .../aws/aws-sdk-go/internal/sdkuri/path.go | 23 - .../internal/shareddefaults/ecs_container.go | 12 - .../internal/shareddefaults/shared_config.go | 46 - .../shared_config_resolve_home.go | 18 - .../shared_config_resolve_home_go1.12.go | 13 - .../aws-sdk-go/internal/strings/strings.go | 11 - .../internal/sync/singleflight/LICENSE | 27 - .../sync/singleflight/singleflight.go | 120 - .../private/protocol/eventstream/debug.go | 144 - .../private/protocol/eventstream/decode.go | 216 - .../private/protocol/eventstream/encode.go | 162 - .../private/protocol/eventstream/error.go | 23 - .../eventstream/eventstreamapi/error.go | 81 - .../eventstream/eventstreamapi/reader.go | 173 - .../eventstream/eventstreamapi/shared.go | 23 - .../eventstream/eventstreamapi/signer.go | 123 - .../eventstreamapi/stream_writer.go | 129 - .../eventstream/eventstreamapi/transport.go | 10 - .../eventstreamapi/transport_go1.17.go | 19 - .../eventstream/eventstreamapi/writer.go | 63 - .../private/protocol/eventstream/header.go | 175 - .../protocol/eventstream/header_value.go | 506 - .../private/protocol/eventstream/message.go | 117 - .../aws/aws-sdk-go/private/protocol/host.go | 104 - .../private/protocol/host_prefix.go | 54 - .../private/protocol/idempotency.go | 75 - .../private/protocol/json/jsonutil/build.go | 309 - .../protocol/json/jsonutil/unmarshal.go | 317 - .../private/protocol/jsonrpc/jsonrpc.go | 87 - .../protocol/jsonrpc/unmarshal_error.go | 160 - .../aws-sdk-go/private/protocol/jsonvalue.go | 76 - .../aws-sdk-go/private/protocol/payload.go | 81 - .../aws-sdk-go/private/protocol/protocol.go | 49 - .../private/protocol/query/build.go | 36 - .../protocol/query/queryutil/queryutil.go | 276 - .../private/protocol/query/unmarshal.go | 39 - .../private/protocol/query/unmarshal_error.go | 70 - .../aws-sdk-go/private/protocol/rest/build.go | 353 - .../private/protocol/rest/payload.go | 54 - .../private/protocol/rest/unmarshal.go | 276 - .../private/protocol/restjson/restjson.go | 59 - .../protocol/restjson/unmarshal_error.go | 157 - .../aws-sdk-go/private/protocol/timestamp.go | 134 - .../aws-sdk-go/private/protocol/unmarshal.go | 27 - .../private/protocol/unmarshal_error.go | 65 - .../private/protocol/xml/xmlutil/build.go | 345 - .../private/protocol/xml/xmlutil/sort.go | 32 - .../private/protocol/xml/xmlutil/unmarshal.go | 311 - .../protocol/xml/xmlutil/xml_to_struct.go | 173 - .../aws-sdk-go/service/cloudwatchlogs/api.go | 21368 ------- .../aws-sdk-go/service/cloudwatchlogs/doc.go | 57 - .../service/cloudwatchlogs/errors.go | 159 - .../service/cloudwatchlogs/service.go | 112 - .../aws/aws-sdk-go/service/sso/api.go | 1367 - .../aws/aws-sdk-go/service/sso/doc.go | 45 - .../aws/aws-sdk-go/service/sso/errors.go | 44 - .../aws/aws-sdk-go/service/sso/service.go | 106 - .../service/sso/ssoiface/interface.go | 86 - .../aws/aws-sdk-go/service/ssooidc/api.go | 2406 - .../aws/aws-sdk-go/service/ssooidc/doc.go | 67 - .../aws/aws-sdk-go/service/ssooidc/errors.go | 123 - .../aws/aws-sdk-go/service/ssooidc/service.go | 106 - .../aws/aws-sdk-go/service/sts/api.go | 3553 -- .../aws-sdk-go/service/sts/customizations.go | 11 - .../aws/aws-sdk-go/service/sts/doc.go | 31 - .../aws/aws-sdk-go/service/sts/errors.go | 84 - .../aws/aws-sdk-go/service/sts/service.go | 104 - .../service/sts/stsiface/interface.go | 96 - vendor/github.com/beorn7/perks/LICENSE | 20 - .../beorn7/perks/quantile/exampledata.txt | 2388 - .../beorn7/perks/quantile/stream.go | 316 - .../github.com/cespare/xxhash/v2/LICENSE.txt | 22 - vendor/github.com/cespare/xxhash/v2/README.md | 74 - .../github.com/cespare/xxhash/v2/testall.sh | 10 - vendor/github.com/cespare/xxhash/v2/xxhash.go | 243 - .../cespare/xxhash/v2/xxhash_amd64.s | 209 - .../cespare/xxhash/v2/xxhash_arm64.s | 183 - .../cespare/xxhash/v2/xxhash_asm.go | 15 - .../cespare/xxhash/v2/xxhash_other.go | 76 - .../cespare/xxhash/v2/xxhash_safe.go | 16 - .../cespare/xxhash/v2/xxhash_unsafe.go | 58 - vendor/github.com/davecgh/go-spew/LICENSE | 15 - .../github.com/davecgh/go-spew/spew/bypass.go | 145 - .../davecgh/go-spew/spew/bypasssafe.go | 38 - .../github.com/davecgh/go-spew/spew/common.go | 341 - .../github.com/davecgh/go-spew/spew/config.go | 306 - vendor/github.com/davecgh/go-spew/spew/doc.go | 211 - .../github.com/davecgh/go-spew/spew/dump.go | 509 - .../github.com/davecgh/go-spew/spew/format.go | 419 - .../github.com/davecgh/go-spew/spew/spew.go | 148 - vendor/github.com/getkin/kin-openapi/LICENSE | 21 - .../getkin/kin-openapi/openapi3/callback.go | 54 - .../getkin/kin-openapi/openapi3/components.go | 370 - .../getkin/kin-openapi/openapi3/contact.go | 68 - .../getkin/kin-openapi/openapi3/content.go | 124 - .../kin-openapi/openapi3/discriminator.go | 61 - .../getkin/kin-openapi/openapi3/doc.go | 4 - .../getkin/kin-openapi/openapi3/encoding.go | 148 - .../getkin/kin-openapi/openapi3/errors.go | 59 - .../getkin/kin-openapi/openapi3/example.go | 85 - .../openapi3/example_validation.go | 16 - .../getkin/kin-openapi/openapi3/extension.go | 32 - .../kin-openapi/openapi3/external_docs.go | 73 - .../getkin/kin-openapi/openapi3/header.go | 96 - .../getkin/kin-openapi/openapi3/helpers.go | 261 - .../getkin/kin-openapi/openapi3/info.go | 103 - .../kin-openapi/openapi3/internalize_refs.go | 546 - .../getkin/kin-openapi/openapi3/license.go | 66 - .../getkin/kin-openapi/openapi3/link.go | 94 - .../getkin/kin-openapi/openapi3/loader.go | 1213 - .../kin-openapi/openapi3/loader_uri_reader.go | 116 - .../getkin/kin-openapi/openapi3/maplike.go | 402 - .../getkin/kin-openapi/openapi3/marsh.go | 34 - .../getkin/kin-openapi/openapi3/media_type.go | 179 - .../getkin/kin-openapi/openapi3/openapi3.go | 205 - .../getkin/kin-openapi/openapi3/operation.go | 222 - .../getkin/kin-openapi/openapi3/parameter.go | 416 - .../getkin/kin-openapi/openapi3/path_item.go | 248 - .../getkin/kin-openapi/openapi3/paths.go | 268 - .../getkin/kin-openapi/openapi3/ref.go | 9 - .../getkin/kin-openapi/openapi3/refs.go | 1238 - .../getkin/kin-openapi/openapi3/refs.tmpl | 151 - .../kin-openapi/openapi3/refs_test.tmpl | 54 - .../kin-openapi/openapi3/request_body.go | 138 - .../getkin/kin-openapi/openapi3/response.go | 227 - .../getkin/kin-openapi/openapi3/schema.go | 2246 - .../kin-openapi/openapi3/schema_formats.go | 169 - .../kin-openapi/openapi3/schema_pattern.go | 35 - .../openapi3/schema_validation_settings.go | 92 - .../openapi3/security_requirements.go | 51 - .../kin-openapi/openapi3/security_scheme.go | 429 - .../openapi3/serialization_method.go | 17 - .../getkin/kin-openapi/openapi3/server.go | 302 - .../getkin/kin-openapi/openapi3/tag.go | 99 - .../openapi3/validation_options.go | 142 - .../getkin/kin-openapi/openapi3/visited.go | 41 - .../getkin/kin-openapi/openapi3/xml.go | 78 - .../openapi3filter/authentication_input.go | 29 - .../kin-openapi/openapi3filter/errors.go | 97 - .../kin-openapi/openapi3filter/internal.go | 25 - .../kin-openapi/openapi3filter/middleware.go | 284 - .../kin-openapi/openapi3filter/options.go | 50 - .../openapi3filter/req_resp_decoder.go | 1588 - .../openapi3filter/req_resp_encoder.go | 58 - .../openapi3filter/validate_request.go | 431 - .../openapi3filter/validate_request_input.go | 38 - .../openapi3filter/validate_response.go | 224 - .../openapi3filter/validate_response_input.go | 41 - .../openapi3filter/validation_error.go | 84 - .../validation_error_encoder.go | 186 - .../openapi3filter/validation_handler.go | 107 - .../openapi3filter/validation_kit.go | 85 - .../routers/legacy/pathpattern/node.go | 328 - .../kin-openapi/routers/legacy/router.go | 164 - .../getkin/kin-openapi/routers/types.go | 42 - .../getsentry/sentry-go/.codecov.yml | 13 - .../github.com/getsentry/sentry-go/.craft.yml | 40 - .../getsentry/sentry-go/.gitattributes | 5 - .../github.com/getsentry/sentry-go/.gitignore | 14 - .../getsentry/sentry-go/.golangci.yml | 46 - .../getsentry/sentry-go/CHANGELOG.md | 960 - .../getsentry/sentry-go/CONTRIBUTING.md | 98 - vendor/github.com/getsentry/sentry-go/LICENSE | 21 - .../getsentry/sentry-go/MIGRATION.md | 3 - .../github.com/getsentry/sentry-go/Makefile | 82 - .../github.com/getsentry/sentry-go/README.md | 106 - .../getsentry/sentry-go/check_in.go | 121 - .../github.com/getsentry/sentry-go/client.go | 733 - vendor/github.com/getsentry/sentry-go/doc.go | 6 - vendor/github.com/getsentry/sentry-go/dsn.go | 233 - .../sentry-go/dynamic_sampling_context.go | 154 - .../getsentry/sentry-go/echo/LICENSE | 21 - .../getsentry/sentry-go/echo/README.md | 135 - .../getsentry/sentry-go/echo/sentryecho.go | 158 - vendor/github.com/getsentry/sentry-go/hub.go | 423 - .../getsentry/sentry-go/integrations.go | 391 - .../getsentry/sentry-go/interfaces.go | 549 - .../sentry-go/internal/debug/transport.go | 79 - .../sentry-go/internal/otel/baggage/README.md | 12 - .../internal/otel/baggage/baggage.go | 604 - .../otel/baggage/internal/baggage/baggage.go | 45 - .../sentry-go/internal/ratelimit/category.go | 45 - .../sentry-go/internal/ratelimit/deadline.go | 22 - .../sentry-go/internal/ratelimit/doc.go | 3 - .../sentry-go/internal/ratelimit/map.go | 64 - .../internal/ratelimit/rate_limits.go | 76 - .../internal/ratelimit/retry_after.go | 40 - .../getsentry/sentry-go/logrus/LICENSE | 21 - .../getsentry/sentry-go/logrus/README.md | 91 - .../getsentry/sentry-go/logrus/logrusentry.go | 217 - .../sentry-go/propagation_context.go | 90 - .../github.com/getsentry/sentry-go/scope.go | 486 - .../github.com/getsentry/sentry-go/sentry.go | 132 - .../getsentry/sentry-go/sourcereader.go | 70 - .../getsentry/sentry-go/span_recorder.go | 56 - .../getsentry/sentry-go/stacktrace.go | 407 - .../getsentry/sentry-go/traces_sampler.go | 19 - .../github.com/getsentry/sentry-go/tracing.go | 1028 - .../getsentry/sentry-go/transport.go | 709 - vendor/github.com/getsentry/sentry-go/util.go | 118 - .../go-openapi/jsonpointer/.editorconfig | 26 - .../go-openapi/jsonpointer/.gitignore | 1 - .../go-openapi/jsonpointer/.golangci.yml | 61 - .../go-openapi/jsonpointer/CODE_OF_CONDUCT.md | 74 - .../github.com/go-openapi/jsonpointer/LICENSE | 202 - .../go-openapi/jsonpointer/README.md | 19 - .../go-openapi/jsonpointer/pointer.go | 531 - .../github.com/go-openapi/swag/.editorconfig | 26 - .../github.com/go-openapi/swag/.gitattributes | 2 - vendor/github.com/go-openapi/swag/.gitignore | 5 - .../github.com/go-openapi/swag/.golangci.yml | 60 - .../github.com/go-openapi/swag/BENCHMARK.md | 52 - .../go-openapi/swag/CODE_OF_CONDUCT.md | 74 - vendor/github.com/go-openapi/swag/LICENSE | 202 - vendor/github.com/go-openapi/swag/README.md | 23 - vendor/github.com/go-openapi/swag/convert.go | 208 - .../go-openapi/swag/convert_types.go | 730 - vendor/github.com/go-openapi/swag/doc.go | 31 - vendor/github.com/go-openapi/swag/file.go | 33 - .../go-openapi/swag/initialism_index.go | 202 - vendor/github.com/go-openapi/swag/json.go | 312 - vendor/github.com/go-openapi/swag/loading.go | 176 - .../github.com/go-openapi/swag/name_lexem.go | 93 - vendor/github.com/go-openapi/swag/net.go | 38 - vendor/github.com/go-openapi/swag/path.go | 59 - vendor/github.com/go-openapi/swag/split.go | 508 - .../go-openapi/swag/string_bytes.go | 8 - vendor/github.com/go-openapi/swag/util.go | 364 - vendor/github.com/go-openapi/swag/yaml.go | 481 - vendor/github.com/google/uuid/CHANGELOG.md | 41 - vendor/github.com/google/uuid/CONTRIBUTING.md | 26 - vendor/github.com/google/uuid/CONTRIBUTORS | 9 - vendor/github.com/google/uuid/LICENSE | 27 - vendor/github.com/google/uuid/README.md | 21 - vendor/github.com/google/uuid/dce.go | 80 - vendor/github.com/google/uuid/doc.go | 12 - vendor/github.com/google/uuid/hash.go | 59 - vendor/github.com/google/uuid/marshal.go | 38 - vendor/github.com/google/uuid/node.go | 90 - vendor/github.com/google/uuid/node_js.go | 12 - vendor/github.com/google/uuid/node_net.go | 33 - vendor/github.com/google/uuid/null.go | 118 - vendor/github.com/google/uuid/sql.go | 59 - vendor/github.com/google/uuid/time.go | 134 - vendor/github.com/google/uuid/util.go | 43 - vendor/github.com/google/uuid/uuid.go | 365 - vendor/github.com/google/uuid/version1.go | 44 - vendor/github.com/google/uuid/version4.go | 76 - vendor/github.com/google/uuid/version6.go | 56 - vendor/github.com/google/uuid/version7.go | 104 - .../github.com/hashicorp/go-cleanhttp/LICENSE | 363 - .../hashicorp/go-cleanhttp/README.md | 30 - .../hashicorp/go-cleanhttp/cleanhttp.go | 58 - .../github.com/hashicorp/go-cleanhttp/doc.go | 20 - .../hashicorp/go-cleanhttp/handlers.go | 48 - .../hashicorp/go-retryablehttp/.gitignore | 4 - .../hashicorp/go-retryablehttp/.go-version | 1 - .../hashicorp/go-retryablehttp/CHANGELOG.md | 33 - .../hashicorp/go-retryablehttp/CODEOWNERS | 1 - .../hashicorp/go-retryablehttp/LICENSE | 365 - .../hashicorp/go-retryablehttp/Makefile | 11 - .../hashicorp/go-retryablehttp/README.md | 62 - .../go-retryablehttp/cert_error_go119.go | 14 - .../go-retryablehttp/cert_error_go120.go | 14 - .../hashicorp/go-retryablehttp/client.go | 919 - .../go-retryablehttp/roundtripper.go | 55 - vendor/github.com/invopop/yaml/.gitignore | 20 - vendor/github.com/invopop/yaml/.golangci.toml | 16 - vendor/github.com/invopop/yaml/LICENSE | 50 - vendor/github.com/invopop/yaml/README.md | 128 - vendor/github.com/invopop/yaml/fields.go | 499 - vendor/github.com/invopop/yaml/yaml.go | 312 - vendor/github.com/jackc/pgerrcode/LICENSE | 46 - vendor/github.com/jackc/pgerrcode/README.md | 9 - vendor/github.com/jackc/pgerrcode/errcode.go | 741 - vendor/github.com/jackc/pgerrcode/gen.rb | 108 - .../github.com/jackc/pgpassfile/.travis.yml | 9 - vendor/github.com/jackc/pgpassfile/LICENSE | 22 - vendor/github.com/jackc/pgpassfile/README.md | 8 - vendor/github.com/jackc/pgpassfile/pgpass.go | 110 - vendor/github.com/jackc/pgservicefile/LICENSE | 22 - .../github.com/jackc/pgservicefile/README.md | 7 - .../jackc/pgservicefile/pgservicefile.go | 81 - vendor/github.com/jackc/pgx/v5/.gitignore | 27 - vendor/github.com/jackc/pgx/v5/CHANGELOG.md | 434 - .../github.com/jackc/pgx/v5/CONTRIBUTING.md | 121 - vendor/github.com/jackc/pgx/v5/LICENSE | 22 - vendor/github.com/jackc/pgx/v5/README.md | 174 - vendor/github.com/jackc/pgx/v5/Rakefile | 18 - vendor/github.com/jackc/pgx/v5/batch.go | 443 - vendor/github.com/jackc/pgx/v5/conn.go | 1444 - vendor/github.com/jackc/pgx/v5/copy_from.go | 276 - .../github.com/jackc/pgx/v5/derived_types.go | 262 - vendor/github.com/jackc/pgx/v5/doc.go | 194 - .../jackc/pgx/v5/extended_query_builder.go | 146 - .../pgx/v5/internal/iobufpool/iobufpool.go | 70 - .../jackc/pgx/v5/internal/pgio/README.md | 6 - .../jackc/pgx/v5/internal/pgio/doc.go | 6 - .../jackc/pgx/v5/internal/pgio/write.go | 40 - .../pgx/v5/internal/sanitize/sanitize.go | 331 - .../pgx/v5/internal/stmtcache/lru_cache.go | 112 - .../pgx/v5/internal/stmtcache/stmtcache.go | 45 - .../v5/internal/stmtcache/unlimited_cache.go | 77 - .../github.com/jackc/pgx/v5/large_objects.go | 161 - vendor/github.com/jackc/pgx/v5/named_args.go | 295 - .../github.com/jackc/pgx/v5/pgconn/README.md | 29 - .../jackc/pgx/v5/pgconn/auth_scram.go | 272 - .../github.com/jackc/pgx/v5/pgconn/config.go | 934 - .../pgx/v5/pgconn/ctxwatch/context_watcher.go | 80 - .../jackc/pgx/v5/pgconn/defaults.go | 63 - .../jackc/pgx/v5/pgconn/defaults_windows.go | 57 - vendor/github.com/jackc/pgx/v5/pgconn/doc.go | 38 - .../github.com/jackc/pgx/v5/pgconn/errors.go | 248 - .../v5/pgconn/internal/bgreader/bgreader.go | 139 - vendor/github.com/jackc/pgx/v5/pgconn/krb5.go | 100 - .../github.com/jackc/pgx/v5/pgconn/pgconn.go | 2346 - .../jackc/pgx/v5/pgproto3/README.md | 7 - .../authentication_cleartext_password.go | 51 - .../pgx/v5/pgproto3/authentication_gss.go | 58 - .../pgproto3/authentication_gss_continue.go | 67 - .../pgproto3/authentication_md5_password.go | 76 - .../pgx/v5/pgproto3/authentication_ok.go | 51 - .../pgx/v5/pgproto3/authentication_sasl.go | 72 - .../pgproto3/authentication_sasl_continue.go | 75 - .../v5/pgproto3/authentication_sasl_final.go | 75 - .../jackc/pgx/v5/pgproto3/backend.go | 299 - .../jackc/pgx/v5/pgproto3/backend_key_data.go | 50 - .../jackc/pgx/v5/pgproto3/big_endian.go | 37 - .../github.com/jackc/pgx/v5/pgproto3/bind.go | 223 - .../jackc/pgx/v5/pgproto3/bind_complete.go | 34 - .../jackc/pgx/v5/pgproto3/cancel_request.go | 58 - .../jackc/pgx/v5/pgproto3/chunkreader.go | 90 - .../github.com/jackc/pgx/v5/pgproto3/close.go | 81 - .../jackc/pgx/v5/pgproto3/close_complete.go | 34 - .../jackc/pgx/v5/pgproto3/command_complete.go | 66 - .../pgx/v5/pgproto3/copy_both_response.go | 95 - .../jackc/pgx/v5/pgproto3/copy_data.go | 59 - .../jackc/pgx/v5/pgproto3/copy_done.go | 38 - .../jackc/pgx/v5/pgproto3/copy_fail.go | 45 - .../jackc/pgx/v5/pgproto3/copy_in_response.go | 96 - .../pgx/v5/pgproto3/copy_out_response.go | 96 - .../jackc/pgx/v5/pgproto3/data_row.go | 143 - .../jackc/pgx/v5/pgproto3/describe.go | 80 - .../github.com/jackc/pgx/v5/pgproto3/doc.go | 11 - .../pgx/v5/pgproto3/empty_query_response.go | 34 - .../jackc/pgx/v5/pgproto3/error_response.go | 326 - .../jackc/pgx/v5/pgproto3/execute.go | 58 - .../github.com/jackc/pgx/v5/pgproto3/flush.go | 34 - .../jackc/pgx/v5/pgproto3/frontend.go | 468 - .../jackc/pgx/v5/pgproto3/function_call.go | 102 - .../pgx/v5/pgproto3/function_call_response.go | 97 - .../jackc/pgx/v5/pgproto3/gss_enc_request.go | 49 - .../jackc/pgx/v5/pgproto3/gss_response.go | 46 - .../jackc/pgx/v5/pgproto3/no_data.go | 34 - .../jackc/pgx/v5/pgproto3/notice_response.go | 19 - .../pgx/v5/pgproto3/notification_response.go | 71 - .../pgx/v5/pgproto3/parameter_description.go | 67 - .../jackc/pgx/v5/pgproto3/parameter_status.go | 58 - .../github.com/jackc/pgx/v5/pgproto3/parse.go | 89 - .../jackc/pgx/v5/pgproto3/parse_complete.go | 34 - .../jackc/pgx/v5/pgproto3/password_message.go | 49 - .../jackc/pgx/v5/pgproto3/pgproto3.go | 120 - .../jackc/pgx/v5/pgproto3/portal_suspended.go | 34 - .../github.com/jackc/pgx/v5/pgproto3/query.go | 45 - .../jackc/pgx/v5/pgproto3/ready_for_query.go | 61 - .../jackc/pgx/v5/pgproto3/row_description.go | 166 - .../pgx/v5/pgproto3/sasl_initial_response.go | 90 - .../jackc/pgx/v5/pgproto3/sasl_response.go | 56 - .../jackc/pgx/v5/pgproto3/ssl_request.go | 49 - .../jackc/pgx/v5/pgproto3/startup_message.go | 94 - .../github.com/jackc/pgx/v5/pgproto3/sync.go | 34 - .../jackc/pgx/v5/pgproto3/terminate.go | 34 - .../github.com/jackc/pgx/v5/pgproto3/trace.go | 416 - .../github.com/jackc/pgx/v5/pgtype/array.go | 460 - .../jackc/pgx/v5/pgtype/array_codec.go | 405 - vendor/github.com/jackc/pgx/v5/pgtype/bits.go | 210 - vendor/github.com/jackc/pgx/v5/pgtype/bool.go | 343 - vendor/github.com/jackc/pgx/v5/pgtype/box.go | 238 - .../jackc/pgx/v5/pgtype/builtin_wrappers.go | 952 - .../github.com/jackc/pgx/v5/pgtype/bytea.go | 255 - .../github.com/jackc/pgx/v5/pgtype/circle.go | 222 - .../jackc/pgx/v5/pgtype/composite.go | 602 - .../github.com/jackc/pgx/v5/pgtype/convert.go | 108 - vendor/github.com/jackc/pgx/v5/pgtype/date.go | 351 - vendor/github.com/jackc/pgx/v5/pgtype/doc.go | 191 - .../jackc/pgx/v5/pgtype/enum_codec.go | 109 - .../github.com/jackc/pgx/v5/pgtype/float4.go | 319 - .../github.com/jackc/pgx/v5/pgtype/float8.go | 365 - .../github.com/jackc/pgx/v5/pgtype/hstore.go | 486 - vendor/github.com/jackc/pgx/v5/pgtype/inet.go | 200 - vendor/github.com/jackc/pgx/v5/pgtype/int.go | 1980 - .../github.com/jackc/pgx/v5/pgtype/int.go.erb | 548 - .../jackc/pgx/v5/pgtype/int_test.go.erb | 93 - .../pgtype/integration_benchmark_test.go.erb | 62 - .../pgtype/integration_benchmark_test_gen.sh | 2 - .../jackc/pgx/v5/pgtype/interval.go | 297 - vendor/github.com/jackc/pgx/v5/pgtype/json.go | 239 - .../github.com/jackc/pgx/v5/pgtype/jsonb.go | 129 - vendor/github.com/jackc/pgx/v5/pgtype/line.go | 225 - vendor/github.com/jackc/pgx/v5/pgtype/lseg.go | 238 - .../github.com/jackc/pgx/v5/pgtype/ltree.go | 122 - .../github.com/jackc/pgx/v5/pgtype/macaddr.go | 162 - .../jackc/pgx/v5/pgtype/multirange.go | 443 - .../github.com/jackc/pgx/v5/pgtype/numeric.go | 823 - vendor/github.com/jackc/pgx/v5/pgtype/path.go | 272 - .../github.com/jackc/pgx/v5/pgtype/pgtype.go | 2104 - .../jackc/pgx/v5/pgtype/pgtype_default.go | 231 - .../github.com/jackc/pgx/v5/pgtype/point.go | 266 - .../github.com/jackc/pgx/v5/pgtype/polygon.go | 253 - .../github.com/jackc/pgx/v5/pgtype/qchar.go | 141 - .../github.com/jackc/pgx/v5/pgtype/range.go | 322 - .../jackc/pgx/v5/pgtype/range_codec.go | 379 - .../jackc/pgx/v5/pgtype/record_codec.go | 125 - .../v5/pgtype/register_default_pg_types.go | 35 - .../register_default_pg_types_disabled.go | 6 - vendor/github.com/jackc/pgx/v5/pgtype/text.go | 223 - .../pgx/v5/pgtype/text_format_only_codec.go | 13 - vendor/github.com/jackc/pgx/v5/pgtype/tid.go | 241 - vendor/github.com/jackc/pgx/v5/pgtype/time.go | 274 - .../jackc/pgx/v5/pgtype/timestamp.go | 355 - .../jackc/pgx/v5/pgtype/timestamptz.go | 366 - .../github.com/jackc/pgx/v5/pgtype/uint32.go | 325 - .../github.com/jackc/pgx/v5/pgtype/uint64.go | 322 - vendor/github.com/jackc/pgx/v5/pgtype/uuid.go | 289 - vendor/github.com/jackc/pgx/v5/pgtype/xml.go | 198 - .../jackc/pgx/v5/pgxpool/batch_results.go | 52 - .../github.com/jackc/pgx/v5/pgxpool/conn.go | 134 - vendor/github.com/jackc/pgx/v5/pgxpool/doc.go | 27 - .../github.com/jackc/pgx/v5/pgxpool/pool.go | 717 - .../github.com/jackc/pgx/v5/pgxpool/rows.go | 116 - .../github.com/jackc/pgx/v5/pgxpool/stat.go | 84 - .../github.com/jackc/pgx/v5/pgxpool/tracer.go | 33 - vendor/github.com/jackc/pgx/v5/pgxpool/tx.go | 83 - vendor/github.com/jackc/pgx/v5/rows.go | 856 - vendor/github.com/jackc/pgx/v5/tracer.go | 107 - vendor/github.com/jackc/pgx/v5/tx.go | 443 - vendor/github.com/jackc/pgx/v5/values.go | 63 - .../github.com/jackc/puddle/v2/CHANGELOG.md | 79 - vendor/github.com/jackc/puddle/v2/LICENSE | 22 - vendor/github.com/jackc/puddle/v2/README.md | 80 - vendor/github.com/jackc/puddle/v2/context.go | 24 - vendor/github.com/jackc/puddle/v2/doc.go | 11 - .../puddle/v2/internal/genstack/gen_stack.go | 85 - .../puddle/v2/internal/genstack/stack.go | 39 - vendor/github.com/jackc/puddle/v2/log.go | 32 - vendor/github.com/jackc/puddle/v2/nanotime.go | 16 - vendor/github.com/jackc/puddle/v2/pool.go | 710 - .../jackc/puddle/v2/resource_list.go | 28 - .../jmespath/go-jmespath/.gitignore | 4 - .../jmespath/go-jmespath/.travis.yml | 28 - .../github.com/jmespath/go-jmespath/LICENSE | 13 - .../github.com/jmespath/go-jmespath/Makefile | 51 - .../github.com/jmespath/go-jmespath/README.md | 87 - vendor/github.com/jmespath/go-jmespath/api.go | 49 - .../go-jmespath/astnodetype_string.go | 16 - .../jmespath/go-jmespath/functions.go | 842 - .../jmespath/go-jmespath/interpreter.go | 418 - .../github.com/jmespath/go-jmespath/lexer.go | 420 - .../github.com/jmespath/go-jmespath/parser.go | 603 - .../jmespath/go-jmespath/toktype_string.go | 16 - .../github.com/jmespath/go-jmespath/util.go | 185 - vendor/github.com/joho/godotenv/.gitignore | 1 - vendor/github.com/joho/godotenv/LICENCE | 23 - vendor/github.com/joho/godotenv/README.md | 202 - vendor/github.com/joho/godotenv/godotenv.go | 228 - vendor/github.com/joho/godotenv/parser.go | 271 - vendor/github.com/josharian/intern/README.md | 5 - vendor/github.com/josharian/intern/intern.go | 44 - vendor/github.com/josharian/intern/license.md | 21 - .../klauspost/compress/.gitattributes | 2 - .../github.com/klauspost/compress/.gitignore | 32 - .../klauspost/compress/.goreleaser.yml | 123 - vendor/github.com/klauspost/compress/LICENSE | 304 - .../github.com/klauspost/compress/README.md | 700 - .../github.com/klauspost/compress/SECURITY.md | 25 - .../klauspost/compress/compressible.go | 85 - .../klauspost/compress/fse/README.md | 79 - .../klauspost/compress/fse/bitreader.go | 122 - .../klauspost/compress/fse/bitwriter.go | 167 - .../klauspost/compress/fse/bytereader.go | 47 - .../klauspost/compress/fse/compress.go | 683 - .../klauspost/compress/fse/decompress.go | 376 - .../github.com/klauspost/compress/fse/fse.go | 144 - vendor/github.com/klauspost/compress/gen.sh | 4 - .../klauspost/compress/huff0/.gitignore | 1 - .../klauspost/compress/huff0/README.md | 89 - .../klauspost/compress/huff0/bitreader.go | 229 - .../klauspost/compress/huff0/bitwriter.go | 102 - .../klauspost/compress/huff0/compress.go | 742 - .../klauspost/compress/huff0/decompress.go | 1167 - .../compress/huff0/decompress_amd64.go | 226 - .../compress/huff0/decompress_amd64.s | 830 - .../compress/huff0/decompress_generic.go | 299 - .../klauspost/compress/huff0/huff0.go | 337 - .../compress/internal/cpuinfo/cpuinfo.go | 34 - .../internal/cpuinfo/cpuinfo_amd64.go | 11 - .../compress/internal/cpuinfo/cpuinfo_amd64.s | 36 - .../compress/internal/snapref/LICENSE | 27 - .../compress/internal/snapref/decode.go | 264 - .../compress/internal/snapref/decode_other.go | 113 - .../compress/internal/snapref/encode.go | 289 - .../compress/internal/snapref/encode_other.go | 250 - .../compress/internal/snapref/snappy.go | 98 - vendor/github.com/klauspost/compress/s2sx.mod | 4 - vendor/github.com/klauspost/compress/s2sx.sum | 0 .../klauspost/compress/zstd/README.md | 441 - .../klauspost/compress/zstd/bitreader.go | 136 - .../klauspost/compress/zstd/bitwriter.go | 112 - .../klauspost/compress/zstd/blockdec.go | 729 - .../klauspost/compress/zstd/blockenc.go | 909 - .../compress/zstd/blocktype_string.go | 85 - .../klauspost/compress/zstd/bytebuf.go | 131 - .../klauspost/compress/zstd/bytereader.go | 82 - .../klauspost/compress/zstd/decodeheader.go | 261 - .../klauspost/compress/zstd/decoder.go | 948 - .../compress/zstd/decoder_options.go | 169 - .../klauspost/compress/zstd/dict.go | 565 - .../klauspost/compress/zstd/enc_base.go | 173 - .../klauspost/compress/zstd/enc_best.go | 560 - .../klauspost/compress/zstd/enc_better.go | 1252 - .../klauspost/compress/zstd/enc_dfast.go | 1123 - .../klauspost/compress/zstd/enc_fast.go | 891 - .../klauspost/compress/zstd/encoder.go | 619 - .../compress/zstd/encoder_options.go | 339 - .../klauspost/compress/zstd/framedec.go | 413 - .../klauspost/compress/zstd/frameenc.go | 137 - .../klauspost/compress/zstd/fse_decoder.go | 307 - .../compress/zstd/fse_decoder_amd64.go | 65 - .../compress/zstd/fse_decoder_amd64.s | 126 - .../compress/zstd/fse_decoder_generic.go | 73 - .../klauspost/compress/zstd/fse_encoder.go | 701 - .../klauspost/compress/zstd/fse_predefined.go | 158 - .../klauspost/compress/zstd/hash.go | 35 - .../klauspost/compress/zstd/history.go | 116 - .../compress/zstd/internal/xxhash/LICENSE.txt | 22 - .../compress/zstd/internal/xxhash/README.md | 71 - .../compress/zstd/internal/xxhash/xxhash.go | 230 - .../zstd/internal/xxhash/xxhash_amd64.s | 210 - .../zstd/internal/xxhash/xxhash_arm64.s | 184 - .../zstd/internal/xxhash/xxhash_asm.go | 16 - .../zstd/internal/xxhash/xxhash_other.go | 76 - .../zstd/internal/xxhash/xxhash_safe.go | 11 - .../klauspost/compress/zstd/matchlen_amd64.go | 16 - .../klauspost/compress/zstd/matchlen_amd64.s | 66 - .../compress/zstd/matchlen_generic.go | 33 - .../klauspost/compress/zstd/seqdec.go | 503 - .../klauspost/compress/zstd/seqdec_amd64.go | 394 - .../klauspost/compress/zstd/seqdec_amd64.s | 4151 -- .../klauspost/compress/zstd/seqdec_generic.go | 237 - .../klauspost/compress/zstd/seqenc.go | 114 - .../klauspost/compress/zstd/snappy.go | 434 - .../github.com/klauspost/compress/zstd/zip.go | 141 - .../klauspost/compress/zstd/zstd.go | 121 - .../github.com/labstack/echo/v4/.editorconfig | 25 - .../labstack/echo/v4/.gitattributes | 20 - vendor/github.com/labstack/echo/v4/.gitignore | 8 - .../github.com/labstack/echo/v4/CHANGELOG.md | 538 - vendor/github.com/labstack/echo/v4/LICENSE | 21 - vendor/github.com/labstack/echo/v4/Makefile | 36 - vendor/github.com/labstack/echo/v4/README.md | 158 - vendor/github.com/labstack/echo/v4/bind.go | 466 - vendor/github.com/labstack/echo/v4/binder.go | 1333 - .../github.com/labstack/echo/v4/codecov.yml | 11 - vendor/github.com/labstack/echo/v4/context.go | 660 - .../github.com/labstack/echo/v4/context_fs.go | 52 - vendor/github.com/labstack/echo/v4/echo.go | 1015 - vendor/github.com/labstack/echo/v4/echo_fs.go | 162 - vendor/github.com/labstack/echo/v4/group.go | 129 - .../github.com/labstack/echo/v4/group_fs.go | 33 - vendor/github.com/labstack/echo/v4/ip.go | 277 - vendor/github.com/labstack/echo/v4/json.go | 34 - vendor/github.com/labstack/echo/v4/log.go | 41 - .../labstack/echo/v4/middleware/basic_auth.go | 111 - .../labstack/echo/v4/middleware/body_dump.go | 113 - .../labstack/echo/v4/middleware/body_limit.go | 114 - .../labstack/echo/v4/middleware/compress.go | 230 - .../echo/v4/middleware/context_timeout.go | 75 - .../labstack/echo/v4/middleware/cors.go | 307 - .../labstack/echo/v4/middleware/csrf.go | 218 - .../labstack/echo/v4/middleware/decompress.go | 98 - .../labstack/echo/v4/middleware/extractor.go | 207 - .../labstack/echo/v4/middleware/key_auth.go | 179 - .../labstack/echo/v4/middleware/logger.go | 244 - .../echo/v4/middleware/method_override.go | 91 - .../labstack/echo/v4/middleware/middleware.go | 90 - .../labstack/echo/v4/middleware/proxy.go | 421 - .../echo/v4/middleware/rate_limiter.go | 267 - .../labstack/echo/v4/middleware/recover.go | 133 - .../labstack/echo/v4/middleware/redirect.go | 155 - .../labstack/echo/v4/middleware/request_id.go | 75 - .../echo/v4/middleware/request_logger.go | 391 - .../labstack/echo/v4/middleware/rewrite.go | 80 - .../labstack/echo/v4/middleware/secure.go | 144 - .../labstack/echo/v4/middleware/slash.go | 129 - .../labstack/echo/v4/middleware/static.go | 270 - .../echo/v4/middleware/static_other.go | 15 - .../echo/v4/middleware/static_windows.go | 26 - .../labstack/echo/v4/middleware/timeout.go | 221 - .../labstack/echo/v4/middleware/util.go | 103 - .../github.com/labstack/echo/v4/renderer.go | 29 - .../github.com/labstack/echo/v4/response.go | 116 - vendor/github.com/labstack/echo/v4/router.go | 760 - vendor/github.com/labstack/gommon/LICENSE | 22 - .../labstack/gommon/bytes/README.md | 29 - .../github.com/labstack/gommon/bytes/bytes.go | 216 - .../labstack/gommon/color/README.md | 86 - .../github.com/labstack/gommon/color/color.go | 407 - .../github.com/labstack/gommon/log/README.md | 5 - .../github.com/labstack/gommon/log/color.go | 13 - vendor/github.com/labstack/gommon/log/log.go | 418 - .../github.com/labstack/gommon/log/white.go | 12 - .../labstack/gommon/random/random.go | 86 - vendor/github.com/mailru/easyjson/LICENSE | 7 - .../github.com/mailru/easyjson/buffer/pool.go | 278 - .../mailru/easyjson/jlexer/bytestostr.go | 24 - .../easyjson/jlexer/bytestostr_nounsafe.go | 13 - .../mailru/easyjson/jlexer/error.go | 15 - .../mailru/easyjson/jlexer/lexer.go | 1244 - .../mailru/easyjson/jwriter/writer.go | 405 - vendor/github.com/mattn/go-colorable/LICENSE | 21 - .../github.com/mattn/go-colorable/README.md | 48 - .../mattn/go-colorable/colorable_appengine.go | 38 - .../mattn/go-colorable/colorable_others.go | 38 - .../mattn/go-colorable/colorable_windows.go | 1047 - .../github.com/mattn/go-colorable/go.test.sh | 12 - .../mattn/go-colorable/noncolorable.go | 57 - vendor/github.com/mattn/go-isatty/LICENSE | 9 - vendor/github.com/mattn/go-isatty/README.md | 50 - vendor/github.com/mattn/go-isatty/doc.go | 2 - vendor/github.com/mattn/go-isatty/go.test.sh | 12 - .../github.com/mattn/go-isatty/isatty_bsd.go | 20 - .../mattn/go-isatty/isatty_others.go | 17 - .../mattn/go-isatty/isatty_plan9.go | 23 - .../mattn/go-isatty/isatty_solaris.go | 21 - .../mattn/go-isatty/isatty_tcgets.go | 20 - .../mattn/go-isatty/isatty_windows.go | 125 - vendor/github.com/mohae/deepcopy/.gitignore | 26 - vendor/github.com/mohae/deepcopy/.travis.yml | 11 - vendor/github.com/mohae/deepcopy/LICENSE | 21 - vendor/github.com/mohae/deepcopy/README.md | 8 - vendor/github.com/mohae/deepcopy/deepcopy.go | 125 - vendor/github.com/munnerz/goautoneg/LICENSE | 31 - vendor/github.com/munnerz/goautoneg/Makefile | 13 - .../github.com/munnerz/goautoneg/README.txt | 67 - .../github.com/munnerz/goautoneg/autoneg.go | 189 - .../oapi-codegen/runtime/.gitignore | 1 - .../github.com/oapi-codegen/runtime/LICENSE | 201 - .../github.com/oapi-codegen/runtime/Makefile | 32 - .../github.com/oapi-codegen/runtime/README.md | 6 - .../github.com/oapi-codegen/runtime/bind.go | 24 - .../oapi-codegen/runtime/bindform.go | 318 - .../oapi-codegen/runtime/bindparam.go | 555 - .../oapi-codegen/runtime/bindstring.go | 174 - .../oapi-codegen/runtime/deepobject.go | 371 - .../oapi-codegen/runtime/jsonmerge.go | 34 - .../oapi-codegen/runtime/renovate.json | 6 - .../oapi-codegen/runtime/styleparam.go | 478 - .../oapi-codegen/runtime/types/date.go | 43 - .../oapi-codegen/runtime/types/email.go | 40 - .../oapi-codegen/runtime/types/file.go | 71 - .../oapi-codegen/runtime/types/regexes.go | 11 - .../oapi-codegen/runtime/types/uuid.go | 7 - .../community-gateway/oidc-authorizer/LICENSE | 201 - .../oidc-authorizer/pkg/identity/identity.go | 36 - .../pkg/identity/middleware.go | 39 - vendor/github.com/osbuild/images/LICENSE | 201 - .../osbuild/images/pkg/crypt/crypt.go | 59 - .../osbuild/images/pkg/crypt/crypt_impl.go | 87 - .../images/pkg/crypt/crypt_impl_macos.go | 7 - .../pkg/splunk_logger/LICENSE | 201 - .../pkg/splunk_logger/environment_hook.go | 26 - .../pkg/splunk_logger/splunk_hook.go | 45 - .../pkg/splunk_logger/splunk_logger.go | 154 - .../perimeterx/marshmallow/.gitignore | 4 - .../perimeterx/marshmallow/CHANGELOG.md | 49 - .../perimeterx/marshmallow/CODE_OF_CONDUCT.md | 133 - .../perimeterx/marshmallow/CONTRIBUTING.md | 47 - .../github.com/perimeterx/marshmallow/LICENSE | 21 - .../perimeterx/marshmallow/README.md | 205 - .../perimeterx/marshmallow/cache.go | 63 - .../github.com/perimeterx/marshmallow/doc.go | 10 - .../perimeterx/marshmallow/errors.go | 101 - .../perimeterx/marshmallow/options.go | 96 - .../perimeterx/marshmallow/reflection.go | 197 - .../perimeterx/marshmallow/unmarshal.go | 383 - .../marshmallow/unmarshal_from_json_map.go | 295 - vendor/github.com/pmezard/go-difflib/LICENSE | 27 - .../pmezard/go-difflib/difflib/difflib.go | 772 - .../prometheus/client_golang/LICENSE | 201 - .../prometheus/client_golang/NOTICE | 18 - .../internal/github.com/golang/gddo/LICENSE | 27 - .../golang/gddo/httputil/header/header.go | 145 - .../golang/gddo/httputil/negotiate.go | 36 - .../client_golang/prometheus/.gitignore | 1 - .../client_golang/prometheus/README.md | 1 - .../prometheus/build_info_collector.go | 38 - .../client_golang/prometheus/collector.go | 128 - .../client_golang/prometheus/counter.go | 358 - .../client_golang/prometheus/desc.go | 207 - .../client_golang/prometheus/doc.go | 210 - .../prometheus/expvar_collector.go | 86 - .../client_golang/prometheus/fnv.go | 42 - .../client_golang/prometheus/gauge.go | 311 - .../client_golang/prometheus/get_pid.go | 26 - .../prometheus/get_pid_gopherjs.go | 23 - .../client_golang/prometheus/go_collector.go | 274 - .../prometheus/go_collector_go116.go | 122 - .../prometheus/go_collector_latest.go | 574 - .../client_golang/prometheus/histogram.go | 1837 - .../prometheus/internal/almost_equal.go | 60 - .../prometheus/internal/difflib.go | 654 - .../internal/go_collector_options.go | 34 - .../prometheus/internal/go_runtime_metrics.go | 142 - .../prometheus/internal/metric.go | 101 - .../client_golang/prometheus/labels.go | 188 - .../client_golang/prometheus/metric.go | 257 - .../client_golang/prometheus/num_threads.go | 25 - .../prometheus/num_threads_gopherjs.go | 22 - .../client_golang/prometheus/observer.go | 64 - .../prometheus/process_collector.go | 177 - .../prometheus/process_collector_js.go | 26 - .../prometheus/process_collector_other.go | 80 - .../prometheus/process_collector_wasip1.go | 26 - .../prometheus/process_collector_windows.go | 116 - .../client_golang/prometheus/promauto/auto.go | 376 - .../prometheus/promhttp/delegator.go | 380 - .../client_golang/prometheus/promhttp/http.go | 467 - .../prometheus/promhttp/instrument_client.go | 249 - .../prometheus/promhttp/instrument_server.go | 576 - .../prometheus/promhttp/option.go | 84 - .../client_golang/prometheus/registry.go | 1076 - .../client_golang/prometheus/summary.go | 827 - .../client_golang/prometheus/timer.go | 81 - .../client_golang/prometheus/untyped.go | 42 - .../client_golang/prometheus/value.go | 274 - .../client_golang/prometheus/vec.go | 709 - .../client_golang/prometheus/vnext.go | 23 - .../client_golang/prometheus/wrap.go | 214 - .../prometheus/client_model/LICENSE | 201 - .../github.com/prometheus/client_model/NOTICE | 5 - .../prometheus/client_model/go/metrics.pb.go | 1399 - vendor/github.com/prometheus/common/LICENSE | 201 - vendor/github.com/prometheus/common/NOTICE | 5 - .../prometheus/common/expfmt/decode.go | 431 - .../prometheus/common/expfmt/encode.go | 198 - .../prometheus/common/expfmt/expfmt.go | 177 - .../prometheus/common/expfmt/fuzz.go | 37 - .../common/expfmt/openmetrics_create.go | 696 - .../prometheus/common/expfmt/text_create.go | 520 - .../prometheus/common/expfmt/text_parse.go | 781 - .../prometheus/common/model/alert.go | 161 - .../prometheus/common/model/fingerprinting.go | 105 - .../github.com/prometheus/common/model/fnv.go | 42 - .../prometheus/common/model/labels.go | 226 - .../prometheus/common/model/labelset.go | 158 - .../common/model/labelset_string.go | 45 - .../common/model/labelset_string_go120.go | 39 - .../prometheus/common/model/metadata.go | 28 - .../prometheus/common/model/metric.go | 457 - .../prometheus/common/model/model.go | 16 - .../prometheus/common/model/signature.go | 142 - .../prometheus/common/model/silence.go | 106 - .../prometheus/common/model/time.go | 340 - .../prometheus/common/model/value.go | 364 - .../prometheus/common/model/value_float.go | 98 - .../common/model/value_histogram.go | 178 - .../prometheus/common/model/value_type.go | 83 - .../github.com/prometheus/procfs/.gitignore | 2 - .../prometheus/procfs/.golangci.yml | 22 - .../prometheus/procfs/CODE_OF_CONDUCT.md | 3 - .../prometheus/procfs/CONTRIBUTING.md | 121 - vendor/github.com/prometheus/procfs/LICENSE | 201 - .../prometheus/procfs/MAINTAINERS.md | 3 - vendor/github.com/prometheus/procfs/Makefile | 31 - .../prometheus/procfs/Makefile.common | 277 - vendor/github.com/prometheus/procfs/NOTICE | 7 - vendor/github.com/prometheus/procfs/README.md | 61 - .../github.com/prometheus/procfs/SECURITY.md | 6 - vendor/github.com/prometheus/procfs/arp.go | 116 - .../github.com/prometheus/procfs/buddyinfo.go | 85 - .../github.com/prometheus/procfs/cmdline.go | 30 - .../github.com/prometheus/procfs/cpuinfo.go | 519 - .../prometheus/procfs/cpuinfo_armx.go | 20 - .../prometheus/procfs/cpuinfo_loong64.go | 19 - .../prometheus/procfs/cpuinfo_mipsx.go | 20 - .../prometheus/procfs/cpuinfo_others.go | 19 - .../prometheus/procfs/cpuinfo_ppcx.go | 20 - .../prometheus/procfs/cpuinfo_riscvx.go | 20 - .../prometheus/procfs/cpuinfo_s390x.go | 19 - .../prometheus/procfs/cpuinfo_x86.go | 20 - vendor/github.com/prometheus/procfs/crypto.go | 154 - vendor/github.com/prometheus/procfs/doc.go | 44 - vendor/github.com/prometheus/procfs/fs.go | 50 - .../prometheus/procfs/fs_statfs_notype.go | 23 - .../prometheus/procfs/fs_statfs_type.go | 33 - .../github.com/prometheus/procfs/fscache.go | 422 - .../prometheus/procfs/internal/fs/fs.go | 55 - .../prometheus/procfs/internal/util/parse.go | 112 - .../procfs/internal/util/readfile.go | 37 - .../procfs/internal/util/sysreadfile.go | 50 - .../internal/util/sysreadfile_compat.go | 27 - .../procfs/internal/util/valueparser.go | 91 - vendor/github.com/prometheus/procfs/ipvs.go | 241 - .../prometheus/procfs/kernel_random.go | 63 - .../github.com/prometheus/procfs/loadavg.go | 62 - vendor/github.com/prometheus/procfs/mdstat.go | 276 - .../github.com/prometheus/procfs/meminfo.go | 389 - .../github.com/prometheus/procfs/mountinfo.go | 180 - .../prometheus/procfs/mountstats.go | 707 - .../prometheus/procfs/net_conntrackstat.go | 118 - .../github.com/prometheus/procfs/net_dev.go | 205 - .../prometheus/procfs/net_ip_socket.go | 248 - .../prometheus/procfs/net_protocols.go | 180 - .../github.com/prometheus/procfs/net_route.go | 143 - .../prometheus/procfs/net_sockstat.go | 162 - .../prometheus/procfs/net_softnet.go | 155 - .../github.com/prometheus/procfs/net_tcp.go | 64 - .../prometheus/procfs/net_tls_stat.go | 119 - .../github.com/prometheus/procfs/net_udp.go | 64 - .../github.com/prometheus/procfs/net_unix.go | 257 - .../prometheus/procfs/net_wireless.go | 182 - .../github.com/prometheus/procfs/net_xfrm.go | 189 - .../github.com/prometheus/procfs/netstat.go | 82 - vendor/github.com/prometheus/procfs/proc.go | 338 - .../prometheus/procfs/proc_cgroup.go | 98 - .../prometheus/procfs/proc_cgroups.go | 98 - .../prometheus/procfs/proc_environ.go | 37 - .../prometheus/procfs/proc_fdinfo.go | 138 - .../prometheus/procfs/proc_interrupts.go | 98 - .../github.com/prometheus/procfs/proc_io.go | 59 - .../prometheus/procfs/proc_limits.go | 160 - .../github.com/prometheus/procfs/proc_maps.go | 211 - .../prometheus/procfs/proc_netstat.go | 443 - .../github.com/prometheus/procfs/proc_ns.go | 68 - .../github.com/prometheus/procfs/proc_psi.go | 102 - .../prometheus/procfs/proc_smaps.go | 166 - .../github.com/prometheus/procfs/proc_snmp.go | 353 - .../prometheus/procfs/proc_snmp6.go | 381 - .../github.com/prometheus/procfs/proc_stat.go | 229 - .../prometheus/procfs/proc_status.go | 238 - .../github.com/prometheus/procfs/proc_sys.go | 51 - .../github.com/prometheus/procfs/schedstat.go | 121 - vendor/github.com/prometheus/procfs/slab.go | 151 - .../github.com/prometheus/procfs/softirqs.go | 160 - vendor/github.com/prometheus/procfs/stat.go | 258 - vendor/github.com/prometheus/procfs/swaps.go | 89 - vendor/github.com/prometheus/procfs/thread.go | 80 - vendor/github.com/prometheus/procfs/ttar | 413 - vendor/github.com/prometheus/procfs/vm.go | 212 - .../github.com/prometheus/procfs/zoneinfo.go | 196 - .../app-common-go/pkg/api/v1/config.go | 141 - .../app-common-go/pkg/api/v1/schema.json | 545 - .../app-common-go/pkg/api/v1/types.go | 711 - .../redhatinsights/identity/README.md | 32 - .../redhatinsights/identity/identity.go | 168 - .../platform-go-middlewares/logging/LICENSE | 21 - .../logging/cloudwatch/LICENSE | 19 - .../logging/cloudwatch/hook.go | 279 - vendor/github.com/sirupsen/logrus/.gitignore | 4 - .../github.com/sirupsen/logrus/.golangci.yml | 40 - vendor/github.com/sirupsen/logrus/.travis.yml | 15 - .../github.com/sirupsen/logrus/CHANGELOG.md | 259 - vendor/github.com/sirupsen/logrus/LICENSE | 21 - vendor/github.com/sirupsen/logrus/README.md | 515 - vendor/github.com/sirupsen/logrus/alt_exit.go | 76 - .../github.com/sirupsen/logrus/appveyor.yml | 14 - .../github.com/sirupsen/logrus/buffer_pool.go | 43 - vendor/github.com/sirupsen/logrus/doc.go | 26 - vendor/github.com/sirupsen/logrus/entry.go | 442 - vendor/github.com/sirupsen/logrus/exported.go | 270 - .../github.com/sirupsen/logrus/formatter.go | 78 - vendor/github.com/sirupsen/logrus/hooks.go | 34 - .../sirupsen/logrus/hooks/test/test.go | 91 - .../sirupsen/logrus/json_formatter.go | 128 - vendor/github.com/sirupsen/logrus/logger.go | 417 - vendor/github.com/sirupsen/logrus/logrus.go | 186 - .../logrus/terminal_check_appengine.go | 11 - .../sirupsen/logrus/terminal_check_bsd.go | 13 - .../sirupsen/logrus/terminal_check_js.go | 7 - .../logrus/terminal_check_no_terminal.go | 11 - .../logrus/terminal_check_notappengine.go | 17 - .../sirupsen/logrus/terminal_check_solaris.go | 11 - .../sirupsen/logrus/terminal_check_unix.go | 13 - .../sirupsen/logrus/terminal_check_windows.go | 27 - .../sirupsen/logrus/text_formatter.go | 339 - vendor/github.com/sirupsen/logrus/writer.go | 102 - .../github.com/stretchr/objx/.codeclimate.yml | 21 - vendor/github.com/stretchr/objx/.gitignore | 11 - vendor/github.com/stretchr/objx/LICENSE | 22 - vendor/github.com/stretchr/objx/README.md | 80 - vendor/github.com/stretchr/objx/Taskfile.yml | 27 - vendor/github.com/stretchr/objx/accessors.go | 197 - .../github.com/stretchr/objx/conversions.go | 280 - vendor/github.com/stretchr/objx/doc.go | 66 - vendor/github.com/stretchr/objx/map.go | 214 - vendor/github.com/stretchr/objx/mutations.go | 77 - vendor/github.com/stretchr/objx/security.go | 12 - vendor/github.com/stretchr/objx/tests.go | 17 - .../github.com/stretchr/objx/type_specific.go | 346 - .../stretchr/objx/type_specific_codegen.go | 2261 - vendor/github.com/stretchr/objx/value.go | 159 - vendor/github.com/stretchr/testify/LICENSE | 21 - .../testify/assert/assertion_compare.go | 489 - .../testify/assert/assertion_format.go | 841 - .../testify/assert/assertion_format.go.tmpl | 5 - .../testify/assert/assertion_forward.go | 1673 - .../testify/assert/assertion_forward.go.tmpl | 5 - .../testify/assert/assertion_order.go | 81 - .../stretchr/testify/assert/assertions.go | 2184 - .../github.com/stretchr/testify/assert/doc.go | 46 - .../stretchr/testify/assert/errors.go | 10 - .../testify/assert/forward_assertions.go | 16 - .../testify/assert/http_assertions.go | 165 - .../testify/assert/yaml/yaml_custom.go | 25 - .../testify/assert/yaml/yaml_default.go | 37 - .../stretchr/testify/assert/yaml/yaml_fail.go | 18 - .../github.com/stretchr/testify/mock/doc.go | 44 - .../github.com/stretchr/testify/mock/mock.go | 1288 - .../stretchr/testify/require/doc.go | 29 - .../testify/require/forward_requirements.go | 16 - .../stretchr/testify/require/require.go | 2124 - .../stretchr/testify/require/require.go.tmpl | 6 - .../testify/require/require_forward.go | 1674 - .../testify/require/require_forward.go.tmpl | 5 - .../stretchr/testify/require/requirements.go | 29 - vendor/github.com/twmb/murmur3/.gitignore | 1 - vendor/github.com/twmb/murmur3/LICENSE | 49 - vendor/github.com/twmb/murmur3/README.md | 129 - vendor/github.com/twmb/murmur3/murmur.go | 58 - vendor/github.com/twmb/murmur3/murmur128.go | 182 - .../github.com/twmb/murmur3/murmur128_amd64.s | 247 - .../github.com/twmb/murmur3/murmur128_decl.go | 36 - .../github.com/twmb/murmur3/murmur128_gen.go | 236 - vendor/github.com/twmb/murmur3/murmur32.go | 100 - .../github.com/twmb/murmur3/murmur32_gen.go | 108 - vendor/github.com/twmb/murmur3/murmur64.go | 70 - .../valyala/bytebufferpool/.travis.yml | 15 - .../github.com/valyala/bytebufferpool/LICENSE | 22 - .../valyala/bytebufferpool/README.md | 21 - .../valyala/bytebufferpool/bytebuffer.go | 111 - .../github.com/valyala/bytebufferpool/doc.go | 7 - .../github.com/valyala/bytebufferpool/pool.go | 151 - .../github.com/valyala/fasttemplate/LICENSE | 22 - .../github.com/valyala/fasttemplate/README.md | 85 - .../valyala/fasttemplate/template.go | 436 - .../github.com/valyala/fasttemplate/unsafe.go | 21 - .../valyala/fasttemplate/unsafe_gae.go | 11 - vendor/golang.org/x/crypto/LICENSE | 27 - vendor/golang.org/x/crypto/PATENTS | 22 - vendor/golang.org/x/crypto/acme/acme.go | 818 - .../x/crypto/acme/autocert/autocert.go | 1198 - .../x/crypto/acme/autocert/cache.go | 135 - .../x/crypto/acme/autocert/listener.go | 155 - .../x/crypto/acme/autocert/renewal.go | 156 - vendor/golang.org/x/crypto/acme/http.go | 344 - vendor/golang.org/x/crypto/acme/jws.go | 257 - vendor/golang.org/x/crypto/acme/rfc8555.go | 476 - vendor/golang.org/x/crypto/acme/types.go | 614 - vendor/golang.org/x/crypto/pbkdf2/pbkdf2.go | 77 - vendor/golang.org/x/net/LICENSE | 27 - vendor/golang.org/x/net/PATENTS | 22 - vendor/golang.org/x/net/http/httpguts/guts.go | 50 - .../golang.org/x/net/http/httpguts/httplex.go | 347 - vendor/golang.org/x/net/http2/.gitignore | 2 - vendor/golang.org/x/net/http2/ascii.go | 53 - vendor/golang.org/x/net/http2/ciphers.go | 641 - .../x/net/http2/client_conn_pool.go | 311 - vendor/golang.org/x/net/http2/config.go | 122 - vendor/golang.org/x/net/http2/config_go124.go | 61 - .../x/net/http2/config_pre_go124.go | 16 - vendor/golang.org/x/net/http2/databuffer.go | 149 - vendor/golang.org/x/net/http2/errors.go | 145 - vendor/golang.org/x/net/http2/flow.go | 120 - vendor/golang.org/x/net/http2/frame.go | 1691 - vendor/golang.org/x/net/http2/gotrack.go | 170 - vendor/golang.org/x/net/http2/h2c/h2c.go | 240 - vendor/golang.org/x/net/http2/headermap.go | 105 - vendor/golang.org/x/net/http2/hpack/encode.go | 245 - vendor/golang.org/x/net/http2/hpack/hpack.go | 523 - .../golang.org/x/net/http2/hpack/huffman.go | 226 - .../x/net/http2/hpack/static_table.go | 188 - vendor/golang.org/x/net/http2/hpack/tables.go | 403 - vendor/golang.org/x/net/http2/http2.go | 441 - vendor/golang.org/x/net/http2/pipe.go | 184 - vendor/golang.org/x/net/http2/server.go | 3392 -- vendor/golang.org/x/net/http2/timer.go | 20 - vendor/golang.org/x/net/http2/transport.go | 3540 -- vendor/golang.org/x/net/http2/unencrypted.go | 32 - vendor/golang.org/x/net/http2/write.go | 380 - vendor/golang.org/x/net/http2/writesched.go | 251 - .../x/net/http2/writesched_priority.go | 451 - .../x/net/http2/writesched_random.go | 77 - .../x/net/http2/writesched_roundrobin.go | 119 - vendor/golang.org/x/net/idna/go118.go | 13 - vendor/golang.org/x/net/idna/idna10.0.0.go | 769 - vendor/golang.org/x/net/idna/idna9.0.0.go | 717 - vendor/golang.org/x/net/idna/pre_go118.go | 11 - vendor/golang.org/x/net/idna/punycode.go | 217 - vendor/golang.org/x/net/idna/tables10.0.0.go | 4559 -- vendor/golang.org/x/net/idna/tables11.0.0.go | 4653 -- vendor/golang.org/x/net/idna/tables12.0.0.go | 4733 -- vendor/golang.org/x/net/idna/tables13.0.0.go | 4959 -- vendor/golang.org/x/net/idna/tables15.0.0.go | 5144 -- vendor/golang.org/x/net/idna/tables9.0.0.go | 4486 -- vendor/golang.org/x/net/idna/trie.go | 51 - vendor/golang.org/x/net/idna/trie12.0.0.go | 30 - vendor/golang.org/x/net/idna/trie13.0.0.go | 30 - vendor/golang.org/x/net/idna/trieval.go | 119 - vendor/golang.org/x/sync/LICENSE | 27 - vendor/golang.org/x/sync/PATENTS | 22 - .../golang.org/x/sync/semaphore/semaphore.go | 160 - vendor/golang.org/x/sys/LICENSE | 27 - vendor/golang.org/x/sys/PATENTS | 22 - vendor/golang.org/x/sys/execabs/execabs.go | 102 - .../golang.org/x/sys/execabs/execabs_go118.go | 17 - .../golang.org/x/sys/execabs/execabs_go119.go | 20 - vendor/golang.org/x/sys/unix/.gitignore | 2 - vendor/golang.org/x/sys/unix/README.md | 184 - .../golang.org/x/sys/unix/affinity_linux.go | 86 - vendor/golang.org/x/sys/unix/aliases.go | 13 - vendor/golang.org/x/sys/unix/asm_aix_ppc64.s | 17 - vendor/golang.org/x/sys/unix/asm_bsd_386.s | 27 - vendor/golang.org/x/sys/unix/asm_bsd_amd64.s | 27 - vendor/golang.org/x/sys/unix/asm_bsd_arm.s | 27 - vendor/golang.org/x/sys/unix/asm_bsd_arm64.s | 27 - vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s | 29 - .../golang.org/x/sys/unix/asm_bsd_riscv64.s | 27 - vendor/golang.org/x/sys/unix/asm_linux_386.s | 65 - .../golang.org/x/sys/unix/asm_linux_amd64.s | 57 - vendor/golang.org/x/sys/unix/asm_linux_arm.s | 56 - .../golang.org/x/sys/unix/asm_linux_arm64.s | 50 - .../golang.org/x/sys/unix/asm_linux_loong64.s | 51 - .../golang.org/x/sys/unix/asm_linux_mips64x.s | 54 - .../golang.org/x/sys/unix/asm_linux_mipsx.s | 52 - .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 42 - .../golang.org/x/sys/unix/asm_linux_riscv64.s | 47 - .../golang.org/x/sys/unix/asm_linux_s390x.s | 54 - .../x/sys/unix/asm_openbsd_mips64.s | 29 - .../golang.org/x/sys/unix/asm_solaris_amd64.s | 17 - vendor/golang.org/x/sys/unix/asm_zos_s390x.s | 382 - .../golang.org/x/sys/unix/bluetooth_linux.go | 36 - vendor/golang.org/x/sys/unix/bpxsvc_zos.go | 657 - vendor/golang.org/x/sys/unix/bpxsvc_zos.s | 192 - vendor/golang.org/x/sys/unix/cap_freebsd.go | 195 - vendor/golang.org/x/sys/unix/constants.go | 13 - vendor/golang.org/x/sys/unix/dev_aix_ppc.go | 26 - vendor/golang.org/x/sys/unix/dev_aix_ppc64.go | 28 - vendor/golang.org/x/sys/unix/dev_darwin.go | 24 - vendor/golang.org/x/sys/unix/dev_dragonfly.go | 30 - vendor/golang.org/x/sys/unix/dev_freebsd.go | 30 - vendor/golang.org/x/sys/unix/dev_linux.go | 42 - vendor/golang.org/x/sys/unix/dev_netbsd.go | 29 - vendor/golang.org/x/sys/unix/dev_openbsd.go | 29 - vendor/golang.org/x/sys/unix/dev_zos.go | 28 - vendor/golang.org/x/sys/unix/dirent.go | 102 - vendor/golang.org/x/sys/unix/endian_big.go | 9 - vendor/golang.org/x/sys/unix/endian_little.go | 9 - vendor/golang.org/x/sys/unix/env_unix.go | 31 - vendor/golang.org/x/sys/unix/fcntl.go | 36 - vendor/golang.org/x/sys/unix/fcntl_darwin.go | 24 - .../x/sys/unix/fcntl_linux_32bit.go | 13 - vendor/golang.org/x/sys/unix/fdset.go | 29 - vendor/golang.org/x/sys/unix/gccgo.go | 59 - vendor/golang.org/x/sys/unix/gccgo_c.c | 44 - .../x/sys/unix/gccgo_linux_amd64.go | 20 - vendor/golang.org/x/sys/unix/ifreq_linux.go | 141 - vendor/golang.org/x/sys/unix/ioctl_linux.go | 334 - vendor/golang.org/x/sys/unix/ioctl_signed.go | 69 - .../golang.org/x/sys/unix/ioctl_unsigned.go | 69 - vendor/golang.org/x/sys/unix/ioctl_zos.go | 71 - vendor/golang.org/x/sys/unix/mkall.sh | 249 - vendor/golang.org/x/sys/unix/mkerrors.sh | 805 - vendor/golang.org/x/sys/unix/mmap_nomremap.go | 13 - vendor/golang.org/x/sys/unix/mremap.go | 57 - vendor/golang.org/x/sys/unix/pagesize_unix.go | 15 - .../golang.org/x/sys/unix/pledge_openbsd.go | 111 - vendor/golang.org/x/sys/unix/ptrace_darwin.go | 11 - vendor/golang.org/x/sys/unix/ptrace_ios.go | 11 - vendor/golang.org/x/sys/unix/race.go | 30 - vendor/golang.org/x/sys/unix/race0.go | 25 - .../x/sys/unix/readdirent_getdents.go | 12 - .../x/sys/unix/readdirent_getdirentries.go | 19 - .../x/sys/unix/sockcmsg_dragonfly.go | 16 - .../golang.org/x/sys/unix/sockcmsg_linux.go | 85 - vendor/golang.org/x/sys/unix/sockcmsg_unix.go | 106 - .../x/sys/unix/sockcmsg_unix_other.go | 46 - vendor/golang.org/x/sys/unix/sockcmsg_zos.go | 58 - .../golang.org/x/sys/unix/symaddr_zos_s390x.s | 75 - vendor/golang.org/x/sys/unix/syscall.go | 86 - vendor/golang.org/x/sys/unix/syscall_aix.go | 582 - .../golang.org/x/sys/unix/syscall_aix_ppc.go | 52 - .../x/sys/unix/syscall_aix_ppc64.go | 83 - vendor/golang.org/x/sys/unix/syscall_bsd.go | 609 - .../golang.org/x/sys/unix/syscall_darwin.go | 707 - .../x/sys/unix/syscall_darwin_amd64.go | 50 - .../x/sys/unix/syscall_darwin_arm64.go | 50 - .../x/sys/unix/syscall_darwin_libSystem.go | 26 - .../x/sys/unix/syscall_dragonfly.go | 347 - .../x/sys/unix/syscall_dragonfly_amd64.go | 56 - .../golang.org/x/sys/unix/syscall_freebsd.go | 455 - .../x/sys/unix/syscall_freebsd_386.go | 64 - .../x/sys/unix/syscall_freebsd_amd64.go | 64 - .../x/sys/unix/syscall_freebsd_arm.go | 60 - .../x/sys/unix/syscall_freebsd_arm64.go | 60 - .../x/sys/unix/syscall_freebsd_riscv64.go | 60 - vendor/golang.org/x/sys/unix/syscall_hurd.go | 30 - .../golang.org/x/sys/unix/syscall_hurd_386.go | 28 - .../golang.org/x/sys/unix/syscall_illumos.go | 78 - vendor/golang.org/x/sys/unix/syscall_linux.go | 2657 - .../x/sys/unix/syscall_linux_386.go | 314 - .../x/sys/unix/syscall_linux_alarm.go | 12 - .../x/sys/unix/syscall_linux_amd64.go | 145 - .../x/sys/unix/syscall_linux_amd64_gc.go | 12 - .../x/sys/unix/syscall_linux_arm.go | 216 - .../x/sys/unix/syscall_linux_arm64.go | 186 - .../golang.org/x/sys/unix/syscall_linux_gc.go | 14 - .../x/sys/unix/syscall_linux_gc_386.go | 16 - .../x/sys/unix/syscall_linux_gc_arm.go | 13 - .../x/sys/unix/syscall_linux_gccgo_386.go | 30 - .../x/sys/unix/syscall_linux_gccgo_arm.go | 20 - .../x/sys/unix/syscall_linux_loong64.go | 218 - .../x/sys/unix/syscall_linux_mips64x.go | 188 - .../x/sys/unix/syscall_linux_mipsx.go | 174 - .../x/sys/unix/syscall_linux_ppc.go | 204 - .../x/sys/unix/syscall_linux_ppc64x.go | 115 - .../x/sys/unix/syscall_linux_riscv64.go | 191 - .../x/sys/unix/syscall_linux_s390x.go | 296 - .../x/sys/unix/syscall_linux_sparc64.go | 112 - .../golang.org/x/sys/unix/syscall_netbsd.go | 371 - .../x/sys/unix/syscall_netbsd_386.go | 37 - .../x/sys/unix/syscall_netbsd_amd64.go | 37 - .../x/sys/unix/syscall_netbsd_arm.go | 37 - .../x/sys/unix/syscall_netbsd_arm64.go | 37 - .../golang.org/x/sys/unix/syscall_openbsd.go | 342 - .../x/sys/unix/syscall_openbsd_386.go | 41 - .../x/sys/unix/syscall_openbsd_amd64.go | 41 - .../x/sys/unix/syscall_openbsd_arm.go | 41 - .../x/sys/unix/syscall_openbsd_arm64.go | 41 - .../x/sys/unix/syscall_openbsd_libc.go | 26 - .../x/sys/unix/syscall_openbsd_mips64.go | 39 - .../x/sys/unix/syscall_openbsd_ppc64.go | 41 - .../x/sys/unix/syscall_openbsd_riscv64.go | 41 - .../golang.org/x/sys/unix/syscall_solaris.go | 1104 - .../x/sys/unix/syscall_solaris_amd64.go | 27 - vendor/golang.org/x/sys/unix/syscall_unix.go | 615 - .../golang.org/x/sys/unix/syscall_unix_gc.go | 14 - .../x/sys/unix/syscall_unix_gc_ppc64x.go | 22 - .../x/sys/unix/syscall_zos_s390x.go | 3213 - vendor/golang.org/x/sys/unix/sysvshm_linux.go | 20 - vendor/golang.org/x/sys/unix/sysvshm_unix.go | 51 - .../x/sys/unix/sysvshm_unix_other.go | 13 - vendor/golang.org/x/sys/unix/timestruct.go | 76 - .../golang.org/x/sys/unix/unveil_openbsd.go | 51 - .../golang.org/x/sys/unix/vgetrandom_linux.go | 13 - .../x/sys/unix/vgetrandom_unsupported.go | 11 - vendor/golang.org/x/sys/unix/xattr_bsd.go | 280 - .../golang.org/x/sys/unix/zerrors_aix_ppc.go | 1384 - .../x/sys/unix/zerrors_aix_ppc64.go | 1385 - .../x/sys/unix/zerrors_darwin_amd64.go | 1922 - .../x/sys/unix/zerrors_darwin_arm64.go | 1922 - .../x/sys/unix/zerrors_dragonfly_amd64.go | 1737 - .../x/sys/unix/zerrors_freebsd_386.go | 2042 - .../x/sys/unix/zerrors_freebsd_amd64.go | 2039 - .../x/sys/unix/zerrors_freebsd_arm.go | 2033 - .../x/sys/unix/zerrors_freebsd_arm64.go | 2033 - .../x/sys/unix/zerrors_freebsd_riscv64.go | 2147 - vendor/golang.org/x/sys/unix/zerrors_linux.go | 3734 -- .../x/sys/unix/zerrors_linux_386.go | 870 - .../x/sys/unix/zerrors_linux_amd64.go | 870 - .../x/sys/unix/zerrors_linux_arm.go | 875 - .../x/sys/unix/zerrors_linux_arm64.go | 871 - .../x/sys/unix/zerrors_linux_loong64.go | 862 - .../x/sys/unix/zerrors_linux_mips.go | 876 - .../x/sys/unix/zerrors_linux_mips64.go | 876 - .../x/sys/unix/zerrors_linux_mips64le.go | 876 - .../x/sys/unix/zerrors_linux_mipsle.go | 876 - .../x/sys/unix/zerrors_linux_ppc.go | 928 - .../x/sys/unix/zerrors_linux_ppc64.go | 932 - .../x/sys/unix/zerrors_linux_ppc64le.go | 932 - .../x/sys/unix/zerrors_linux_riscv64.go | 859 - .../x/sys/unix/zerrors_linux_s390x.go | 931 - .../x/sys/unix/zerrors_linux_sparc64.go | 974 - .../x/sys/unix/zerrors_netbsd_386.go | 1779 - .../x/sys/unix/zerrors_netbsd_amd64.go | 1769 - .../x/sys/unix/zerrors_netbsd_arm.go | 1758 - .../x/sys/unix/zerrors_netbsd_arm64.go | 1769 - .../x/sys/unix/zerrors_openbsd_386.go | 1905 - .../x/sys/unix/zerrors_openbsd_amd64.go | 1905 - .../x/sys/unix/zerrors_openbsd_arm.go | 1905 - .../x/sys/unix/zerrors_openbsd_arm64.go | 1905 - .../x/sys/unix/zerrors_openbsd_mips64.go | 1905 - .../x/sys/unix/zerrors_openbsd_ppc64.go | 1904 - .../x/sys/unix/zerrors_openbsd_riscv64.go | 1903 - .../x/sys/unix/zerrors_solaris_amd64.go | 1556 - .../x/sys/unix/zerrors_zos_s390x.go | 990 - .../x/sys/unix/zptrace_armnn_linux.go | 40 - .../x/sys/unix/zptrace_linux_arm64.go | 17 - .../x/sys/unix/zptrace_mipsnn_linux.go | 49 - .../x/sys/unix/zptrace_mipsnnle_linux.go | 49 - .../x/sys/unix/zptrace_x86_linux.go | 79 - .../x/sys/unix/zsymaddr_zos_s390x.s | 364 - .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 1461 - .../x/sys/unix/zsyscall_aix_ppc64.go | 1420 - .../x/sys/unix/zsyscall_aix_ppc64_gc.go | 1188 - .../x/sys/unix/zsyscall_aix_ppc64_gccgo.go | 1069 - .../x/sys/unix/zsyscall_darwin_amd64.go | 2644 - .../x/sys/unix/zsyscall_darwin_amd64.s | 779 - .../x/sys/unix/zsyscall_darwin_arm64.go | 2644 - .../x/sys/unix/zsyscall_darwin_arm64.s | 779 - .../x/sys/unix/zsyscall_dragonfly_amd64.go | 1666 - .../x/sys/unix/zsyscall_freebsd_386.go | 1886 - .../x/sys/unix/zsyscall_freebsd_amd64.go | 1886 - .../x/sys/unix/zsyscall_freebsd_arm.go | 1886 - .../x/sys/unix/zsyscall_freebsd_arm64.go | 1886 - .../x/sys/unix/zsyscall_freebsd_riscv64.go | 1886 - .../x/sys/unix/zsyscall_illumos_amd64.go | 101 - .../golang.org/x/sys/unix/zsyscall_linux.go | 2240 - .../x/sys/unix/zsyscall_linux_386.go | 486 - .../x/sys/unix/zsyscall_linux_amd64.go | 653 - .../x/sys/unix/zsyscall_linux_arm.go | 601 - .../x/sys/unix/zsyscall_linux_arm64.go | 552 - .../x/sys/unix/zsyscall_linux_loong64.go | 486 - .../x/sys/unix/zsyscall_linux_mips.go | 653 - .../x/sys/unix/zsyscall_linux_mips64.go | 647 - .../x/sys/unix/zsyscall_linux_mips64le.go | 636 - .../x/sys/unix/zsyscall_linux_mipsle.go | 653 - .../x/sys/unix/zsyscall_linux_ppc.go | 658 - .../x/sys/unix/zsyscall_linux_ppc64.go | 704 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 704 - .../x/sys/unix/zsyscall_linux_riscv64.go | 548 - .../x/sys/unix/zsyscall_linux_s390x.go | 495 - .../x/sys/unix/zsyscall_linux_sparc64.go | 648 - .../x/sys/unix/zsyscall_netbsd_386.go | 1848 - .../x/sys/unix/zsyscall_netbsd_amd64.go | 1848 - .../x/sys/unix/zsyscall_netbsd_arm.go | 1848 - .../x/sys/unix/zsyscall_netbsd_arm64.go | 1848 - .../x/sys/unix/zsyscall_openbsd_386.go | 2323 - .../x/sys/unix/zsyscall_openbsd_386.s | 699 - .../x/sys/unix/zsyscall_openbsd_amd64.go | 2323 - .../x/sys/unix/zsyscall_openbsd_amd64.s | 699 - .../x/sys/unix/zsyscall_openbsd_arm.go | 2323 - .../x/sys/unix/zsyscall_openbsd_arm.s | 699 - .../x/sys/unix/zsyscall_openbsd_arm64.go | 2323 - .../x/sys/unix/zsyscall_openbsd_arm64.s | 699 - .../x/sys/unix/zsyscall_openbsd_mips64.go | 2323 - .../x/sys/unix/zsyscall_openbsd_mips64.s | 699 - .../x/sys/unix/zsyscall_openbsd_ppc64.go | 2323 - .../x/sys/unix/zsyscall_openbsd_ppc64.s | 838 - .../x/sys/unix/zsyscall_openbsd_riscv64.go | 2323 - .../x/sys/unix/zsyscall_openbsd_riscv64.s | 699 - .../x/sys/unix/zsyscall_solaris_amd64.go | 2103 - .../x/sys/unix/zsyscall_zos_s390x.go | 3458 -- .../x/sys/unix/zsysctl_openbsd_386.go | 280 - .../x/sys/unix/zsysctl_openbsd_amd64.go | 280 - .../x/sys/unix/zsysctl_openbsd_arm.go | 280 - .../x/sys/unix/zsysctl_openbsd_arm64.go | 280 - .../x/sys/unix/zsysctl_openbsd_mips64.go | 280 - .../x/sys/unix/zsysctl_openbsd_ppc64.go | 280 - .../x/sys/unix/zsysctl_openbsd_riscv64.go | 281 - .../x/sys/unix/zsysnum_darwin_amd64.go | 439 - .../x/sys/unix/zsysnum_darwin_arm64.go | 437 - .../x/sys/unix/zsysnum_dragonfly_amd64.go | 316 - .../x/sys/unix/zsysnum_freebsd_386.go | 393 - .../x/sys/unix/zsysnum_freebsd_amd64.go | 393 - .../x/sys/unix/zsysnum_freebsd_arm.go | 393 - .../x/sys/unix/zsysnum_freebsd_arm64.go | 393 - .../x/sys/unix/zsysnum_freebsd_riscv64.go | 393 - .../x/sys/unix/zsysnum_linux_386.go | 461 - .../x/sys/unix/zsysnum_linux_amd64.go | 384 - .../x/sys/unix/zsysnum_linux_arm.go | 425 - .../x/sys/unix/zsysnum_linux_arm64.go | 328 - .../x/sys/unix/zsysnum_linux_loong64.go | 324 - .../x/sys/unix/zsysnum_linux_mips.go | 445 - .../x/sys/unix/zsysnum_linux_mips64.go | 375 - .../x/sys/unix/zsysnum_linux_mips64le.go | 375 - .../x/sys/unix/zsysnum_linux_mipsle.go | 445 - .../x/sys/unix/zsysnum_linux_ppc.go | 452 - .../x/sys/unix/zsysnum_linux_ppc64.go | 424 - .../x/sys/unix/zsysnum_linux_ppc64le.go | 424 - .../x/sys/unix/zsysnum_linux_riscv64.go | 329 - .../x/sys/unix/zsysnum_linux_s390x.go | 390 - .../x/sys/unix/zsysnum_linux_sparc64.go | 403 - .../x/sys/unix/zsysnum_netbsd_386.go | 274 - .../x/sys/unix/zsysnum_netbsd_amd64.go | 274 - .../x/sys/unix/zsysnum_netbsd_arm.go | 274 - .../x/sys/unix/zsysnum_netbsd_arm64.go | 274 - .../x/sys/unix/zsysnum_openbsd_386.go | 219 - .../x/sys/unix/zsysnum_openbsd_amd64.go | 219 - .../x/sys/unix/zsysnum_openbsd_arm.go | 219 - .../x/sys/unix/zsysnum_openbsd_arm64.go | 218 - .../x/sys/unix/zsysnum_openbsd_mips64.go | 221 - .../x/sys/unix/zsysnum_openbsd_ppc64.go | 217 - .../x/sys/unix/zsysnum_openbsd_riscv64.go | 218 - .../x/sys/unix/zsysnum_zos_s390x.go | 2852 - .../golang.org/x/sys/unix/ztypes_aix_ppc.go | 353 - .../golang.org/x/sys/unix/ztypes_aix_ppc64.go | 357 - .../x/sys/unix/ztypes_darwin_amd64.go | 878 - .../x/sys/unix/ztypes_darwin_arm64.go | 878 - .../x/sys/unix/ztypes_dragonfly_amd64.go | 473 - .../x/sys/unix/ztypes_freebsd_386.go | 651 - .../x/sys/unix/ztypes_freebsd_amd64.go | 656 - .../x/sys/unix/ztypes_freebsd_arm.go | 642 - .../x/sys/unix/ztypes_freebsd_arm64.go | 636 - .../x/sys/unix/ztypes_freebsd_riscv64.go | 638 - vendor/golang.org/x/sys/unix/ztypes_linux.go | 6176 -- .../golang.org/x/sys/unix/ztypes_linux_386.go | 689 - .../x/sys/unix/ztypes_linux_amd64.go | 703 - .../golang.org/x/sys/unix/ztypes_linux_arm.go | 683 - .../x/sys/unix/ztypes_linux_arm64.go | 682 - .../x/sys/unix/ztypes_linux_loong64.go | 683 - .../x/sys/unix/ztypes_linux_mips.go | 688 - .../x/sys/unix/ztypes_linux_mips64.go | 685 - .../x/sys/unix/ztypes_linux_mips64le.go | 685 - .../x/sys/unix/ztypes_linux_mipsle.go | 688 - .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 696 - .../x/sys/unix/ztypes_linux_ppc64.go | 691 - .../x/sys/unix/ztypes_linux_ppc64le.go | 691 - .../x/sys/unix/ztypes_linux_riscv64.go | 770 - .../x/sys/unix/ztypes_linux_s390x.go | 705 - .../x/sys/unix/ztypes_linux_sparc64.go | 686 - .../x/sys/unix/ztypes_netbsd_386.go | 585 - .../x/sys/unix/ztypes_netbsd_amd64.go | 593 - .../x/sys/unix/ztypes_netbsd_arm.go | 590 - .../x/sys/unix/ztypes_netbsd_arm64.go | 593 - .../x/sys/unix/ztypes_openbsd_386.go | 568 - .../x/sys/unix/ztypes_openbsd_amd64.go | 568 - .../x/sys/unix/ztypes_openbsd_arm.go | 575 - .../x/sys/unix/ztypes_openbsd_arm64.go | 568 - .../x/sys/unix/ztypes_openbsd_mips64.go | 568 - .../x/sys/unix/ztypes_openbsd_ppc64.go | 570 - .../x/sys/unix/ztypes_openbsd_riscv64.go | 570 - .../x/sys/unix/ztypes_solaris_amd64.go | 516 - .../golang.org/x/sys/unix/ztypes_zos_s390x.go | 552 - vendor/golang.org/x/sys/windows/aliases.go | 12 - .../golang.org/x/sys/windows/dll_windows.go | 416 - .../golang.org/x/sys/windows/env_windows.go | 57 - vendor/golang.org/x/sys/windows/eventlog.go | 20 - .../golang.org/x/sys/windows/exec_windows.go | 248 - .../x/sys/windows/memory_windows.go | 48 - vendor/golang.org/x/sys/windows/mkerrors.bash | 70 - .../x/sys/windows/mkknownfolderids.bash | 27 - vendor/golang.org/x/sys/windows/mksyscall.go | 9 - vendor/golang.org/x/sys/windows/race.go | 30 - vendor/golang.org/x/sys/windows/race0.go | 25 - .../x/sys/windows/security_windows.go | 1458 - vendor/golang.org/x/sys/windows/service.go | 257 - .../x/sys/windows/setupapi_windows.go | 1425 - vendor/golang.org/x/sys/windows/str.go | 22 - vendor/golang.org/x/sys/windows/syscall.go | 104 - .../x/sys/windows/syscall_windows.go | 1932 - .../golang.org/x/sys/windows/types_windows.go | 3603 -- .../x/sys/windows/types_windows_386.go | 35 - .../x/sys/windows/types_windows_amd64.go | 34 - .../x/sys/windows/types_windows_arm.go | 35 - .../x/sys/windows/types_windows_arm64.go | 34 - .../x/sys/windows/zerrors_windows.go | 9468 --- .../x/sys/windows/zknownfolderids_windows.go | 149 - .../x/sys/windows/zsyscall_windows.go | 4686 -- vendor/golang.org/x/text/LICENSE | 27 - vendor/golang.org/x/text/PATENTS | 22 - vendor/golang.org/x/text/cases/cases.go | 162 - vendor/golang.org/x/text/cases/context.go | 376 - vendor/golang.org/x/text/cases/fold.go | 34 - vendor/golang.org/x/text/cases/icu.go | 61 - vendor/golang.org/x/text/cases/info.go | 82 - vendor/golang.org/x/text/cases/map.go | 816 - .../golang.org/x/text/cases/tables10.0.0.go | 2255 - .../golang.org/x/text/cases/tables11.0.0.go | 2316 - .../golang.org/x/text/cases/tables12.0.0.go | 2359 - .../golang.org/x/text/cases/tables13.0.0.go | 2399 - .../golang.org/x/text/cases/tables15.0.0.go | 2527 - vendor/golang.org/x/text/cases/tables9.0.0.go | 2215 - vendor/golang.org/x/text/cases/trieval.go | 217 - vendor/golang.org/x/text/internal/internal.go | 49 - .../x/text/internal/language/common.go | 16 - .../x/text/internal/language/compact.go | 29 - .../text/internal/language/compact/compact.go | 61 - .../internal/language/compact/language.go | 260 - .../text/internal/language/compact/parents.go | 120 - .../text/internal/language/compact/tables.go | 1015 - .../x/text/internal/language/compact/tags.go | 91 - .../x/text/internal/language/compose.go | 167 - .../x/text/internal/language/coverage.go | 28 - .../x/text/internal/language/language.go | 627 - .../x/text/internal/language/lookup.go | 412 - .../x/text/internal/language/match.go | 226 - .../x/text/internal/language/parse.go | 608 - .../x/text/internal/language/tables.go | 3494 -- .../x/text/internal/language/tags.go | 48 - vendor/golang.org/x/text/internal/match.go | 67 - vendor/golang.org/x/text/internal/tag/tag.go | 100 - vendor/golang.org/x/text/language/coverage.go | 187 - vendor/golang.org/x/text/language/doc.go | 98 - vendor/golang.org/x/text/language/language.go | 605 - vendor/golang.org/x/text/language/match.go | 735 - vendor/golang.org/x/text/language/parse.go | 256 - vendor/golang.org/x/text/language/tables.go | 298 - vendor/golang.org/x/text/language/tags.go | 145 - vendor/golang.org/x/text/runes/cond.go | 187 - vendor/golang.org/x/text/runes/runes.go | 355 - .../x/text/secure/bidirule/bidirule.go | 336 - .../x/text/secure/bidirule/bidirule10.0.0.go | 11 - .../x/text/secure/bidirule/bidirule9.0.0.go | 14 - .../golang.org/x/text/secure/precis/class.go | 36 - .../x/text/secure/precis/context.go | 139 - vendor/golang.org/x/text/secure/precis/doc.go | 14 - .../x/text/secure/precis/nickname.go | 72 - .../x/text/secure/precis/options.go | 157 - .../x/text/secure/precis/profile.go | 412 - .../x/text/secure/precis/profiles.go | 78 - .../x/text/secure/precis/tables10.0.0.go | 3889 -- .../x/text/secure/precis/tables11.0.0.go | 4016 -- .../x/text/secure/precis/tables12.0.0.go | 4118 -- .../x/text/secure/precis/tables13.0.0.go | 4152 -- .../x/text/secure/precis/tables15.0.0.go | 4315 -- .../x/text/secure/precis/tables9.0.0.go | 3790 -- .../x/text/secure/precis/transformer.go | 32 - .../x/text/secure/precis/trieval.go | 64 - .../golang.org/x/text/transform/transform.go | 709 - vendor/golang.org/x/text/unicode/bidi/bidi.go | 359 - .../golang.org/x/text/unicode/bidi/bracket.go | 335 - vendor/golang.org/x/text/unicode/bidi/core.go | 1071 - vendor/golang.org/x/text/unicode/bidi/prop.go | 206 - .../x/text/unicode/bidi/tables10.0.0.go | 1815 - .../x/text/unicode/bidi/tables11.0.0.go | 1887 - .../x/text/unicode/bidi/tables12.0.0.go | 1923 - .../x/text/unicode/bidi/tables13.0.0.go | 1955 - .../x/text/unicode/bidi/tables15.0.0.go | 2042 - .../x/text/unicode/bidi/tables9.0.0.go | 1781 - .../golang.org/x/text/unicode/bidi/trieval.go | 48 - .../x/text/unicode/norm/composition.go | 512 - .../x/text/unicode/norm/forminfo.go | 279 - .../golang.org/x/text/unicode/norm/input.go | 109 - vendor/golang.org/x/text/unicode/norm/iter.go | 458 - .../x/text/unicode/norm/normalize.go | 610 - .../x/text/unicode/norm/readwriter.go | 125 - .../x/text/unicode/norm/tables10.0.0.go | 7657 --- .../x/text/unicode/norm/tables11.0.0.go | 7693 --- .../x/text/unicode/norm/tables12.0.0.go | 7710 --- .../x/text/unicode/norm/tables13.0.0.go | 7760 --- .../x/text/unicode/norm/tables15.0.0.go | 7907 --- .../x/text/unicode/norm/tables9.0.0.go | 7637 --- .../x/text/unicode/norm/transform.go | 88 - vendor/golang.org/x/text/unicode/norm/trie.go | 54 - vendor/golang.org/x/text/width/kind_string.go | 28 - .../golang.org/x/text/width/tables10.0.0.go | 1328 - .../golang.org/x/text/width/tables11.0.0.go | 1340 - .../golang.org/x/text/width/tables12.0.0.go | 1360 - .../golang.org/x/text/width/tables13.0.0.go | 1361 - .../golang.org/x/text/width/tables15.0.0.go | 1367 - vendor/golang.org/x/text/width/tables9.0.0.go | 1296 - vendor/golang.org/x/text/width/transform.go | 239 - vendor/golang.org/x/text/width/trieval.go | 30 - vendor/golang.org/x/text/width/width.go | 206 - vendor/golang.org/x/time/LICENSE | 27 - vendor/golang.org/x/time/PATENTS | 22 - vendor/golang.org/x/time/rate/rate.go | 419 - vendor/golang.org/x/time/rate/sometimes.go | 67 - vendor/google.golang.org/protobuf/LICENSE | 27 - vendor/google.golang.org/protobuf/PATENTS | 22 - .../encoding/protodelim/protodelim.go | 160 - .../protobuf/encoding/prototext/decode.go | 772 - .../protobuf/encoding/prototext/doc.go | 7 - .../protobuf/encoding/prototext/encode.go | 380 - .../protobuf/encoding/protowire/wire.go | 547 - .../protobuf/internal/descfmt/stringer.go | 414 - .../protobuf/internal/descopts/options.go | 29 - .../protobuf/internal/detrand/rand.go | 69 - .../internal/editiondefaults/defaults.go | 12 - .../editiondefaults/editions_defaults.binpb | Bin 93 -> 0 bytes .../internal/encoding/defval/default.go | 213 - .../encoding/messageset/messageset.go | 242 - .../protobuf/internal/encoding/tag/tag.go | 207 - .../protobuf/internal/encoding/text/decode.go | 686 - .../internal/encoding/text/decode_number.go | 211 - .../internal/encoding/text/decode_string.go | 161 - .../internal/encoding/text/decode_token.go | 373 - .../protobuf/internal/encoding/text/doc.go | 29 - .../protobuf/internal/encoding/text/encode.go | 272 - .../protobuf/internal/errors/errors.go | 104 - .../protobuf/internal/errors/is_go112.go | 40 - .../protobuf/internal/errors/is_go113.go | 13 - .../protobuf/internal/filedesc/build.go | 157 - .../protobuf/internal/filedesc/desc.go | 737 - .../protobuf/internal/filedesc/desc_init.go | 560 - .../protobuf/internal/filedesc/desc_lazy.go | 703 - .../protobuf/internal/filedesc/desc_list.go | 457 - .../internal/filedesc/desc_list_gen.go | 367 - .../protobuf/internal/filedesc/editions.go | 156 - .../protobuf/internal/filedesc/placeholder.go | 110 - .../protobuf/internal/filetype/build.go | 296 - .../protobuf/internal/flags/flags.go | 24 - .../internal/flags/proto_legacy_disable.go | 10 - .../internal/flags/proto_legacy_enable.go | 10 - .../protobuf/internal/genid/any_gen.go | 34 - .../protobuf/internal/genid/api_gen.go | 106 - .../protobuf/internal/genid/descriptor_gen.go | 1270 - .../protobuf/internal/genid/doc.go | 11 - .../protobuf/internal/genid/duration_gen.go | 34 - .../protobuf/internal/genid/empty_gen.go | 19 - .../protobuf/internal/genid/field_mask_gen.go | 31 - .../internal/genid/go_features_gen.go | 36 - .../protobuf/internal/genid/goname.go | 25 - .../protobuf/internal/genid/map_entry.go | 16 - .../internal/genid/source_context_gen.go | 31 - .../protobuf/internal/genid/struct_gen.go | 121 - .../protobuf/internal/genid/timestamp_gen.go | 34 - .../protobuf/internal/genid/type_gen.go | 228 - .../protobuf/internal/genid/wrappers.go | 13 - .../protobuf/internal/genid/wrappers_gen.go | 175 - .../protobuf/internal/impl/api_export.go | 177 - .../protobuf/internal/impl/checkinit.go | 141 - .../protobuf/internal/impl/codec_extension.go | 228 - .../protobuf/internal/impl/codec_field.go | 863 - .../protobuf/internal/impl/codec_gen.go | 5724 -- .../protobuf/internal/impl/codec_map.go | 399 - .../protobuf/internal/impl/codec_map_go111.go | 38 - .../protobuf/internal/impl/codec_map_go112.go | 12 - .../protobuf/internal/impl/codec_message.go | 220 - .../internal/impl/codec_messageset.go | 145 - .../protobuf/internal/impl/codec_tables.go | 557 - .../protobuf/internal/impl/codec_unsafe.go | 15 - .../protobuf/internal/impl/convert.go | 495 - .../protobuf/internal/impl/convert_list.go | 141 - .../protobuf/internal/impl/convert_map.go | 121 - .../protobuf/internal/impl/decode.go | 285 - .../protobuf/internal/impl/encode.go | 237 - .../protobuf/internal/impl/enum.go | 21 - .../protobuf/internal/impl/equal.go | 224 - .../protobuf/internal/impl/extension.go | 156 - .../protobuf/internal/impl/legacy_enum.go | 219 - .../protobuf/internal/impl/legacy_export.go | 92 - .../internal/impl/legacy_extension.go | 177 - .../protobuf/internal/impl/legacy_file.go | 81 - .../protobuf/internal/impl/legacy_message.go | 572 - .../protobuf/internal/impl/merge.go | 176 - .../protobuf/internal/impl/merge_gen.go | 209 - .../protobuf/internal/impl/message.go | 284 - .../protobuf/internal/impl/message_reflect.go | 462 - .../internal/impl/message_reflect_field.go | 543 - .../internal/impl/message_reflect_gen.go | 271 - .../protobuf/internal/impl/pointer_unsafe.go | 212 - .../protobuf/internal/impl/validate.go | 576 - .../protobuf/internal/impl/weak.go | 74 - .../protobuf/internal/order/order.go | 89 - .../protobuf/internal/order/range.go | 115 - .../protobuf/internal/pragma/pragma.go | 29 - .../protobuf/internal/set/ints.go | 58 - .../protobuf/internal/strs/strings.go | 196 - .../internal/strs/strings_unsafe_go120.go | 94 - .../internal/strs/strings_unsafe_go121.go | 73 - .../protobuf/internal/version/version.go | 79 - .../protobuf/proto/checkinit.go | 71 - .../protobuf/proto/decode.go | 296 - .../protobuf/proto/decode_gen.go | 603 - .../google.golang.org/protobuf/proto/doc.go | 86 - .../protobuf/proto/encode.go | 354 - .../protobuf/proto/encode_gen.go | 97 - .../google.golang.org/protobuf/proto/equal.go | 66 - .../protobuf/proto/extension.go | 166 - .../google.golang.org/protobuf/proto/merge.go | 139 - .../protobuf/proto/messageset.go | 98 - .../google.golang.org/protobuf/proto/proto.go | 45 - .../protobuf/proto/proto_methods.go | 20 - .../protobuf/proto/proto_reflect.go | 20 - .../google.golang.org/protobuf/proto/reset.go | 43 - .../google.golang.org/protobuf/proto/size.go | 103 - .../protobuf/proto/size_gen.go | 55 - .../protobuf/proto/wrappers.go | 29 - .../protobuf/reflect/protoreflect/methods.go | 88 - .../protobuf/reflect/protoreflect/proto.go | 513 - .../protobuf/reflect/protoreflect/source.go | 129 - .../reflect/protoreflect/source_gen.go | 573 - .../protobuf/reflect/protoreflect/type.go | 672 - .../protobuf/reflect/protoreflect/value.go | 285 - .../reflect/protoreflect/value_equal.go | 168 - .../reflect/protoreflect/value_union.go | 438 - .../protoreflect/value_unsafe_go120.go | 98 - .../protoreflect/value_unsafe_go121.go | 86 - .../reflect/protoregistry/registry.go | 882 - .../protobuf/runtime/protoiface/legacy.go | 15 - .../protobuf/runtime/protoiface/methods.go | 186 - .../protobuf/runtime/protoimpl/impl.go | 44 - .../protobuf/runtime/protoimpl/version.go | 60 - .../types/known/timestamppb/timestamp.pb.go | 367 - vendor/gopkg.in/yaml.v3/LICENSE | 50 - vendor/gopkg.in/yaml.v3/NOTICE | 13 - vendor/gopkg.in/yaml.v3/README.md | 150 - vendor/gopkg.in/yaml.v3/apic.go | 747 - vendor/gopkg.in/yaml.v3/decode.go | 1000 - vendor/gopkg.in/yaml.v3/emitterc.go | 2020 - vendor/gopkg.in/yaml.v3/encode.go | 577 - vendor/gopkg.in/yaml.v3/parserc.go | 1258 - vendor/gopkg.in/yaml.v3/readerc.go | 434 - vendor/gopkg.in/yaml.v3/resolve.go | 326 - vendor/gopkg.in/yaml.v3/scannerc.go | 3038 - vendor/gopkg.in/yaml.v3/sorter.go | 134 - vendor/gopkg.in/yaml.v3/writerc.go | 48 - vendor/gopkg.in/yaml.v3/yaml.go | 698 - vendor/gopkg.in/yaml.v3/yamlh.go | 807 - vendor/gopkg.in/yaml.v3/yamlprivateh.go | 198 - vendor/modules.txt | 327 - 1815 files changed, 737895 deletions(-) delete mode 100644 vendor/github.com/BurntSushi/toml/.gitignore delete mode 100644 vendor/github.com/BurntSushi/toml/COPYING delete mode 100644 vendor/github.com/BurntSushi/toml/README.md delete mode 100644 vendor/github.com/BurntSushi/toml/decode.go delete mode 100644 vendor/github.com/BurntSushi/toml/deprecated.go delete mode 100644 vendor/github.com/BurntSushi/toml/doc.go delete mode 100644 vendor/github.com/BurntSushi/toml/encode.go delete mode 100644 vendor/github.com/BurntSushi/toml/error.go delete mode 100644 vendor/github.com/BurntSushi/toml/internal/tz.go delete mode 100644 vendor/github.com/BurntSushi/toml/lex.go delete mode 100644 vendor/github.com/BurntSushi/toml/meta.go delete mode 100644 vendor/github.com/BurntSushi/toml/parse.go delete mode 100644 vendor/github.com/BurntSushi/toml/type_fields.go delete mode 100644 vendor/github.com/BurntSushi/toml/type_toml.go delete mode 100644 vendor/github.com/Masterminds/semver/v3/.gitignore delete mode 100644 vendor/github.com/Masterminds/semver/v3/.golangci.yml delete mode 100644 vendor/github.com/Masterminds/semver/v3/CHANGELOG.md delete mode 100644 vendor/github.com/Masterminds/semver/v3/LICENSE.txt delete mode 100644 vendor/github.com/Masterminds/semver/v3/Makefile delete mode 100644 vendor/github.com/Masterminds/semver/v3/README.md delete mode 100644 vendor/github.com/Masterminds/semver/v3/collection.go delete mode 100644 vendor/github.com/Masterminds/semver/v3/constraints.go delete mode 100644 vendor/github.com/Masterminds/semver/v3/doc.go delete mode 100644 vendor/github.com/Masterminds/semver/v3/fuzz.go delete mode 100644 vendor/github.com/Masterminds/semver/v3/version.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/.gitignore delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/LICENSE delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/Makefile delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/README.md delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/api/constraint.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/api/feature.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/api/response.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/api/strategy.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/api/variant.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/bootstrap_storage.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/client.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/config.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/context/context.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/debuglistener.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/demo_app_toggles.json delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/doc.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/api/event.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/api/metrics.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/check.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_date.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_in.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_num.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_semver.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_str.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/application_hostname.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/default.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/flexible_rollout.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_random.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_session_id.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_user_id.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/helpers.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/remote_addresss.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/user_with_id.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/metrics.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/nooplistener.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/repository.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/storage.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/strategy/strategy.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/unleash.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/unleash_mock.go delete mode 100644 vendor/github.com/Unleash/unleash-client-go/v4/utils.go delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/.editorconfig delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/.gitattributes delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/.gitignore delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/.gitlab-ci.yml delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/.travis.yml delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/LICENSE delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/README.md delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/build.cmd delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/build.sh delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/doc.go delete mode 100644 vendor/github.com/apapsch/go-jsonmerge/v2/merge.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/LICENSE.txt delete mode 100644 vendor/github.com/aws/aws-sdk-go/NOTICE.txt delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/auth/bearer/token.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/client/client.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/client/logger.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/client/no_op_retryer.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/config.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_1_5.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_1_9.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_background_1_5.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/context_sleep.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/convert_types.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/corehandlers/awsinternal.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/context_background_go1.5.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/context_background_go1.7.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/context_go1.5.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/context_go1.9.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/processcreds/provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/os.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/os_windows.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/sso_cached_token.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/token_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/metric_exception.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/token_provider.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/dep_service_ids.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/legacy_regions.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/errors.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/logger.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/validation.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/credentials.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.12.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.5.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.6.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/session.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/request_context_go1.5.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/request_context_go1.7.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/stream.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/types.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/url.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/aws/version.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/context/background_go1.5.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ast.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/comma_token.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/comment_token.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/empty_token.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/expression.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/fuzz.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ini.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ini_lexer.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ini_parser.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/newline_token.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/number_helper.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/op_tokens.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/parse_error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/parse_stack.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/sep_tokens.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/skipper.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/statement.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/value_util.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/walker.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/ini/ws_token.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkio/byte.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkmath/floor.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkmath/floor_go1.9.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkrand/read.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkrand/read_1_5.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/ecs_container.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_resolve_home.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_resolve_home_go1.12.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/strings/strings.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sync/singleflight/LICENSE delete mode 100644 vendor/github.com/aws/aws-sdk-go/internal/sync/singleflight/singleflight.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/debug.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/decode.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/encode.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/shared.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/signer.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/stream_writer.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/transport.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/transport_go1.17.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/writer.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header_value.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/host.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/host_prefix.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/unmarshal_error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/protocol.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/restjson.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_error.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/sort.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/errors.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sso/api.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sso/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sso/errors.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sso/service.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sso/ssoiface/interface.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/ssooidc/api.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/ssooidc/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/ssooidc/errors.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/ssooidc/service.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sts/api.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sts/doc.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sts/errors.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sts/service.go delete mode 100644 vendor/github.com/aws/aws-sdk-go/service/sts/stsiface/interface.go delete mode 100644 vendor/github.com/beorn7/perks/LICENSE delete mode 100644 vendor/github.com/beorn7/perks/quantile/exampledata.txt delete mode 100644 vendor/github.com/beorn7/perks/quantile/stream.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/LICENSE.txt delete mode 100644 vendor/github.com/cespare/xxhash/v2/README.md delete mode 100644 vendor/github.com/cespare/xxhash/v2/testall.sh delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_asm.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_other.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_safe.go delete mode 100644 vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go delete mode 100644 vendor/github.com/davecgh/go-spew/LICENSE delete mode 100644 vendor/github.com/davecgh/go-spew/spew/bypass.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/bypasssafe.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/common.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/config.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/doc.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/dump.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/format.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/spew.go delete mode 100644 vendor/github.com/getkin/kin-openapi/LICENSE delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/callback.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/components.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/contact.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/content.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/discriminator.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/doc.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/encoding.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/errors.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/example.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/example_validation.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/extension.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/external_docs.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/header.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/helpers.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/info.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/internalize_refs.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/license.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/link.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/loader.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/loader_uri_reader.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/maplike.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/marsh.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/media_type.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/openapi3.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/operation.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/parameter.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/path_item.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/paths.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/ref.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/refs.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/refs.tmpl delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/refs_test.tmpl delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/request_body.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/response.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/schema.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/schema_formats.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/schema_pattern.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/schema_validation_settings.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/security_requirements.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/security_scheme.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/serialization_method.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/server.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/tag.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/validation_options.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/visited.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3/xml.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/authentication_input.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/errors.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/internal.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/middleware.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/options.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/req_resp_decoder.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/req_resp_encoder.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/validate_request.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/validate_request_input.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/validate_response.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/validate_response_input.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/validation_error.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/validation_error_encoder.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/validation_handler.go delete mode 100644 vendor/github.com/getkin/kin-openapi/openapi3filter/validation_kit.go delete mode 100644 vendor/github.com/getkin/kin-openapi/routers/legacy/pathpattern/node.go delete mode 100644 vendor/github.com/getkin/kin-openapi/routers/legacy/router.go delete mode 100644 vendor/github.com/getkin/kin-openapi/routers/types.go delete mode 100644 vendor/github.com/getsentry/sentry-go/.codecov.yml delete mode 100644 vendor/github.com/getsentry/sentry-go/.craft.yml delete mode 100644 vendor/github.com/getsentry/sentry-go/.gitattributes delete mode 100644 vendor/github.com/getsentry/sentry-go/.gitignore delete mode 100644 vendor/github.com/getsentry/sentry-go/.golangci.yml delete mode 100644 vendor/github.com/getsentry/sentry-go/CHANGELOG.md delete mode 100644 vendor/github.com/getsentry/sentry-go/CONTRIBUTING.md delete mode 100644 vendor/github.com/getsentry/sentry-go/LICENSE delete mode 100644 vendor/github.com/getsentry/sentry-go/MIGRATION.md delete mode 100644 vendor/github.com/getsentry/sentry-go/Makefile delete mode 100644 vendor/github.com/getsentry/sentry-go/README.md delete mode 100644 vendor/github.com/getsentry/sentry-go/check_in.go delete mode 100644 vendor/github.com/getsentry/sentry-go/client.go delete mode 100644 vendor/github.com/getsentry/sentry-go/doc.go delete mode 100644 vendor/github.com/getsentry/sentry-go/dsn.go delete mode 100644 vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go delete mode 100644 vendor/github.com/getsentry/sentry-go/echo/LICENSE delete mode 100644 vendor/github.com/getsentry/sentry-go/echo/README.md delete mode 100644 vendor/github.com/getsentry/sentry-go/echo/sentryecho.go delete mode 100644 vendor/github.com/getsentry/sentry-go/hub.go delete mode 100644 vendor/github.com/getsentry/sentry-go/integrations.go delete mode 100644 vendor/github.com/getsentry/sentry-go/interfaces.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/debug/transport.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/otel/baggage/README.md delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/otel/baggage/baggage.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage/baggage.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/ratelimit/deadline.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/ratelimit/doc.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/ratelimit/map.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/ratelimit/rate_limits.go delete mode 100644 vendor/github.com/getsentry/sentry-go/internal/ratelimit/retry_after.go delete mode 100644 vendor/github.com/getsentry/sentry-go/logrus/LICENSE delete mode 100644 vendor/github.com/getsentry/sentry-go/logrus/README.md delete mode 100644 vendor/github.com/getsentry/sentry-go/logrus/logrusentry.go delete mode 100644 vendor/github.com/getsentry/sentry-go/propagation_context.go delete mode 100644 vendor/github.com/getsentry/sentry-go/scope.go delete mode 100644 vendor/github.com/getsentry/sentry-go/sentry.go delete mode 100644 vendor/github.com/getsentry/sentry-go/sourcereader.go delete mode 100644 vendor/github.com/getsentry/sentry-go/span_recorder.go delete mode 100644 vendor/github.com/getsentry/sentry-go/stacktrace.go delete mode 100644 vendor/github.com/getsentry/sentry-go/traces_sampler.go delete mode 100644 vendor/github.com/getsentry/sentry-go/tracing.go delete mode 100644 vendor/github.com/getsentry/sentry-go/transport.go delete mode 100644 vendor/github.com/getsentry/sentry-go/util.go delete mode 100644 vendor/github.com/go-openapi/jsonpointer/.editorconfig delete mode 100644 vendor/github.com/go-openapi/jsonpointer/.gitignore delete mode 100644 vendor/github.com/go-openapi/jsonpointer/.golangci.yml delete mode 100644 vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-openapi/jsonpointer/LICENSE delete mode 100644 vendor/github.com/go-openapi/jsonpointer/README.md delete mode 100644 vendor/github.com/go-openapi/jsonpointer/pointer.go delete mode 100644 vendor/github.com/go-openapi/swag/.editorconfig delete mode 100644 vendor/github.com/go-openapi/swag/.gitattributes delete mode 100644 vendor/github.com/go-openapi/swag/.gitignore delete mode 100644 vendor/github.com/go-openapi/swag/.golangci.yml delete mode 100644 vendor/github.com/go-openapi/swag/BENCHMARK.md delete mode 100644 vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/go-openapi/swag/LICENSE delete mode 100644 vendor/github.com/go-openapi/swag/README.md delete mode 100644 vendor/github.com/go-openapi/swag/convert.go delete mode 100644 vendor/github.com/go-openapi/swag/convert_types.go delete mode 100644 vendor/github.com/go-openapi/swag/doc.go delete mode 100644 vendor/github.com/go-openapi/swag/file.go delete mode 100644 vendor/github.com/go-openapi/swag/initialism_index.go delete mode 100644 vendor/github.com/go-openapi/swag/json.go delete mode 100644 vendor/github.com/go-openapi/swag/loading.go delete mode 100644 vendor/github.com/go-openapi/swag/name_lexem.go delete mode 100644 vendor/github.com/go-openapi/swag/net.go delete mode 100644 vendor/github.com/go-openapi/swag/path.go delete mode 100644 vendor/github.com/go-openapi/swag/split.go delete mode 100644 vendor/github.com/go-openapi/swag/string_bytes.go delete mode 100644 vendor/github.com/go-openapi/swag/util.go delete mode 100644 vendor/github.com/go-openapi/swag/yaml.go delete mode 100644 vendor/github.com/google/uuid/CHANGELOG.md delete mode 100644 vendor/github.com/google/uuid/CONTRIBUTING.md delete mode 100644 vendor/github.com/google/uuid/CONTRIBUTORS delete mode 100644 vendor/github.com/google/uuid/LICENSE delete mode 100644 vendor/github.com/google/uuid/README.md delete mode 100644 vendor/github.com/google/uuid/dce.go delete mode 100644 vendor/github.com/google/uuid/doc.go delete mode 100644 vendor/github.com/google/uuid/hash.go delete mode 100644 vendor/github.com/google/uuid/marshal.go delete mode 100644 vendor/github.com/google/uuid/node.go delete mode 100644 vendor/github.com/google/uuid/node_js.go delete mode 100644 vendor/github.com/google/uuid/node_net.go delete mode 100644 vendor/github.com/google/uuid/null.go delete mode 100644 vendor/github.com/google/uuid/sql.go delete mode 100644 vendor/github.com/google/uuid/time.go delete mode 100644 vendor/github.com/google/uuid/util.go delete mode 100644 vendor/github.com/google/uuid/uuid.go delete mode 100644 vendor/github.com/google/uuid/version1.go delete mode 100644 vendor/github.com/google/uuid/version4.go delete mode 100644 vendor/github.com/google/uuid/version6.go delete mode 100644 vendor/github.com/google/uuid/version7.go delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/README.md delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/doc.go delete mode 100644 vendor/github.com/hashicorp/go-cleanhttp/handlers.go delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/.gitignore delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/.go-version delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/CHANGELOG.md delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/CODEOWNERS delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/LICENSE delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/Makefile delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/README.md delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/cert_error_go119.go delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/cert_error_go120.go delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/client.go delete mode 100644 vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go delete mode 100644 vendor/github.com/invopop/yaml/.gitignore delete mode 100644 vendor/github.com/invopop/yaml/.golangci.toml delete mode 100644 vendor/github.com/invopop/yaml/LICENSE delete mode 100644 vendor/github.com/invopop/yaml/README.md delete mode 100644 vendor/github.com/invopop/yaml/fields.go delete mode 100644 vendor/github.com/invopop/yaml/yaml.go delete mode 100644 vendor/github.com/jackc/pgerrcode/LICENSE delete mode 100644 vendor/github.com/jackc/pgerrcode/README.md delete mode 100644 vendor/github.com/jackc/pgerrcode/errcode.go delete mode 100644 vendor/github.com/jackc/pgerrcode/gen.rb delete mode 100644 vendor/github.com/jackc/pgpassfile/.travis.yml delete mode 100644 vendor/github.com/jackc/pgpassfile/LICENSE delete mode 100644 vendor/github.com/jackc/pgpassfile/README.md delete mode 100644 vendor/github.com/jackc/pgpassfile/pgpass.go delete mode 100644 vendor/github.com/jackc/pgservicefile/LICENSE delete mode 100644 vendor/github.com/jackc/pgservicefile/README.md delete mode 100644 vendor/github.com/jackc/pgservicefile/pgservicefile.go delete mode 100644 vendor/github.com/jackc/pgx/v5/.gitignore delete mode 100644 vendor/github.com/jackc/pgx/v5/CHANGELOG.md delete mode 100644 vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md delete mode 100644 vendor/github.com/jackc/pgx/v5/LICENSE delete mode 100644 vendor/github.com/jackc/pgx/v5/README.md delete mode 100644 vendor/github.com/jackc/pgx/v5/Rakefile delete mode 100644 vendor/github.com/jackc/pgx/v5/batch.go delete mode 100644 vendor/github.com/jackc/pgx/v5/conn.go delete mode 100644 vendor/github.com/jackc/pgx/v5/copy_from.go delete mode 100644 vendor/github.com/jackc/pgx/v5/derived_types.go delete mode 100644 vendor/github.com/jackc/pgx/v5/doc.go delete mode 100644 vendor/github.com/jackc/pgx/v5/extended_query_builder.go delete mode 100644 vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go delete mode 100644 vendor/github.com/jackc/pgx/v5/internal/pgio/README.md delete mode 100644 vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go delete mode 100644 vendor/github.com/jackc/pgx/v5/internal/pgio/write.go delete mode 100644 vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go delete mode 100644 vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go delete mode 100644 vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go delete mode 100644 vendor/github.com/jackc/pgx/v5/internal/stmtcache/unlimited_cache.go delete mode 100644 vendor/github.com/jackc/pgx/v5/large_objects.go delete mode 100644 vendor/github.com/jackc/pgx/v5/named_args.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/README.md delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/config.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/ctxwatch/context_watcher.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/defaults.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/doc.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/errors.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/krb5.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/README.md delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/authentication_cleartext_password.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss_continue.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/authentication_md5_password.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/authentication_ok.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/backend.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/big_endian.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/bind.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/chunkreader.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/close.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/describe.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/doc.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/execute.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/flush.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/parse.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/query.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/sync.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgproto3/trace.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/array.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/bits.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/bool.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/box.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/bytea.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/circle.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/composite.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/convert.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/date.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/doc.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/float4.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/float8.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/hstore.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/inet.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/int.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/int_test.go.erb delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test.go.erb delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test_gen.sh delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/interval.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/json.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/jsonb.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/line.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/lseg.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/ltree.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/multirange.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/numeric.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/path.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/point.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/polygon.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/qchar.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/range.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types_disabled.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/text.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/text_format_only_codec.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/tid.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/time.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/uint32.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/uint64.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/uuid.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgtype/xml.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgxpool/conn.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgxpool/doc.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgxpool/pool.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgxpool/rows.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgxpool/stat.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgxpool/tracer.go delete mode 100644 vendor/github.com/jackc/pgx/v5/pgxpool/tx.go delete mode 100644 vendor/github.com/jackc/pgx/v5/rows.go delete mode 100644 vendor/github.com/jackc/pgx/v5/tracer.go delete mode 100644 vendor/github.com/jackc/pgx/v5/tx.go delete mode 100644 vendor/github.com/jackc/pgx/v5/values.go delete mode 100644 vendor/github.com/jackc/puddle/v2/CHANGELOG.md delete mode 100644 vendor/github.com/jackc/puddle/v2/LICENSE delete mode 100644 vendor/github.com/jackc/puddle/v2/README.md delete mode 100644 vendor/github.com/jackc/puddle/v2/context.go delete mode 100644 vendor/github.com/jackc/puddle/v2/doc.go delete mode 100644 vendor/github.com/jackc/puddle/v2/internal/genstack/gen_stack.go delete mode 100644 vendor/github.com/jackc/puddle/v2/internal/genstack/stack.go delete mode 100644 vendor/github.com/jackc/puddle/v2/log.go delete mode 100644 vendor/github.com/jackc/puddle/v2/nanotime.go delete mode 100644 vendor/github.com/jackc/puddle/v2/pool.go delete mode 100644 vendor/github.com/jackc/puddle/v2/resource_list.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/.gitignore delete mode 100644 vendor/github.com/jmespath/go-jmespath/.travis.yml delete mode 100644 vendor/github.com/jmespath/go-jmespath/LICENSE delete mode 100644 vendor/github.com/jmespath/go-jmespath/Makefile delete mode 100644 vendor/github.com/jmespath/go-jmespath/README.md delete mode 100644 vendor/github.com/jmespath/go-jmespath/api.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/astnodetype_string.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/functions.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/interpreter.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/lexer.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/parser.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/toktype_string.go delete mode 100644 vendor/github.com/jmespath/go-jmespath/util.go delete mode 100644 vendor/github.com/joho/godotenv/.gitignore delete mode 100644 vendor/github.com/joho/godotenv/LICENCE delete mode 100644 vendor/github.com/joho/godotenv/README.md delete mode 100644 vendor/github.com/joho/godotenv/godotenv.go delete mode 100644 vendor/github.com/joho/godotenv/parser.go delete mode 100644 vendor/github.com/josharian/intern/README.md delete mode 100644 vendor/github.com/josharian/intern/intern.go delete mode 100644 vendor/github.com/josharian/intern/license.md delete mode 100644 vendor/github.com/klauspost/compress/.gitattributes delete mode 100644 vendor/github.com/klauspost/compress/.gitignore delete mode 100644 vendor/github.com/klauspost/compress/.goreleaser.yml delete mode 100644 vendor/github.com/klauspost/compress/LICENSE delete mode 100644 vendor/github.com/klauspost/compress/README.md delete mode 100644 vendor/github.com/klauspost/compress/SECURITY.md delete mode 100644 vendor/github.com/klauspost/compress/compressible.go delete mode 100644 vendor/github.com/klauspost/compress/fse/README.md delete mode 100644 vendor/github.com/klauspost/compress/fse/bitreader.go delete mode 100644 vendor/github.com/klauspost/compress/fse/bitwriter.go delete mode 100644 vendor/github.com/klauspost/compress/fse/bytereader.go delete mode 100644 vendor/github.com/klauspost/compress/fse/compress.go delete mode 100644 vendor/github.com/klauspost/compress/fse/decompress.go delete mode 100644 vendor/github.com/klauspost/compress/fse/fse.go delete mode 100644 vendor/github.com/klauspost/compress/gen.sh delete mode 100644 vendor/github.com/klauspost/compress/huff0/.gitignore delete mode 100644 vendor/github.com/klauspost/compress/huff0/README.md delete mode 100644 vendor/github.com/klauspost/compress/huff0/bitreader.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/bitwriter.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/compress.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/decompress.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/decompress_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/decompress_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/huff0/decompress_generic.go delete mode 100644 vendor/github.com/klauspost/compress/huff0/huff0.go delete mode 100644 vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go delete mode 100644 vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/LICENSE delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/decode.go delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/decode_other.go delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/encode.go delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/encode_other.go delete mode 100644 vendor/github.com/klauspost/compress/internal/snapref/snappy.go delete mode 100644 vendor/github.com/klauspost/compress/s2sx.mod delete mode 100644 vendor/github.com/klauspost/compress/s2sx.sum delete mode 100644 vendor/github.com/klauspost/compress/zstd/README.md delete mode 100644 vendor/github.com/klauspost/compress/zstd/bitreader.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/bitwriter.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/blockdec.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/blockenc.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/blocktype_string.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/bytebuf.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/bytereader.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/decodeheader.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/decoder.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/decoder_options.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/dict.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_base.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_best.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_better.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_dfast.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/enc_fast.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/encoder.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/encoder_options.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/framedec.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/frameenc.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_decoder.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_encoder.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/fse_predefined.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/hash.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/history.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/matchlen_generic.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqdec.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqdec_generic.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/seqenc.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/snappy.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/zip.go delete mode 100644 vendor/github.com/klauspost/compress/zstd/zstd.go delete mode 100644 vendor/github.com/labstack/echo/v4/.editorconfig delete mode 100644 vendor/github.com/labstack/echo/v4/.gitattributes delete mode 100644 vendor/github.com/labstack/echo/v4/.gitignore delete mode 100644 vendor/github.com/labstack/echo/v4/CHANGELOG.md delete mode 100644 vendor/github.com/labstack/echo/v4/LICENSE delete mode 100644 vendor/github.com/labstack/echo/v4/Makefile delete mode 100644 vendor/github.com/labstack/echo/v4/README.md delete mode 100644 vendor/github.com/labstack/echo/v4/bind.go delete mode 100644 vendor/github.com/labstack/echo/v4/binder.go delete mode 100644 vendor/github.com/labstack/echo/v4/codecov.yml delete mode 100644 vendor/github.com/labstack/echo/v4/context.go delete mode 100644 vendor/github.com/labstack/echo/v4/context_fs.go delete mode 100644 vendor/github.com/labstack/echo/v4/echo.go delete mode 100644 vendor/github.com/labstack/echo/v4/echo_fs.go delete mode 100644 vendor/github.com/labstack/echo/v4/group.go delete mode 100644 vendor/github.com/labstack/echo/v4/group_fs.go delete mode 100644 vendor/github.com/labstack/echo/v4/ip.go delete mode 100644 vendor/github.com/labstack/echo/v4/json.go delete mode 100644 vendor/github.com/labstack/echo/v4/log.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/basic_auth.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/body_dump.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/body_limit.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/compress.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/context_timeout.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/cors.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/csrf.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/decompress.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/extractor.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/key_auth.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/logger.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/method_override.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/middleware.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/proxy.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/rate_limiter.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/recover.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/redirect.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/request_id.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/request_logger.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/rewrite.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/secure.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/slash.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/static.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/static_other.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/static_windows.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/timeout.go delete mode 100644 vendor/github.com/labstack/echo/v4/middleware/util.go delete mode 100644 vendor/github.com/labstack/echo/v4/renderer.go delete mode 100644 vendor/github.com/labstack/echo/v4/response.go delete mode 100644 vendor/github.com/labstack/echo/v4/router.go delete mode 100644 vendor/github.com/labstack/gommon/LICENSE delete mode 100644 vendor/github.com/labstack/gommon/bytes/README.md delete mode 100644 vendor/github.com/labstack/gommon/bytes/bytes.go delete mode 100644 vendor/github.com/labstack/gommon/color/README.md delete mode 100644 vendor/github.com/labstack/gommon/color/color.go delete mode 100644 vendor/github.com/labstack/gommon/log/README.md delete mode 100644 vendor/github.com/labstack/gommon/log/color.go delete mode 100644 vendor/github.com/labstack/gommon/log/log.go delete mode 100644 vendor/github.com/labstack/gommon/log/white.go delete mode 100644 vendor/github.com/labstack/gommon/random/random.go delete mode 100644 vendor/github.com/mailru/easyjson/LICENSE delete mode 100644 vendor/github.com/mailru/easyjson/buffer/pool.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/bytestostr.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/error.go delete mode 100644 vendor/github.com/mailru/easyjson/jlexer/lexer.go delete mode 100644 vendor/github.com/mailru/easyjson/jwriter/writer.go delete mode 100644 vendor/github.com/mattn/go-colorable/LICENSE delete mode 100644 vendor/github.com/mattn/go-colorable/README.md delete mode 100644 vendor/github.com/mattn/go-colorable/colorable_appengine.go delete mode 100644 vendor/github.com/mattn/go-colorable/colorable_others.go delete mode 100644 vendor/github.com/mattn/go-colorable/colorable_windows.go delete mode 100644 vendor/github.com/mattn/go-colorable/go.test.sh delete mode 100644 vendor/github.com/mattn/go-colorable/noncolorable.go delete mode 100644 vendor/github.com/mattn/go-isatty/LICENSE delete mode 100644 vendor/github.com/mattn/go-isatty/README.md delete mode 100644 vendor/github.com/mattn/go-isatty/doc.go delete mode 100644 vendor/github.com/mattn/go-isatty/go.test.sh delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_bsd.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_others.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_plan9.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_solaris.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_tcgets.go delete mode 100644 vendor/github.com/mattn/go-isatty/isatty_windows.go delete mode 100644 vendor/github.com/mohae/deepcopy/.gitignore delete mode 100644 vendor/github.com/mohae/deepcopy/.travis.yml delete mode 100644 vendor/github.com/mohae/deepcopy/LICENSE delete mode 100644 vendor/github.com/mohae/deepcopy/README.md delete mode 100644 vendor/github.com/mohae/deepcopy/deepcopy.go delete mode 100644 vendor/github.com/munnerz/goautoneg/LICENSE delete mode 100644 vendor/github.com/munnerz/goautoneg/Makefile delete mode 100644 vendor/github.com/munnerz/goautoneg/README.txt delete mode 100644 vendor/github.com/munnerz/goautoneg/autoneg.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/.gitignore delete mode 100644 vendor/github.com/oapi-codegen/runtime/LICENSE delete mode 100644 vendor/github.com/oapi-codegen/runtime/Makefile delete mode 100644 vendor/github.com/oapi-codegen/runtime/README.md delete mode 100644 vendor/github.com/oapi-codegen/runtime/bind.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/bindform.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/bindparam.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/bindstring.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/deepobject.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/jsonmerge.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/renovate.json delete mode 100644 vendor/github.com/oapi-codegen/runtime/styleparam.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/types/date.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/types/email.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/types/file.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/types/regexes.go delete mode 100644 vendor/github.com/oapi-codegen/runtime/types/uuid.go delete mode 100644 vendor/github.com/osbuild/community-gateway/oidc-authorizer/LICENSE delete mode 100644 vendor/github.com/osbuild/community-gateway/oidc-authorizer/pkg/identity/identity.go delete mode 100644 vendor/github.com/osbuild/community-gateway/oidc-authorizer/pkg/identity/middleware.go delete mode 100644 vendor/github.com/osbuild/images/LICENSE delete mode 100644 vendor/github.com/osbuild/images/pkg/crypt/crypt.go delete mode 100644 vendor/github.com/osbuild/images/pkg/crypt/crypt_impl.go delete mode 100644 vendor/github.com/osbuild/images/pkg/crypt/crypt_impl_macos.go delete mode 100644 vendor/github.com/osbuild/osbuild-composer/pkg/splunk_logger/LICENSE delete mode 100644 vendor/github.com/osbuild/osbuild-composer/pkg/splunk_logger/environment_hook.go delete mode 100644 vendor/github.com/osbuild/osbuild-composer/pkg/splunk_logger/splunk_hook.go delete mode 100644 vendor/github.com/osbuild/osbuild-composer/pkg/splunk_logger/splunk_logger.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/.gitignore delete mode 100644 vendor/github.com/perimeterx/marshmallow/CHANGELOG.md delete mode 100644 vendor/github.com/perimeterx/marshmallow/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/perimeterx/marshmallow/CONTRIBUTING.md delete mode 100644 vendor/github.com/perimeterx/marshmallow/LICENSE delete mode 100644 vendor/github.com/perimeterx/marshmallow/README.md delete mode 100644 vendor/github.com/perimeterx/marshmallow/cache.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/doc.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/errors.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/options.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/reflection.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/unmarshal.go delete mode 100644 vendor/github.com/perimeterx/marshmallow/unmarshal_from_json_map.go delete mode 100644 vendor/github.com/pmezard/go-difflib/LICENSE delete mode 100644 vendor/github.com/pmezard/go-difflib/difflib/difflib.go delete mode 100644 vendor/github.com/prometheus/client_golang/LICENSE delete mode 100644 vendor/github.com/prometheus/client_golang/NOTICE delete mode 100644 vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/LICENSE delete mode 100644 vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go delete mode 100644 vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/negotiate.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/.gitignore delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/README.md delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/build_info_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/counter.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/desc.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/doc.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/fnv.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/gauge.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/get_pid.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/get_pid_gopherjs.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector_go116.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/histogram.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/almost_equal.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/go_collector_options.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/internal/metric.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/labels.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/metric.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/num_threads.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/num_threads_gopherjs.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/observer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_js.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promauto/auto.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/delegator.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/registry.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/summary.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/timer.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/untyped.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/value.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/vec.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/vnext.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/wrap.go delete mode 100644 vendor/github.com/prometheus/client_model/LICENSE delete mode 100644 vendor/github.com/prometheus/client_model/NOTICE delete mode 100644 vendor/github.com/prometheus/client_model/go/metrics.pb.go delete mode 100644 vendor/github.com/prometheus/common/LICENSE delete mode 100644 vendor/github.com/prometheus/common/NOTICE delete mode 100644 vendor/github.com/prometheus/common/expfmt/decode.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/encode.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/expfmt.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/fuzz.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/openmetrics_create.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_create.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_parse.go delete mode 100644 vendor/github.com/prometheus/common/model/alert.go delete mode 100644 vendor/github.com/prometheus/common/model/fingerprinting.go delete mode 100644 vendor/github.com/prometheus/common/model/fnv.go delete mode 100644 vendor/github.com/prometheus/common/model/labels.go delete mode 100644 vendor/github.com/prometheus/common/model/labelset.go delete mode 100644 vendor/github.com/prometheus/common/model/labelset_string.go delete mode 100644 vendor/github.com/prometheus/common/model/labelset_string_go120.go delete mode 100644 vendor/github.com/prometheus/common/model/metadata.go delete mode 100644 vendor/github.com/prometheus/common/model/metric.go delete mode 100644 vendor/github.com/prometheus/common/model/model.go delete mode 100644 vendor/github.com/prometheus/common/model/signature.go delete mode 100644 vendor/github.com/prometheus/common/model/silence.go delete mode 100644 vendor/github.com/prometheus/common/model/time.go delete mode 100644 vendor/github.com/prometheus/common/model/value.go delete mode 100644 vendor/github.com/prometheus/common/model/value_float.go delete mode 100644 vendor/github.com/prometheus/common/model/value_histogram.go delete mode 100644 vendor/github.com/prometheus/common/model/value_type.go delete mode 100644 vendor/github.com/prometheus/procfs/.gitignore delete mode 100644 vendor/github.com/prometheus/procfs/.golangci.yml delete mode 100644 vendor/github.com/prometheus/procfs/CODE_OF_CONDUCT.md delete mode 100644 vendor/github.com/prometheus/procfs/CONTRIBUTING.md delete mode 100644 vendor/github.com/prometheus/procfs/LICENSE delete mode 100644 vendor/github.com/prometheus/procfs/MAINTAINERS.md delete mode 100644 vendor/github.com/prometheus/procfs/Makefile delete mode 100644 vendor/github.com/prometheus/procfs/Makefile.common delete mode 100644 vendor/github.com/prometheus/procfs/NOTICE delete mode 100644 vendor/github.com/prometheus/procfs/README.md delete mode 100644 vendor/github.com/prometheus/procfs/SECURITY.md delete mode 100644 vendor/github.com/prometheus/procfs/arp.go delete mode 100644 vendor/github.com/prometheus/procfs/buddyinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/cmdline.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_armx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_loong64.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_others.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_s390x.go delete mode 100644 vendor/github.com/prometheus/procfs/cpuinfo_x86.go delete mode 100644 vendor/github.com/prometheus/procfs/crypto.go delete mode 100644 vendor/github.com/prometheus/procfs/doc.go delete mode 100644 vendor/github.com/prometheus/procfs/fs.go delete mode 100644 vendor/github.com/prometheus/procfs/fs_statfs_notype.go delete mode 100644 vendor/github.com/prometheus/procfs/fs_statfs_type.go delete mode 100644 vendor/github.com/prometheus/procfs/fscache.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/fs/fs.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/parse.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/readfile.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go delete mode 100644 vendor/github.com/prometheus/procfs/internal/util/valueparser.go delete mode 100644 vendor/github.com/prometheus/procfs/ipvs.go delete mode 100644 vendor/github.com/prometheus/procfs/kernel_random.go delete mode 100644 vendor/github.com/prometheus/procfs/loadavg.go delete mode 100644 vendor/github.com/prometheus/procfs/mdstat.go delete mode 100644 vendor/github.com/prometheus/procfs/meminfo.go delete mode 100644 vendor/github.com/prometheus/procfs/mountinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/mountstats.go delete mode 100644 vendor/github.com/prometheus/procfs/net_conntrackstat.go delete mode 100644 vendor/github.com/prometheus/procfs/net_dev.go delete mode 100644 vendor/github.com/prometheus/procfs/net_ip_socket.go delete mode 100644 vendor/github.com/prometheus/procfs/net_protocols.go delete mode 100644 vendor/github.com/prometheus/procfs/net_route.go delete mode 100644 vendor/github.com/prometheus/procfs/net_sockstat.go delete mode 100644 vendor/github.com/prometheus/procfs/net_softnet.go delete mode 100644 vendor/github.com/prometheus/procfs/net_tcp.go delete mode 100644 vendor/github.com/prometheus/procfs/net_tls_stat.go delete mode 100644 vendor/github.com/prometheus/procfs/net_udp.go delete mode 100644 vendor/github.com/prometheus/procfs/net_unix.go delete mode 100644 vendor/github.com/prometheus/procfs/net_wireless.go delete mode 100644 vendor/github.com/prometheus/procfs/net_xfrm.go delete mode 100644 vendor/github.com/prometheus/procfs/netstat.go delete mode 100644 vendor/github.com/prometheus/procfs/proc.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_cgroup.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_cgroups.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_environ.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_fdinfo.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_interrupts.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_io.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_limits.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_maps.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_netstat.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_ns.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_psi.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_smaps.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_snmp.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_snmp6.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_stat.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_status.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_sys.go delete mode 100644 vendor/github.com/prometheus/procfs/schedstat.go delete mode 100644 vendor/github.com/prometheus/procfs/slab.go delete mode 100644 vendor/github.com/prometheus/procfs/softirqs.go delete mode 100644 vendor/github.com/prometheus/procfs/stat.go delete mode 100644 vendor/github.com/prometheus/procfs/swaps.go delete mode 100644 vendor/github.com/prometheus/procfs/thread.go delete mode 100644 vendor/github.com/prometheus/procfs/ttar delete mode 100644 vendor/github.com/prometheus/procfs/vm.go delete mode 100644 vendor/github.com/prometheus/procfs/zoneinfo.go delete mode 100644 vendor/github.com/redhatinsights/app-common-go/pkg/api/v1/config.go delete mode 100644 vendor/github.com/redhatinsights/app-common-go/pkg/api/v1/schema.json delete mode 100644 vendor/github.com/redhatinsights/app-common-go/pkg/api/v1/types.go delete mode 100644 vendor/github.com/redhatinsights/identity/README.md delete mode 100644 vendor/github.com/redhatinsights/identity/identity.go delete mode 100644 vendor/github.com/redhatinsights/platform-go-middlewares/logging/LICENSE delete mode 100644 vendor/github.com/redhatinsights/platform-go-middlewares/logging/cloudwatch/LICENSE delete mode 100644 vendor/github.com/redhatinsights/platform-go-middlewares/logging/cloudwatch/hook.go delete mode 100644 vendor/github.com/sirupsen/logrus/.gitignore delete mode 100644 vendor/github.com/sirupsen/logrus/.golangci.yml delete mode 100644 vendor/github.com/sirupsen/logrus/.travis.yml delete mode 100644 vendor/github.com/sirupsen/logrus/CHANGELOG.md delete mode 100644 vendor/github.com/sirupsen/logrus/LICENSE delete mode 100644 vendor/github.com/sirupsen/logrus/README.md delete mode 100644 vendor/github.com/sirupsen/logrus/alt_exit.go delete mode 100644 vendor/github.com/sirupsen/logrus/appveyor.yml delete mode 100644 vendor/github.com/sirupsen/logrus/buffer_pool.go delete mode 100644 vendor/github.com/sirupsen/logrus/doc.go delete mode 100644 vendor/github.com/sirupsen/logrus/entry.go delete mode 100644 vendor/github.com/sirupsen/logrus/exported.go delete mode 100644 vendor/github.com/sirupsen/logrus/formatter.go delete mode 100644 vendor/github.com/sirupsen/logrus/hooks.go delete mode 100644 vendor/github.com/sirupsen/logrus/hooks/test/test.go delete mode 100644 vendor/github.com/sirupsen/logrus/json_formatter.go delete mode 100644 vendor/github.com/sirupsen/logrus/logger.go delete mode 100644 vendor/github.com/sirupsen/logrus/logrus.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_appengine.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_bsd.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_js.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_solaris.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_unix.go delete mode 100644 vendor/github.com/sirupsen/logrus/terminal_check_windows.go delete mode 100644 vendor/github.com/sirupsen/logrus/text_formatter.go delete mode 100644 vendor/github.com/sirupsen/logrus/writer.go delete mode 100644 vendor/github.com/stretchr/objx/.codeclimate.yml delete mode 100644 vendor/github.com/stretchr/objx/.gitignore delete mode 100644 vendor/github.com/stretchr/objx/LICENSE delete mode 100644 vendor/github.com/stretchr/objx/README.md delete mode 100644 vendor/github.com/stretchr/objx/Taskfile.yml delete mode 100644 vendor/github.com/stretchr/objx/accessors.go delete mode 100644 vendor/github.com/stretchr/objx/conversions.go delete mode 100644 vendor/github.com/stretchr/objx/doc.go delete mode 100644 vendor/github.com/stretchr/objx/map.go delete mode 100644 vendor/github.com/stretchr/objx/mutations.go delete mode 100644 vendor/github.com/stretchr/objx/security.go delete mode 100644 vendor/github.com/stretchr/objx/tests.go delete mode 100644 vendor/github.com/stretchr/objx/type_specific.go delete mode 100644 vendor/github.com/stretchr/objx/type_specific_codegen.go delete mode 100644 vendor/github.com/stretchr/objx/value.go delete mode 100644 vendor/github.com/stretchr/testify/LICENSE delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_compare.go delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_format.go delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_forward.go delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/assert/assertion_order.go delete mode 100644 vendor/github.com/stretchr/testify/assert/assertions.go delete mode 100644 vendor/github.com/stretchr/testify/assert/doc.go delete mode 100644 vendor/github.com/stretchr/testify/assert/errors.go delete mode 100644 vendor/github.com/stretchr/testify/assert/forward_assertions.go delete mode 100644 vendor/github.com/stretchr/testify/assert/http_assertions.go delete mode 100644 vendor/github.com/stretchr/testify/assert/yaml/yaml_custom.go delete mode 100644 vendor/github.com/stretchr/testify/assert/yaml/yaml_default.go delete mode 100644 vendor/github.com/stretchr/testify/assert/yaml/yaml_fail.go delete mode 100644 vendor/github.com/stretchr/testify/mock/doc.go delete mode 100644 vendor/github.com/stretchr/testify/mock/mock.go delete mode 100644 vendor/github.com/stretchr/testify/require/doc.go delete mode 100644 vendor/github.com/stretchr/testify/require/forward_requirements.go delete mode 100644 vendor/github.com/stretchr/testify/require/require.go delete mode 100644 vendor/github.com/stretchr/testify/require/require.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/require/require_forward.go delete mode 100644 vendor/github.com/stretchr/testify/require/require_forward.go.tmpl delete mode 100644 vendor/github.com/stretchr/testify/require/requirements.go delete mode 100644 vendor/github.com/twmb/murmur3/.gitignore delete mode 100644 vendor/github.com/twmb/murmur3/LICENSE delete mode 100644 vendor/github.com/twmb/murmur3/README.md delete mode 100644 vendor/github.com/twmb/murmur3/murmur.go delete mode 100644 vendor/github.com/twmb/murmur3/murmur128.go delete mode 100644 vendor/github.com/twmb/murmur3/murmur128_amd64.s delete mode 100644 vendor/github.com/twmb/murmur3/murmur128_decl.go delete mode 100644 vendor/github.com/twmb/murmur3/murmur128_gen.go delete mode 100644 vendor/github.com/twmb/murmur3/murmur32.go delete mode 100644 vendor/github.com/twmb/murmur3/murmur32_gen.go delete mode 100644 vendor/github.com/twmb/murmur3/murmur64.go delete mode 100644 vendor/github.com/valyala/bytebufferpool/.travis.yml delete mode 100644 vendor/github.com/valyala/bytebufferpool/LICENSE delete mode 100644 vendor/github.com/valyala/bytebufferpool/README.md delete mode 100644 vendor/github.com/valyala/bytebufferpool/bytebuffer.go delete mode 100644 vendor/github.com/valyala/bytebufferpool/doc.go delete mode 100644 vendor/github.com/valyala/bytebufferpool/pool.go delete mode 100644 vendor/github.com/valyala/fasttemplate/LICENSE delete mode 100644 vendor/github.com/valyala/fasttemplate/README.md delete mode 100644 vendor/github.com/valyala/fasttemplate/template.go delete mode 100644 vendor/github.com/valyala/fasttemplate/unsafe.go delete mode 100644 vendor/github.com/valyala/fasttemplate/unsafe_gae.go delete mode 100644 vendor/golang.org/x/crypto/LICENSE delete mode 100644 vendor/golang.org/x/crypto/PATENTS delete mode 100644 vendor/golang.org/x/crypto/acme/acme.go delete mode 100644 vendor/golang.org/x/crypto/acme/autocert/autocert.go delete mode 100644 vendor/golang.org/x/crypto/acme/autocert/cache.go delete mode 100644 vendor/golang.org/x/crypto/acme/autocert/listener.go delete mode 100644 vendor/golang.org/x/crypto/acme/autocert/renewal.go delete mode 100644 vendor/golang.org/x/crypto/acme/http.go delete mode 100644 vendor/golang.org/x/crypto/acme/jws.go delete mode 100644 vendor/golang.org/x/crypto/acme/rfc8555.go delete mode 100644 vendor/golang.org/x/crypto/acme/types.go delete mode 100644 vendor/golang.org/x/crypto/pbkdf2/pbkdf2.go delete mode 100644 vendor/golang.org/x/net/LICENSE delete mode 100644 vendor/golang.org/x/net/PATENTS delete mode 100644 vendor/golang.org/x/net/http/httpguts/guts.go delete mode 100644 vendor/golang.org/x/net/http/httpguts/httplex.go delete mode 100644 vendor/golang.org/x/net/http2/.gitignore delete mode 100644 vendor/golang.org/x/net/http2/ascii.go delete mode 100644 vendor/golang.org/x/net/http2/ciphers.go delete mode 100644 vendor/golang.org/x/net/http2/client_conn_pool.go delete mode 100644 vendor/golang.org/x/net/http2/config.go delete mode 100644 vendor/golang.org/x/net/http2/config_go124.go delete mode 100644 vendor/golang.org/x/net/http2/config_pre_go124.go delete mode 100644 vendor/golang.org/x/net/http2/databuffer.go delete mode 100644 vendor/golang.org/x/net/http2/errors.go delete mode 100644 vendor/golang.org/x/net/http2/flow.go delete mode 100644 vendor/golang.org/x/net/http2/frame.go delete mode 100644 vendor/golang.org/x/net/http2/gotrack.go delete mode 100644 vendor/golang.org/x/net/http2/h2c/h2c.go delete mode 100644 vendor/golang.org/x/net/http2/headermap.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/encode.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/hpack.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/huffman.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/static_table.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/tables.go delete mode 100644 vendor/golang.org/x/net/http2/http2.go delete mode 100644 vendor/golang.org/x/net/http2/pipe.go delete mode 100644 vendor/golang.org/x/net/http2/server.go delete mode 100644 vendor/golang.org/x/net/http2/timer.go delete mode 100644 vendor/golang.org/x/net/http2/transport.go delete mode 100644 vendor/golang.org/x/net/http2/unencrypted.go delete mode 100644 vendor/golang.org/x/net/http2/write.go delete mode 100644 vendor/golang.org/x/net/http2/writesched.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_priority.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_random.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_roundrobin.go delete mode 100644 vendor/golang.org/x/net/idna/go118.go delete mode 100644 vendor/golang.org/x/net/idna/idna10.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/idna9.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/pre_go118.go delete mode 100644 vendor/golang.org/x/net/idna/punycode.go delete mode 100644 vendor/golang.org/x/net/idna/tables10.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables11.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables12.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables13.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables15.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/tables9.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/trie.go delete mode 100644 vendor/golang.org/x/net/idna/trie12.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/trie13.0.0.go delete mode 100644 vendor/golang.org/x/net/idna/trieval.go delete mode 100644 vendor/golang.org/x/sync/LICENSE delete mode 100644 vendor/golang.org/x/sync/PATENTS delete mode 100644 vendor/golang.org/x/sync/semaphore/semaphore.go delete mode 100644 vendor/golang.org/x/sys/LICENSE delete mode 100644 vendor/golang.org/x/sys/PATENTS delete mode 100644 vendor/golang.org/x/sys/execabs/execabs.go delete mode 100644 vendor/golang.org/x/sys/execabs/execabs_go118.go delete mode 100644 vendor/golang.org/x/sys/execabs/execabs_go119.go delete mode 100644 vendor/golang.org/x/sys/unix/.gitignore delete mode 100644 vendor/golang.org/x/sys/unix/README.md delete mode 100644 vendor/golang.org/x/sys/unix/affinity_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/aliases.go delete mode 100644 vendor/golang.org/x/sys/unix/asm_aix_ppc64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_ppc64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_bsd_riscv64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_386.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_loong64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mips64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_mipsx.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_riscv64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_linux_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_openbsd_mips64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_solaris_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/asm_zos_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/bluetooth_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/bpxsvc_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/bpxsvc_zos.s delete mode 100644 vendor/golang.org/x/sys/unix/cap_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/constants.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/dirent.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_big.go delete mode 100644 vendor/golang.org/x/sys/unix/endian_little.go delete mode 100644 vendor/golang.org/x/sys/unix/env_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go delete mode 100644 vendor/golang.org/x/sys/unix/fdset.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_c.c delete mode 100644 vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ifreq_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_signed.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_unsigned.go delete mode 100644 vendor/golang.org/x/sys/unix/ioctl_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/mkall.sh delete mode 100644 vendor/golang.org/x/sys/unix/mkerrors.sh delete mode 100644 vendor/golang.org/x/sys/unix/mmap_nomremap.go delete mode 100644 vendor/golang.org/x/sys/unix/mremap.go delete mode 100644 vendor/golang.org/x/sys/unix/pagesize_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/pledge_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/ptrace_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/ptrace_ios.go delete mode 100644 vendor/golang.org/x/sys/unix/race.go delete mode 100644 vendor/golang.org/x/sys/unix/race0.go delete mode 100644 vendor/golang.org/x/sys/unix/readdirent_getdents.go delete mode 100644 vendor/golang.org/x/sys/unix/readdirent_getdirentries.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_unix_other.go delete mode 100644 vendor/golang.org/x/sys/unix/sockcmsg_zos.go delete mode 100644 vendor/golang.org/x/sys/unix/symaddr_zos_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/syscall.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_darwin_libSystem.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_hurd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_hurd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_illumos.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_alarm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_amd64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_libc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_gc_ppc64x.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/sysvshm_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/sysvshm_unix.go delete mode 100644 vendor/golang.org/x/sys/unix/sysvshm_unix_other.go delete mode 100644 vendor/golang.org/x/sys/unix/timestruct.go delete mode 100644 vendor/golang.org/x/sys/unix/unveil_openbsd.go delete mode 100644 vendor/golang.org/x/sys/unix/vgetrandom_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/vgetrandom_unsupported.go delete mode 100644 vendor/golang.org/x/sys/unix/xattr_bsd.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zerrors_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_armnn_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_mipsnn_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_mipsnnle_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zptrace_x86_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zsymaddr_zos_s390x.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64_gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.s delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysctl_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_aix_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_freebsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_loong64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_netbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_arm64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_mips64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_ppc64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_openbsd_riscv64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/unix/ztypes_zos_s390x.go delete mode 100644 vendor/golang.org/x/sys/windows/aliases.go delete mode 100644 vendor/golang.org/x/sys/windows/dll_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/env_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/eventlog.go delete mode 100644 vendor/golang.org/x/sys/windows/exec_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/memory_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/mkerrors.bash delete mode 100644 vendor/golang.org/x/sys/windows/mkknownfolderids.bash delete mode 100644 vendor/golang.org/x/sys/windows/mksyscall.go delete mode 100644 vendor/golang.org/x/sys/windows/race.go delete mode 100644 vendor/golang.org/x/sys/windows/race0.go delete mode 100644 vendor/golang.org/x/sys/windows/security_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/service.go delete mode 100644 vendor/golang.org/x/sys/windows/setupapi_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/str.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_386.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_amd64.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_arm.go delete mode 100644 vendor/golang.org/x/sys/windows/types_windows_arm64.go delete mode 100644 vendor/golang.org/x/sys/windows/zerrors_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/zknownfolderids_windows.go delete mode 100644 vendor/golang.org/x/sys/windows/zsyscall_windows.go delete mode 100644 vendor/golang.org/x/text/LICENSE delete mode 100644 vendor/golang.org/x/text/PATENTS delete mode 100644 vendor/golang.org/x/text/cases/cases.go delete mode 100644 vendor/golang.org/x/text/cases/context.go delete mode 100644 vendor/golang.org/x/text/cases/fold.go delete mode 100644 vendor/golang.org/x/text/cases/icu.go delete mode 100644 vendor/golang.org/x/text/cases/info.go delete mode 100644 vendor/golang.org/x/text/cases/map.go delete mode 100644 vendor/golang.org/x/text/cases/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/cases/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/cases/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/cases/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/cases/tables15.0.0.go delete mode 100644 vendor/golang.org/x/text/cases/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/cases/trieval.go delete mode 100644 vendor/golang.org/x/text/internal/internal.go delete mode 100644 vendor/golang.org/x/text/internal/language/common.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/compact.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/language.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/parents.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/tables.go delete mode 100644 vendor/golang.org/x/text/internal/language/compact/tags.go delete mode 100644 vendor/golang.org/x/text/internal/language/compose.go delete mode 100644 vendor/golang.org/x/text/internal/language/coverage.go delete mode 100644 vendor/golang.org/x/text/internal/language/language.go delete mode 100644 vendor/golang.org/x/text/internal/language/lookup.go delete mode 100644 vendor/golang.org/x/text/internal/language/match.go delete mode 100644 vendor/golang.org/x/text/internal/language/parse.go delete mode 100644 vendor/golang.org/x/text/internal/language/tables.go delete mode 100644 vendor/golang.org/x/text/internal/language/tags.go delete mode 100644 vendor/golang.org/x/text/internal/match.go delete mode 100644 vendor/golang.org/x/text/internal/tag/tag.go delete mode 100644 vendor/golang.org/x/text/language/coverage.go delete mode 100644 vendor/golang.org/x/text/language/doc.go delete mode 100644 vendor/golang.org/x/text/language/language.go delete mode 100644 vendor/golang.org/x/text/language/match.go delete mode 100644 vendor/golang.org/x/text/language/parse.go delete mode 100644 vendor/golang.org/x/text/language/tables.go delete mode 100644 vendor/golang.org/x/text/language/tags.go delete mode 100644 vendor/golang.org/x/text/runes/cond.go delete mode 100644 vendor/golang.org/x/text/runes/runes.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/precis/class.go delete mode 100644 vendor/golang.org/x/text/secure/precis/context.go delete mode 100644 vendor/golang.org/x/text/secure/precis/doc.go delete mode 100644 vendor/golang.org/x/text/secure/precis/nickname.go delete mode 100644 vendor/golang.org/x/text/secure/precis/options.go delete mode 100644 vendor/golang.org/x/text/secure/precis/profile.go delete mode 100644 vendor/golang.org/x/text/secure/precis/profiles.go delete mode 100644 vendor/golang.org/x/text/secure/precis/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/precis/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/precis/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/precis/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/precis/tables15.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/precis/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/precis/transformer.go delete mode 100644 vendor/golang.org/x/text/secure/precis/trieval.go delete mode 100644 vendor/golang.org/x/text/transform/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bidi.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/bracket.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/core.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/prop.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables15.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/trieval.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/composition.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/input.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/iter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/normalize.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables15.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/transform.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/trie.go delete mode 100644 vendor/golang.org/x/text/width/kind_string.go delete mode 100644 vendor/golang.org/x/text/width/tables10.0.0.go delete mode 100644 vendor/golang.org/x/text/width/tables11.0.0.go delete mode 100644 vendor/golang.org/x/text/width/tables12.0.0.go delete mode 100644 vendor/golang.org/x/text/width/tables13.0.0.go delete mode 100644 vendor/golang.org/x/text/width/tables15.0.0.go delete mode 100644 vendor/golang.org/x/text/width/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/width/transform.go delete mode 100644 vendor/golang.org/x/text/width/trieval.go delete mode 100644 vendor/golang.org/x/text/width/width.go delete mode 100644 vendor/golang.org/x/time/LICENSE delete mode 100644 vendor/golang.org/x/time/PATENTS delete mode 100644 vendor/golang.org/x/time/rate/rate.go delete mode 100644 vendor/golang.org/x/time/rate/sometimes.go delete mode 100644 vendor/google.golang.org/protobuf/LICENSE delete mode 100644 vendor/google.golang.org/protobuf/PATENTS delete mode 100644 vendor/google.golang.org/protobuf/encoding/protodelim/protodelim.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/decode.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/doc.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/prototext/encode.go delete mode 100644 vendor/google.golang.org/protobuf/encoding/protowire/wire.go delete mode 100644 vendor/google.golang.org/protobuf/internal/descfmt/stringer.go delete mode 100644 vendor/google.golang.org/protobuf/internal/descopts/options.go delete mode 100644 vendor/google.golang.org/protobuf/internal/detrand/rand.go delete mode 100644 vendor/google.golang.org/protobuf/internal/editiondefaults/defaults.go delete mode 100644 vendor/google.golang.org/protobuf/internal/editiondefaults/editions_defaults.binpb delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/defval/default.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/messageset/messageset.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_number.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_string.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/decode_token.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/doc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/encoding/text/encode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/errors.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/is_go112.go delete mode 100644 vendor/google.golang.org/protobuf/internal/errors/is_go113.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/build.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_list.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/editions.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filedesc/placeholder.go delete mode 100644 vendor/google.golang.org/protobuf/internal/filetype/build.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/flags.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go delete mode 100644 vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/any_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/api_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/doc.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/duration_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/empty_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/field_mask_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/go_features_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/goname.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/map_entry.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/struct_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/type_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/wrappers.go delete mode 100644 vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/api_export.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/checkinit.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_field.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_messageset.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_tables.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert_list.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/convert_map.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/decode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/encode.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/enum.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/equal.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_export.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_extension.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_file.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/legacy_message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/merge.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/merge_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect_field.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/validate.go delete mode 100644 vendor/google.golang.org/protobuf/internal/impl/weak.go delete mode 100644 vendor/google.golang.org/protobuf/internal/order/order.go delete mode 100644 vendor/google.golang.org/protobuf/internal/order/range.go delete mode 100644 vendor/google.golang.org/protobuf/internal/pragma/pragma.go delete mode 100644 vendor/google.golang.org/protobuf/internal/set/ints.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings_unsafe_go120.go delete mode 100644 vendor/google.golang.org/protobuf/internal/strs/strings_unsafe_go121.go delete mode 100644 vendor/google.golang.org/protobuf/internal/version/version.go delete mode 100644 vendor/google.golang.org/protobuf/proto/checkinit.go delete mode 100644 vendor/google.golang.org/protobuf/proto/decode.go delete mode 100644 vendor/google.golang.org/protobuf/proto/decode_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/doc.go delete mode 100644 vendor/google.golang.org/protobuf/proto/encode.go delete mode 100644 vendor/google.golang.org/protobuf/proto/encode_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/equal.go delete mode 100644 vendor/google.golang.org/protobuf/proto/extension.go delete mode 100644 vendor/google.golang.org/protobuf/proto/merge.go delete mode 100644 vendor/google.golang.org/protobuf/proto/messageset.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto_methods.go delete mode 100644 vendor/google.golang.org/protobuf/proto/proto_reflect.go delete mode 100644 vendor/google.golang.org/protobuf/proto/reset.go delete mode 100644 vendor/google.golang.org/protobuf/proto/size.go delete mode 100644 vendor/google.golang.org/protobuf/proto/size_gen.go delete mode 100644 vendor/google.golang.org/protobuf/proto/wrappers.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/proto.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/source.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/source_gen.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/type.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_equal.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe_go120.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe_go121.go delete mode 100644 vendor/google.golang.org/protobuf/reflect/protoregistry/registry.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoiface/legacy.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoiface/methods.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoimpl/impl.go delete mode 100644 vendor/google.golang.org/protobuf/runtime/protoimpl/version.go delete mode 100644 vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go delete mode 100644 vendor/gopkg.in/yaml.v3/LICENSE delete mode 100644 vendor/gopkg.in/yaml.v3/NOTICE delete mode 100644 vendor/gopkg.in/yaml.v3/README.md delete mode 100644 vendor/gopkg.in/yaml.v3/apic.go delete mode 100644 vendor/gopkg.in/yaml.v3/decode.go delete mode 100644 vendor/gopkg.in/yaml.v3/emitterc.go delete mode 100644 vendor/gopkg.in/yaml.v3/encode.go delete mode 100644 vendor/gopkg.in/yaml.v3/parserc.go delete mode 100644 vendor/gopkg.in/yaml.v3/readerc.go delete mode 100644 vendor/gopkg.in/yaml.v3/resolve.go delete mode 100644 vendor/gopkg.in/yaml.v3/scannerc.go delete mode 100644 vendor/gopkg.in/yaml.v3/sorter.go delete mode 100644 vendor/gopkg.in/yaml.v3/writerc.go delete mode 100644 vendor/gopkg.in/yaml.v3/yaml.go delete mode 100644 vendor/gopkg.in/yaml.v3/yamlh.go delete mode 100644 vendor/gopkg.in/yaml.v3/yamlprivateh.go delete mode 100644 vendor/modules.txt diff --git a/vendor/github.com/BurntSushi/toml/.gitignore b/vendor/github.com/BurntSushi/toml/.gitignore deleted file mode 100644 index fe79e3add..000000000 --- a/vendor/github.com/BurntSushi/toml/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/toml.test -/toml-test diff --git a/vendor/github.com/BurntSushi/toml/COPYING b/vendor/github.com/BurntSushi/toml/COPYING deleted file mode 100644 index 01b574320..000000000 --- a/vendor/github.com/BurntSushi/toml/COPYING +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 TOML authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/BurntSushi/toml/README.md b/vendor/github.com/BurntSushi/toml/README.md deleted file mode 100644 index 639e6c399..000000000 --- a/vendor/github.com/BurntSushi/toml/README.md +++ /dev/null @@ -1,120 +0,0 @@ -TOML stands for Tom's Obvious, Minimal Language. This Go package provides a -reflection interface similar to Go's standard library `json` and `xml` packages. - -Compatible with TOML version [v1.0.0](https://toml.io/en/v1.0.0). - -Documentation: https://godocs.io/github.com/BurntSushi/toml - -See the [releases page](https://github.com/BurntSushi/toml/releases) for a -changelog; this information is also in the git tag annotations (e.g. `git show -v0.4.0`). - -This library requires Go 1.18 or newer; add it to your go.mod with: - - % go get github.com/BurntSushi/toml@latest - -It also comes with a TOML validator CLI tool: - - % go install github.com/BurntSushi/toml/cmd/tomlv@latest - % tomlv some-toml-file.toml - -### Examples -For the simplest example, consider some TOML file as just a list of keys and -values: - -```toml -Age = 25 -Cats = [ "Cauchy", "Plato" ] -Pi = 3.14 -Perfection = [ 6, 28, 496, 8128 ] -DOB = 1987-07-05T05:45:00Z -``` - -Which can be decoded with: - -```go -type Config struct { - Age int - Cats []string - Pi float64 - Perfection []int - DOB time.Time -} - -var conf Config -_, err := toml.Decode(tomlData, &conf) -``` - -You can also use struct tags if your struct field name doesn't map to a TOML key -value directly: - -```toml -some_key_NAME = "wat" -``` - -```go -type TOML struct { - ObscureKey string `toml:"some_key_NAME"` -} -``` - -Beware that like other decoders **only exported fields** are considered when -encoding and decoding; private fields are silently ignored. - -### Using the `Marshaler` and `encoding.TextUnmarshaler` interfaces -Here's an example that automatically parses values in a `mail.Address`: - -```toml -contacts = [ - "Donald Duck ", - "Scrooge McDuck ", -] -``` - -Can be decoded with: - -```go -// Create address type which satisfies the encoding.TextUnmarshaler interface. -type address struct { - *mail.Address -} - -func (a *address) UnmarshalText(text []byte) error { - var err error - a.Address, err = mail.ParseAddress(string(text)) - return err -} - -// Decode it. -func decode() { - blob := ` - contacts = [ - "Donald Duck ", - "Scrooge McDuck ", - ] - ` - - var contacts struct { - Contacts []address - } - - _, err := toml.Decode(blob, &contacts) - if err != nil { - log.Fatal(err) - } - - for _, c := range contacts.Contacts { - fmt.Printf("%#v\n", c.Address) - } - - // Output: - // &mail.Address{Name:"Donald Duck", Address:"donald@duckburg.com"} - // &mail.Address{Name:"Scrooge McDuck", Address:"scrooge@duckburg.com"} -} -``` - -To target TOML specifically you can implement `UnmarshalTOML` TOML interface in -a similar way. - -### More complex usage -See the [`_example/`](/_example) directory for a more complex example. diff --git a/vendor/github.com/BurntSushi/toml/decode.go b/vendor/github.com/BurntSushi/toml/decode.go deleted file mode 100644 index 7aaf462c9..000000000 --- a/vendor/github.com/BurntSushi/toml/decode.go +++ /dev/null @@ -1,613 +0,0 @@ -package toml - -import ( - "bytes" - "encoding" - "encoding/json" - "fmt" - "io" - "io/fs" - "math" - "os" - "reflect" - "strconv" - "strings" - "time" -) - -// Unmarshaler is the interface implemented by objects that can unmarshal a -// TOML description of themselves. -type Unmarshaler interface { - UnmarshalTOML(any) error -} - -// Unmarshal decodes the contents of data in TOML format into a pointer v. -// -// See [Decoder] for a description of the decoding process. -func Unmarshal(data []byte, v any) error { - _, err := NewDecoder(bytes.NewReader(data)).Decode(v) - return err -} - -// Decode the TOML data in to the pointer v. -// -// See [Decoder] for a description of the decoding process. -func Decode(data string, v any) (MetaData, error) { - return NewDecoder(strings.NewReader(data)).Decode(v) -} - -// DecodeFile reads the contents of a file and decodes it with [Decode]. -func DecodeFile(path string, v any) (MetaData, error) { - fp, err := os.Open(path) - if err != nil { - return MetaData{}, err - } - defer fp.Close() - return NewDecoder(fp).Decode(v) -} - -// DecodeFS reads the contents of a file from [fs.FS] and decodes it with -// [Decode]. -func DecodeFS(fsys fs.FS, path string, v any) (MetaData, error) { - fp, err := fsys.Open(path) - if err != nil { - return MetaData{}, err - } - defer fp.Close() - return NewDecoder(fp).Decode(v) -} - -// Primitive is a TOML value that hasn't been decoded into a Go value. -// -// This type can be used for any value, which will cause decoding to be delayed. -// You can use [PrimitiveDecode] to "manually" decode these values. -// -// NOTE: The underlying representation of a `Primitive` value is subject to -// change. Do not rely on it. -// -// NOTE: Primitive values are still parsed, so using them will only avoid the -// overhead of reflection. They can be useful when you don't know the exact type -// of TOML data until runtime. -type Primitive struct { - undecoded any - context Key -} - -// The significand precision for float32 and float64 is 24 and 53 bits; this is -// the range a natural number can be stored in a float without loss of data. -const ( - maxSafeFloat32Int = 16777215 // 2^24-1 - maxSafeFloat64Int = int64(9007199254740991) // 2^53-1 -) - -// Decoder decodes TOML data. -// -// TOML tables correspond to Go structs or maps; they can be used -// interchangeably, but structs offer better type safety. -// -// TOML table arrays correspond to either a slice of structs or a slice of maps. -// -// TOML datetimes correspond to [time.Time]. Local datetimes are parsed in the -// local timezone. -// -// [time.Duration] types are treated as nanoseconds if the TOML value is an -// integer, or they're parsed with time.ParseDuration() if they're strings. -// -// All other TOML types (float, string, int, bool and array) correspond to the -// obvious Go types. -// -// An exception to the above rules is if a type implements the TextUnmarshaler -// interface, in which case any primitive TOML value (floats, strings, integers, -// booleans, datetimes) will be converted to a []byte and given to the value's -// UnmarshalText method. See the Unmarshaler example for a demonstration with -// email addresses. -// -// # Key mapping -// -// TOML keys can map to either keys in a Go map or field names in a Go struct. -// The special `toml` struct tag can be used to map TOML keys to struct fields -// that don't match the key name exactly (see the example). A case insensitive -// match to struct names will be tried if an exact match can't be found. -// -// The mapping between TOML values and Go values is loose. That is, there may -// exist TOML values that cannot be placed into your representation, and there -// may be parts of your representation that do not correspond to TOML values. -// This loose mapping can be made stricter by using the IsDefined and/or -// Undecoded methods on the MetaData returned. -// -// This decoder does not handle cyclic types. Decode will not terminate if a -// cyclic type is passed. -type Decoder struct { - r io.Reader -} - -// NewDecoder creates a new Decoder. -func NewDecoder(r io.Reader) *Decoder { - return &Decoder{r: r} -} - -var ( - unmarshalToml = reflect.TypeOf((*Unmarshaler)(nil)).Elem() - unmarshalText = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() - primitiveType = reflect.TypeOf((*Primitive)(nil)).Elem() -) - -// Decode TOML data in to the pointer `v`. -func (dec *Decoder) Decode(v any) (MetaData, error) { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr { - s := "%q" - if reflect.TypeOf(v) == nil { - s = "%v" - } - - return MetaData{}, fmt.Errorf("toml: cannot decode to non-pointer "+s, reflect.TypeOf(v)) - } - if rv.IsNil() { - return MetaData{}, fmt.Errorf("toml: cannot decode to nil value of %q", reflect.TypeOf(v)) - } - - // Check if this is a supported type: struct, map, any, or something that - // implements UnmarshalTOML or UnmarshalText. - rv = indirect(rv) - rt := rv.Type() - if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map && - !(rv.Kind() == reflect.Interface && rv.NumMethod() == 0) && - !rt.Implements(unmarshalToml) && !rt.Implements(unmarshalText) { - return MetaData{}, fmt.Errorf("toml: cannot decode to type %s", rt) - } - - // TODO: parser should read from io.Reader? Or at the very least, make it - // read from []byte rather than string - data, err := io.ReadAll(dec.r) - if err != nil { - return MetaData{}, err - } - - p, err := parse(string(data)) - if err != nil { - return MetaData{}, err - } - - md := MetaData{ - mapping: p.mapping, - keyInfo: p.keyInfo, - keys: p.ordered, - decoded: make(map[string]struct{}, len(p.ordered)), - context: nil, - data: data, - } - return md, md.unify(p.mapping, rv) -} - -// PrimitiveDecode is just like the other Decode* functions, except it decodes a -// TOML value that has already been parsed. Valid primitive values can *only* be -// obtained from values filled by the decoder functions, including this method. -// (i.e., v may contain more [Primitive] values.) -// -// Meta data for primitive values is included in the meta data returned by the -// Decode* functions with one exception: keys returned by the Undecoded method -// will only reflect keys that were decoded. Namely, any keys hidden behind a -// Primitive will be considered undecoded. Executing this method will update the -// undecoded keys in the meta data. (See the example.) -func (md *MetaData) PrimitiveDecode(primValue Primitive, v any) error { - md.context = primValue.context - defer func() { md.context = nil }() - return md.unify(primValue.undecoded, rvalue(v)) -} - -// unify performs a sort of type unification based on the structure of `rv`, -// which is the client representation. -// -// Any type mismatch produces an error. Finding a type that we don't know -// how to handle produces an unsupported type error. -func (md *MetaData) unify(data any, rv reflect.Value) error { - // Special case. Look for a `Primitive` value. - // TODO: #76 would make this superfluous after implemented. - if rv.Type() == primitiveType { - // Save the undecoded data and the key context into the primitive - // value. - context := make(Key, len(md.context)) - copy(context, md.context) - rv.Set(reflect.ValueOf(Primitive{ - undecoded: data, - context: context, - })) - return nil - } - - rvi := rv.Interface() - if v, ok := rvi.(Unmarshaler); ok { - err := v.UnmarshalTOML(data) - if err != nil { - return md.parseErr(err) - } - return nil - } - if v, ok := rvi.(encoding.TextUnmarshaler); ok { - return md.unifyText(data, v) - } - - // TODO: - // The behavior here is incorrect whenever a Go type satisfies the - // encoding.TextUnmarshaler interface but also corresponds to a TOML hash or - // array. In particular, the unmarshaler should only be applied to primitive - // TOML values. But at this point, it will be applied to all kinds of values - // and produce an incorrect error whenever those values are hashes or arrays - // (including arrays of tables). - - k := rv.Kind() - - if k >= reflect.Int && k <= reflect.Uint64 { - return md.unifyInt(data, rv) - } - switch k { - case reflect.Struct: - return md.unifyStruct(data, rv) - case reflect.Map: - return md.unifyMap(data, rv) - case reflect.Array: - return md.unifyArray(data, rv) - case reflect.Slice: - return md.unifySlice(data, rv) - case reflect.String: - return md.unifyString(data, rv) - case reflect.Bool: - return md.unifyBool(data, rv) - case reflect.Interface: - if rv.NumMethod() > 0 { /// Only empty interfaces are supported. - return md.e("unsupported type %s", rv.Type()) - } - return md.unifyAnything(data, rv) - case reflect.Float32, reflect.Float64: - return md.unifyFloat64(data, rv) - } - return md.e("unsupported type %s", rv.Kind()) -} - -func (md *MetaData) unifyStruct(mapping any, rv reflect.Value) error { - tmap, ok := mapping.(map[string]any) - if !ok { - if mapping == nil { - return nil - } - return md.e("type mismatch for %s: expected table but found %s", rv.Type().String(), fmtType(mapping)) - } - - for key, datum := range tmap { - var f *field - fields := cachedTypeFields(rv.Type()) - for i := range fields { - ff := &fields[i] - if ff.name == key { - f = ff - break - } - if f == nil && strings.EqualFold(ff.name, key) { - f = ff - } - } - if f != nil { - subv := rv - for _, i := range f.index { - subv = indirect(subv.Field(i)) - } - - if isUnifiable(subv) { - md.decoded[md.context.add(key).String()] = struct{}{} - md.context = append(md.context, key) - - err := md.unify(datum, subv) - if err != nil { - return err - } - md.context = md.context[0 : len(md.context)-1] - } else if f.name != "" { - return md.e("cannot write unexported field %s.%s", rv.Type().String(), f.name) - } - } - } - return nil -} - -func (md *MetaData) unifyMap(mapping any, rv reflect.Value) error { - keyType := rv.Type().Key().Kind() - if keyType != reflect.String && keyType != reflect.Interface { - return fmt.Errorf("toml: cannot decode to a map with non-string key type (%s in %q)", - keyType, rv.Type()) - } - - tmap, ok := mapping.(map[string]any) - if !ok { - if tmap == nil { - return nil - } - return md.badtype("map", mapping) - } - if rv.IsNil() { - rv.Set(reflect.MakeMap(rv.Type())) - } - for k, v := range tmap { - md.decoded[md.context.add(k).String()] = struct{}{} - md.context = append(md.context, k) - - rvval := reflect.Indirect(reflect.New(rv.Type().Elem())) - - err := md.unify(v, indirect(rvval)) - if err != nil { - return err - } - md.context = md.context[0 : len(md.context)-1] - - rvkey := indirect(reflect.New(rv.Type().Key())) - - switch keyType { - case reflect.Interface: - rvkey.Set(reflect.ValueOf(k)) - case reflect.String: - rvkey.SetString(k) - } - - rv.SetMapIndex(rvkey, rvval) - } - return nil -} - -func (md *MetaData) unifyArray(data any, rv reflect.Value) error { - datav := reflect.ValueOf(data) - if datav.Kind() != reflect.Slice { - if !datav.IsValid() { - return nil - } - return md.badtype("slice", data) - } - if l := datav.Len(); l != rv.Len() { - return md.e("expected array length %d; got TOML array of length %d", rv.Len(), l) - } - return md.unifySliceArray(datav, rv) -} - -func (md *MetaData) unifySlice(data any, rv reflect.Value) error { - datav := reflect.ValueOf(data) - if datav.Kind() != reflect.Slice { - if !datav.IsValid() { - return nil - } - return md.badtype("slice", data) - } - n := datav.Len() - if rv.IsNil() || rv.Cap() < n { - rv.Set(reflect.MakeSlice(rv.Type(), n, n)) - } - rv.SetLen(n) - return md.unifySliceArray(datav, rv) -} - -func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { - l := data.Len() - for i := 0; i < l; i++ { - err := md.unify(data.Index(i).Interface(), indirect(rv.Index(i))) - if err != nil { - return err - } - } - return nil -} - -func (md *MetaData) unifyString(data any, rv reflect.Value) error { - _, ok := rv.Interface().(json.Number) - if ok { - if i, ok := data.(int64); ok { - rv.SetString(strconv.FormatInt(i, 10)) - } else if f, ok := data.(float64); ok { - rv.SetString(strconv.FormatFloat(f, 'f', -1, 64)) - } else { - return md.badtype("string", data) - } - return nil - } - - if s, ok := data.(string); ok { - rv.SetString(s) - return nil - } - return md.badtype("string", data) -} - -func (md *MetaData) unifyFloat64(data any, rv reflect.Value) error { - rvk := rv.Kind() - - if num, ok := data.(float64); ok { - switch rvk { - case reflect.Float32: - if num < -math.MaxFloat32 || num > math.MaxFloat32 { - return md.parseErr(errParseRange{i: num, size: rvk.String()}) - } - fallthrough - case reflect.Float64: - rv.SetFloat(num) - default: - panic("bug") - } - return nil - } - - if num, ok := data.(int64); ok { - if (rvk == reflect.Float32 && (num < -maxSafeFloat32Int || num > maxSafeFloat32Int)) || - (rvk == reflect.Float64 && (num < -maxSafeFloat64Int || num > maxSafeFloat64Int)) { - return md.parseErr(errUnsafeFloat{i: num, size: rvk.String()}) - } - rv.SetFloat(float64(num)) - return nil - } - - return md.badtype("float", data) -} - -func (md *MetaData) unifyInt(data any, rv reflect.Value) error { - _, ok := rv.Interface().(time.Duration) - if ok { - // Parse as string duration, and fall back to regular integer parsing - // (as nanosecond) if this is not a string. - if s, ok := data.(string); ok { - dur, err := time.ParseDuration(s) - if err != nil { - return md.parseErr(errParseDuration{s}) - } - rv.SetInt(int64(dur)) - return nil - } - } - - num, ok := data.(int64) - if !ok { - return md.badtype("integer", data) - } - - rvk := rv.Kind() - switch { - case rvk >= reflect.Int && rvk <= reflect.Int64: - if (rvk == reflect.Int8 && (num < math.MinInt8 || num > math.MaxInt8)) || - (rvk == reflect.Int16 && (num < math.MinInt16 || num > math.MaxInt16)) || - (rvk == reflect.Int32 && (num < math.MinInt32 || num > math.MaxInt32)) { - return md.parseErr(errParseRange{i: num, size: rvk.String()}) - } - rv.SetInt(num) - case rvk >= reflect.Uint && rvk <= reflect.Uint64: - unum := uint64(num) - if rvk == reflect.Uint8 && (num < 0 || unum > math.MaxUint8) || - rvk == reflect.Uint16 && (num < 0 || unum > math.MaxUint16) || - rvk == reflect.Uint32 && (num < 0 || unum > math.MaxUint32) { - return md.parseErr(errParseRange{i: num, size: rvk.String()}) - } - rv.SetUint(unum) - default: - panic("unreachable") - } - return nil -} - -func (md *MetaData) unifyBool(data any, rv reflect.Value) error { - if b, ok := data.(bool); ok { - rv.SetBool(b) - return nil - } - return md.badtype("boolean", data) -} - -func (md *MetaData) unifyAnything(data any, rv reflect.Value) error { - rv.Set(reflect.ValueOf(data)) - return nil -} - -func (md *MetaData) unifyText(data any, v encoding.TextUnmarshaler) error { - var s string - switch sdata := data.(type) { - case Marshaler: - text, err := sdata.MarshalTOML() - if err != nil { - return err - } - s = string(text) - case encoding.TextMarshaler: - text, err := sdata.MarshalText() - if err != nil { - return err - } - s = string(text) - case fmt.Stringer: - s = sdata.String() - case string: - s = sdata - case bool: - s = fmt.Sprintf("%v", sdata) - case int64: - s = fmt.Sprintf("%d", sdata) - case float64: - s = fmt.Sprintf("%f", sdata) - default: - return md.badtype("primitive (string-like)", data) - } - if err := v.UnmarshalText([]byte(s)); err != nil { - return md.parseErr(err) - } - return nil -} - -func (md *MetaData) badtype(dst string, data any) error { - return md.e("incompatible types: TOML value has type %s; destination has type %s", fmtType(data), dst) -} - -func (md *MetaData) parseErr(err error) error { - k := md.context.String() - return ParseError{ - LastKey: k, - Position: md.keyInfo[k].pos, - Line: md.keyInfo[k].pos.Line, - err: err, - input: string(md.data), - } -} - -func (md *MetaData) e(format string, args ...any) error { - f := "toml: " - if len(md.context) > 0 { - f = fmt.Sprintf("toml: (last key %q): ", md.context) - p := md.keyInfo[md.context.String()].pos - if p.Line > 0 { - f = fmt.Sprintf("toml: line %d (last key %q): ", p.Line, md.context) - } - } - return fmt.Errorf(f+format, args...) -} - -// rvalue returns a reflect.Value of `v`. All pointers are resolved. -func rvalue(v any) reflect.Value { - return indirect(reflect.ValueOf(v)) -} - -// indirect returns the value pointed to by a pointer. -// -// Pointers are followed until the value is not a pointer. New values are -// allocated for each nil pointer. -// -// An exception to this rule is if the value satisfies an interface of interest -// to us (like encoding.TextUnmarshaler). -func indirect(v reflect.Value) reflect.Value { - if v.Kind() != reflect.Ptr { - if v.CanSet() { - pv := v.Addr() - pvi := pv.Interface() - if _, ok := pvi.(encoding.TextUnmarshaler); ok { - return pv - } - if _, ok := pvi.(Unmarshaler); ok { - return pv - } - } - return v - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - return indirect(reflect.Indirect(v)) -} - -func isUnifiable(rv reflect.Value) bool { - if rv.CanSet() { - return true - } - rvi := rv.Interface() - if _, ok := rvi.(encoding.TextUnmarshaler); ok { - return true - } - if _, ok := rvi.(Unmarshaler); ok { - return true - } - return false -} - -// fmt %T with "interface {}" replaced with "any", which is far more readable. -func fmtType(t any) string { - return strings.ReplaceAll(fmt.Sprintf("%T", t), "interface {}", "any") -} diff --git a/vendor/github.com/BurntSushi/toml/deprecated.go b/vendor/github.com/BurntSushi/toml/deprecated.go deleted file mode 100644 index 155709a80..000000000 --- a/vendor/github.com/BurntSushi/toml/deprecated.go +++ /dev/null @@ -1,29 +0,0 @@ -package toml - -import ( - "encoding" - "io" -) - -// TextMarshaler is an alias for encoding.TextMarshaler. -// -// Deprecated: use encoding.TextMarshaler -type TextMarshaler encoding.TextMarshaler - -// TextUnmarshaler is an alias for encoding.TextUnmarshaler. -// -// Deprecated: use encoding.TextUnmarshaler -type TextUnmarshaler encoding.TextUnmarshaler - -// DecodeReader is an alias for NewDecoder(r).Decode(v). -// -// Deprecated: use NewDecoder(reader).Decode(&value). -func DecodeReader(r io.Reader, v any) (MetaData, error) { return NewDecoder(r).Decode(v) } - -// PrimitiveDecode is an alias for MetaData.PrimitiveDecode(). -// -// Deprecated: use MetaData.PrimitiveDecode. -func PrimitiveDecode(primValue Primitive, v any) error { - md := MetaData{decoded: make(map[string]struct{})} - return md.unify(primValue.undecoded, rvalue(v)) -} diff --git a/vendor/github.com/BurntSushi/toml/doc.go b/vendor/github.com/BurntSushi/toml/doc.go deleted file mode 100644 index 82c90a905..000000000 --- a/vendor/github.com/BurntSushi/toml/doc.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package toml implements decoding and encoding of TOML files. -// -// This package supports TOML v1.0.0, as specified at https://toml.io -// -// The github.com/BurntSushi/toml/cmd/tomlv package implements a TOML validator, -// and can be used to verify if TOML document is valid. It can also be used to -// print the type of each key. -package toml diff --git a/vendor/github.com/BurntSushi/toml/encode.go b/vendor/github.com/BurntSushi/toml/encode.go deleted file mode 100644 index 73366c0d9..000000000 --- a/vendor/github.com/BurntSushi/toml/encode.go +++ /dev/null @@ -1,778 +0,0 @@ -package toml - -import ( - "bufio" - "bytes" - "encoding" - "encoding/json" - "errors" - "fmt" - "io" - "math" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/BurntSushi/toml/internal" -) - -type tomlEncodeError struct{ error } - -var ( - errArrayNilElement = errors.New("toml: cannot encode array with nil element") - errNonString = errors.New("toml: cannot encode a map with non-string key type") - errNoKey = errors.New("toml: top-level values must be Go maps or structs") - errAnything = errors.New("") // used in testing -) - -var dblQuotedReplacer = strings.NewReplacer( - "\"", "\\\"", - "\\", "\\\\", - "\x00", `\u0000`, - "\x01", `\u0001`, - "\x02", `\u0002`, - "\x03", `\u0003`, - "\x04", `\u0004`, - "\x05", `\u0005`, - "\x06", `\u0006`, - "\x07", `\u0007`, - "\b", `\b`, - "\t", `\t`, - "\n", `\n`, - "\x0b", `\u000b`, - "\f", `\f`, - "\r", `\r`, - "\x0e", `\u000e`, - "\x0f", `\u000f`, - "\x10", `\u0010`, - "\x11", `\u0011`, - "\x12", `\u0012`, - "\x13", `\u0013`, - "\x14", `\u0014`, - "\x15", `\u0015`, - "\x16", `\u0016`, - "\x17", `\u0017`, - "\x18", `\u0018`, - "\x19", `\u0019`, - "\x1a", `\u001a`, - "\x1b", `\u001b`, - "\x1c", `\u001c`, - "\x1d", `\u001d`, - "\x1e", `\u001e`, - "\x1f", `\u001f`, - "\x7f", `\u007f`, -) - -var ( - marshalToml = reflect.TypeOf((*Marshaler)(nil)).Elem() - marshalText = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() - timeType = reflect.TypeOf((*time.Time)(nil)).Elem() -) - -// Marshaler is the interface implemented by types that can marshal themselves -// into valid TOML. -type Marshaler interface { - MarshalTOML() ([]byte, error) -} - -// Marshal returns a TOML representation of the Go value. -// -// See [Encoder] for a description of the encoding process. -func Marshal(v any) ([]byte, error) { - buff := new(bytes.Buffer) - if err := NewEncoder(buff).Encode(v); err != nil { - return nil, err - } - return buff.Bytes(), nil -} - -// Encoder encodes a Go to a TOML document. -// -// The mapping between Go values and TOML values should be precisely the same as -// for [Decode]. -// -// time.Time is encoded as a RFC 3339 string, and time.Duration as its string -// representation. -// -// The [Marshaler] and [encoding.TextMarshaler] interfaces are supported to -// encoding the value as custom TOML. -// -// If you want to write arbitrary binary data then you will need to use -// something like base64 since TOML does not have any binary types. -// -// When encoding TOML hashes (Go maps or structs), keys without any sub-hashes -// are encoded first. -// -// Go maps will be sorted alphabetically by key for deterministic output. -// -// The toml struct tag can be used to provide the key name; if omitted the -// struct field name will be used. If the "omitempty" option is present the -// following value will be skipped: -// -// - arrays, slices, maps, and string with len of 0 -// - struct with all zero values -// - bool false -// -// If omitzero is given all int and float types with a value of 0 will be -// skipped. -// -// Encoding Go values without a corresponding TOML representation will return an -// error. Examples of this includes maps with non-string keys, slices with nil -// elements, embedded non-struct types, and nested slices containing maps or -// structs. (e.g. [][]map[string]string is not allowed but []map[string]string -// is okay, as is []map[string][]string). -// -// NOTE: only exported keys are encoded due to the use of reflection. Unexported -// keys are silently discarded. -type Encoder struct { - Indent string // string for a single indentation level; default is two spaces. - hasWritten bool // written any output to w yet? - w *bufio.Writer -} - -// NewEncoder create a new Encoder. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{w: bufio.NewWriter(w), Indent: " "} -} - -// Encode writes a TOML representation of the Go value to the [Encoder]'s writer. -// -// An error is returned if the value given cannot be encoded to a valid TOML -// document. -func (enc *Encoder) Encode(v any) error { - rv := eindirect(reflect.ValueOf(v)) - err := enc.safeEncode(Key([]string{}), rv) - if err != nil { - return err - } - return enc.w.Flush() -} - -func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) { - defer func() { - if r := recover(); r != nil { - if terr, ok := r.(tomlEncodeError); ok { - err = terr.error - return - } - panic(r) - } - }() - enc.encode(key, rv) - return nil -} - -func (enc *Encoder) encode(key Key, rv reflect.Value) { - // If we can marshal the type to text, then we use that. This prevents the - // encoder for handling these types as generic structs (or whatever the - // underlying type of a TextMarshaler is). - switch { - case isMarshaler(rv): - enc.writeKeyValue(key, rv, false) - return - case rv.Type() == primitiveType: // TODO: #76 would make this superfluous after implemented. - enc.encode(key, reflect.ValueOf(rv.Interface().(Primitive).undecoded)) - return - } - - k := rv.Kind() - switch k { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64, - reflect.Float32, reflect.Float64, reflect.String, reflect.Bool: - enc.writeKeyValue(key, rv, false) - case reflect.Array, reflect.Slice: - if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) { - enc.eArrayOfTables(key, rv) - } else { - enc.writeKeyValue(key, rv, false) - } - case reflect.Interface: - if rv.IsNil() { - return - } - enc.encode(key, rv.Elem()) - case reflect.Map: - if rv.IsNil() { - return - } - enc.eTable(key, rv) - case reflect.Ptr: - if rv.IsNil() { - return - } - enc.encode(key, rv.Elem()) - case reflect.Struct: - enc.eTable(key, rv) - default: - encPanic(fmt.Errorf("unsupported type for key '%s': %s", key, k)) - } -} - -// eElement encodes any value that can be an array element. -func (enc *Encoder) eElement(rv reflect.Value) { - switch v := rv.Interface().(type) { - case time.Time: // Using TextMarshaler adds extra quotes, which we don't want. - format := time.RFC3339Nano - switch v.Location() { - case internal.LocalDatetime: - format = "2006-01-02T15:04:05.999999999" - case internal.LocalDate: - format = "2006-01-02" - case internal.LocalTime: - format = "15:04:05.999999999" - } - switch v.Location() { - default: - enc.wf(v.Format(format)) - case internal.LocalDatetime, internal.LocalDate, internal.LocalTime: - enc.wf(v.In(time.UTC).Format(format)) - } - return - case Marshaler: - s, err := v.MarshalTOML() - if err != nil { - encPanic(err) - } - if s == nil { - encPanic(errors.New("MarshalTOML returned nil and no error")) - } - enc.w.Write(s) - return - case encoding.TextMarshaler: - s, err := v.MarshalText() - if err != nil { - encPanic(err) - } - if s == nil { - encPanic(errors.New("MarshalText returned nil and no error")) - } - enc.writeQuoted(string(s)) - return - case time.Duration: - enc.writeQuoted(v.String()) - return - case json.Number: - n, _ := rv.Interface().(json.Number) - - if n == "" { /// Useful zero value. - enc.w.WriteByte('0') - return - } else if v, err := n.Int64(); err == nil { - enc.eElement(reflect.ValueOf(v)) - return - } else if v, err := n.Float64(); err == nil { - enc.eElement(reflect.ValueOf(v)) - return - } - encPanic(fmt.Errorf("unable to convert %q to int64 or float64", n)) - } - - switch rv.Kind() { - case reflect.Ptr: - enc.eElement(rv.Elem()) - return - case reflect.String: - enc.writeQuoted(rv.String()) - case reflect.Bool: - enc.wf(strconv.FormatBool(rv.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - enc.wf(strconv.FormatInt(rv.Int(), 10)) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - enc.wf(strconv.FormatUint(rv.Uint(), 10)) - case reflect.Float32: - f := rv.Float() - if math.IsNaN(f) { - if math.Signbit(f) { - enc.wf("-") - } - enc.wf("nan") - } else if math.IsInf(f, 0) { - if math.Signbit(f) { - enc.wf("-") - } - enc.wf("inf") - } else { - enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 32))) - } - case reflect.Float64: - f := rv.Float() - if math.IsNaN(f) { - if math.Signbit(f) { - enc.wf("-") - } - enc.wf("nan") - } else if math.IsInf(f, 0) { - if math.Signbit(f) { - enc.wf("-") - } - enc.wf("inf") - } else { - enc.wf(floatAddDecimal(strconv.FormatFloat(f, 'f', -1, 64))) - } - case reflect.Array, reflect.Slice: - enc.eArrayOrSliceElement(rv) - case reflect.Struct: - enc.eStruct(nil, rv, true) - case reflect.Map: - enc.eMap(nil, rv, true) - case reflect.Interface: - enc.eElement(rv.Elem()) - default: - encPanic(fmt.Errorf("unexpected type: %s", fmtType(rv.Interface()))) - } -} - -// By the TOML spec, all floats must have a decimal with at least one number on -// either side. -func floatAddDecimal(fstr string) string { - if !strings.Contains(fstr, ".") { - return fstr + ".0" - } - return fstr -} - -func (enc *Encoder) writeQuoted(s string) { - enc.wf("\"%s\"", dblQuotedReplacer.Replace(s)) -} - -func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) { - length := rv.Len() - enc.wf("[") - for i := 0; i < length; i++ { - elem := eindirect(rv.Index(i)) - enc.eElement(elem) - if i != length-1 { - enc.wf(", ") - } - } - enc.wf("]") -} - -func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) { - if len(key) == 0 { - encPanic(errNoKey) - } - for i := 0; i < rv.Len(); i++ { - trv := eindirect(rv.Index(i)) - if isNil(trv) { - continue - } - enc.newline() - enc.wf("%s[[%s]]", enc.indentStr(key), key) - enc.newline() - enc.eMapOrStruct(key, trv, false) - } -} - -func (enc *Encoder) eTable(key Key, rv reflect.Value) { - if len(key) == 1 { - // Output an extra newline between top-level tables. - // (The newline isn't written if nothing else has been written though.) - enc.newline() - } - if len(key) > 0 { - enc.wf("%s[%s]", enc.indentStr(key), key) - enc.newline() - } - enc.eMapOrStruct(key, rv, false) -} - -func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value, inline bool) { - switch rv.Kind() { - case reflect.Map: - enc.eMap(key, rv, inline) - case reflect.Struct: - enc.eStruct(key, rv, inline) - default: - // Should never happen? - panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String()) - } -} - -func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) { - rt := rv.Type() - if rt.Key().Kind() != reflect.String { - encPanic(errNonString) - } - - // Sort keys so that we have deterministic output. And write keys directly - // underneath this key first, before writing sub-structs or sub-maps. - var mapKeysDirect, mapKeysSub []string - for _, mapKey := range rv.MapKeys() { - k := mapKey.String() - if typeIsTable(tomlTypeOfGo(eindirect(rv.MapIndex(mapKey)))) { - mapKeysSub = append(mapKeysSub, k) - } else { - mapKeysDirect = append(mapKeysDirect, k) - } - } - - var writeMapKeys = func(mapKeys []string, trailC bool) { - sort.Strings(mapKeys) - for i, mapKey := range mapKeys { - val := eindirect(rv.MapIndex(reflect.ValueOf(mapKey))) - if isNil(val) { - continue - } - - if inline { - enc.writeKeyValue(Key{mapKey}, val, true) - if trailC || i != len(mapKeys)-1 { - enc.wf(", ") - } - } else { - enc.encode(key.add(mapKey), val) - } - } - } - - if inline { - enc.wf("{") - } - writeMapKeys(mapKeysDirect, len(mapKeysSub) > 0) - writeMapKeys(mapKeysSub, false) - if inline { - enc.wf("}") - } -} - -const is32Bit = (32 << (^uint(0) >> 63)) == 32 - -func pointerTo(t reflect.Type) reflect.Type { - if t.Kind() == reflect.Ptr { - return pointerTo(t.Elem()) - } - return t -} - -func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { - // Write keys for fields directly under this key first, because if we write - // a field that creates a new table then all keys under it will be in that - // table (not the one we're writing here). - // - // Fields is a [][]int: for fieldsDirect this always has one entry (the - // struct index). For fieldsSub it contains two entries: the parent field - // index from tv, and the field indexes for the fields of the sub. - var ( - rt = rv.Type() - fieldsDirect, fieldsSub [][]int - addFields func(rt reflect.Type, rv reflect.Value, start []int) - ) - addFields = func(rt reflect.Type, rv reflect.Value, start []int) { - for i := 0; i < rt.NumField(); i++ { - f := rt.Field(i) - isEmbed := f.Anonymous && pointerTo(f.Type).Kind() == reflect.Struct - if f.PkgPath != "" && !isEmbed { /// Skip unexported fields. - continue - } - opts := getOptions(f.Tag) - if opts.skip { - continue - } - - frv := eindirect(rv.Field(i)) - - if is32Bit { - // Copy so it works correct on 32bit archs; not clear why this - // is needed. See #314, and https://www.reddit.com/r/golang/comments/pnx8v4 - // This also works fine on 64bit, but 32bit archs are somewhat - // rare and this is a wee bit faster. - copyStart := make([]int, len(start)) - copy(copyStart, start) - start = copyStart - } - - // Treat anonymous struct fields with tag names as though they are - // not anonymous, like encoding/json does. - // - // Non-struct anonymous fields use the normal encoding logic. - if isEmbed { - if getOptions(f.Tag).name == "" && frv.Kind() == reflect.Struct { - addFields(frv.Type(), frv, append(start, f.Index...)) - continue - } - } - - if typeIsTable(tomlTypeOfGo(frv)) { - fieldsSub = append(fieldsSub, append(start, f.Index...)) - } else { - fieldsDirect = append(fieldsDirect, append(start, f.Index...)) - } - } - } - addFields(rt, rv, nil) - - writeFields := func(fields [][]int) { - for _, fieldIndex := range fields { - fieldType := rt.FieldByIndex(fieldIndex) - fieldVal := rv.FieldByIndex(fieldIndex) - - opts := getOptions(fieldType.Tag) - if opts.skip { - continue - } - if opts.omitempty && isEmpty(fieldVal) { - continue - } - - fieldVal = eindirect(fieldVal) - - if isNil(fieldVal) { /// Don't write anything for nil fields. - continue - } - - keyName := fieldType.Name - if opts.name != "" { - keyName = opts.name - } - - if opts.omitzero && isZero(fieldVal) { - continue - } - - if inline { - enc.writeKeyValue(Key{keyName}, fieldVal, true) - if fieldIndex[0] != len(fields)-1 { - enc.wf(", ") - } - } else { - enc.encode(key.add(keyName), fieldVal) - } - } - } - - if inline { - enc.wf("{") - } - writeFields(fieldsDirect) - writeFields(fieldsSub) - if inline { - enc.wf("}") - } -} - -// tomlTypeOfGo returns the TOML type name of the Go value's type. -// -// It is used to determine whether the types of array elements are mixed (which -// is forbidden). If the Go value is nil, then it is illegal for it to be an -// array element, and valueIsNil is returned as true. -// -// The type may be `nil`, which means no concrete TOML type could be found. -func tomlTypeOfGo(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() { - return nil - } - - if rv.Kind() == reflect.Struct { - if rv.Type() == timeType { - return tomlDatetime - } - if isMarshaler(rv) { - return tomlString - } - return tomlHash - } - - if isMarshaler(rv) { - return tomlString - } - - switch rv.Kind() { - case reflect.Bool: - return tomlBool - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64: - return tomlInteger - case reflect.Float32, reflect.Float64: - return tomlFloat - case reflect.Array, reflect.Slice: - if isTableArray(rv) { - return tomlArrayHash - } - return tomlArray - case reflect.Ptr, reflect.Interface: - return tomlTypeOfGo(rv.Elem()) - case reflect.String: - return tomlString - case reflect.Map: - return tomlHash - default: - encPanic(errors.New("unsupported type: " + rv.Kind().String())) - panic("unreachable") - } -} - -func isMarshaler(rv reflect.Value) bool { - return rv.Type().Implements(marshalText) || rv.Type().Implements(marshalToml) -} - -// isTableArray reports if all entries in the array or slice are a table. -func isTableArray(arr reflect.Value) bool { - if isNil(arr) || !arr.IsValid() || arr.Len() == 0 { - return false - } - - ret := true - for i := 0; i < arr.Len(); i++ { - tt := tomlTypeOfGo(eindirect(arr.Index(i))) - // Don't allow nil. - if tt == nil { - encPanic(errArrayNilElement) - } - - if ret && !typeEqual(tomlHash, tt) { - ret = false - } - } - return ret -} - -type tagOptions struct { - skip bool // "-" - name string - omitempty bool - omitzero bool -} - -func getOptions(tag reflect.StructTag) tagOptions { - t := tag.Get("toml") - if t == "-" { - return tagOptions{skip: true} - } - var opts tagOptions - parts := strings.Split(t, ",") - opts.name = parts[0] - for _, s := range parts[1:] { - switch s { - case "omitempty": - opts.omitempty = true - case "omitzero": - opts.omitzero = true - } - } - return opts -} - -func isZero(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return rv.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return rv.Uint() == 0 - case reflect.Float32, reflect.Float64: - return rv.Float() == 0.0 - } - return false -} - -func isEmpty(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Array, reflect.Slice, reflect.Map, reflect.String: - return rv.Len() == 0 - case reflect.Struct: - if rv.Type().Comparable() { - return reflect.Zero(rv.Type()).Interface() == rv.Interface() - } - // Need to also check if all the fields are empty, otherwise something - // like this with uncomparable types will always return true: - // - // type a struct{ field b } - // type b struct{ s []string } - // s := a{field: b{s: []string{"AAA"}}} - for i := 0; i < rv.NumField(); i++ { - if !isEmpty(rv.Field(i)) { - return false - } - } - return true - case reflect.Bool: - return !rv.Bool() - case reflect.Ptr: - return rv.IsNil() - } - return false -} - -func (enc *Encoder) newline() { - if enc.hasWritten { - enc.wf("\n") - } -} - -// Write a key/value pair: -// -// key = -// -// This is also used for "k = v" in inline tables; so something like this will -// be written in three calls: -// -// ┌───────────────────┐ -// │ ┌───┐ ┌────┐│ -// v v v v vv -// key = {k = 1, k2 = 2} -func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) { - /// Marshaler used on top-level document; call eElement() to just call - /// Marshal{TOML,Text}. - if len(key) == 0 { - enc.eElement(val) - return - } - enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1)) - enc.eElement(val) - if !inline { - enc.newline() - } -} - -func (enc *Encoder) wf(format string, v ...any) { - _, err := fmt.Fprintf(enc.w, format, v...) - if err != nil { - encPanic(err) - } - enc.hasWritten = true -} - -func (enc *Encoder) indentStr(key Key) string { - return strings.Repeat(enc.Indent, len(key)-1) -} - -func encPanic(err error) { - panic(tomlEncodeError{err}) -} - -// Resolve any level of pointers to the actual value (e.g. **string → string). -func eindirect(v reflect.Value) reflect.Value { - if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface { - if isMarshaler(v) { - return v - } - if v.CanAddr() { /// Special case for marshalers; see #358. - if pv := v.Addr(); isMarshaler(pv) { - return pv - } - } - return v - } - - if v.IsNil() { - return v - } - - return eindirect(v.Elem()) -} - -func isNil(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return rv.IsNil() - default: - return false - } -} diff --git a/vendor/github.com/BurntSushi/toml/error.go b/vendor/github.com/BurntSushi/toml/error.go deleted file mode 100644 index b45a3f45f..000000000 --- a/vendor/github.com/BurntSushi/toml/error.go +++ /dev/null @@ -1,356 +0,0 @@ -package toml - -import ( - "fmt" - "strings" -) - -// ParseError is returned when there is an error parsing the TOML syntax such as -// invalid syntax, duplicate keys, etc. -// -// In addition to the error message itself, you can also print detailed location -// information with context by using [ErrorWithPosition]: -// -// toml: error: Key 'fruit' was already created and cannot be used as an array. -// -// At line 4, column 2-7: -// -// 2 | fruit = [] -// 3 | -// 4 | [[fruit]] # Not allowed -// ^^^^^ -// -// [ErrorWithUsage] can be used to print the above with some more detailed usage -// guidance: -// -// toml: error: newlines not allowed within inline tables -// -// At line 1, column 18: -// -// 1 | x = [{ key = 42 # -// ^ -// -// Error help: -// -// Inline tables must always be on a single line: -// -// table = {key = 42, second = 43} -// -// It is invalid to split them over multiple lines like so: -// -// # INVALID -// table = { -// key = 42, -// second = 43 -// } -// -// Use regular for this: -// -// [table] -// key = 42 -// second = 43 -type ParseError struct { - Message string // Short technical message. - Usage string // Longer message with usage guidance; may be blank. - Position Position // Position of the error - LastKey string // Last parsed key, may be blank. - - // Line the error occurred. - // - // Deprecated: use [Position]. - Line int - - err error - input string -} - -// Position of an error. -type Position struct { - Line int // Line number, starting at 1. - Start int // Start of error, as byte offset starting at 0. - Len int // Lenght in bytes. -} - -func (pe ParseError) Error() string { - msg := pe.Message - if msg == "" { // Error from errorf() - msg = pe.err.Error() - } - - if pe.LastKey == "" { - return fmt.Sprintf("toml: line %d: %s", pe.Position.Line, msg) - } - return fmt.Sprintf("toml: line %d (last key %q): %s", - pe.Position.Line, pe.LastKey, msg) -} - -// ErrorWithPosition returns the error with detailed location context. -// -// See the documentation on [ParseError]. -func (pe ParseError) ErrorWithPosition() string { - if pe.input == "" { // Should never happen, but just in case. - return pe.Error() - } - - var ( - lines = strings.Split(pe.input, "\n") - col = pe.column(lines) - b = new(strings.Builder) - ) - - msg := pe.Message - if msg == "" { - msg = pe.err.Error() - } - - // TODO: don't show control characters as literals? This may not show up - // well everywhere. - - if pe.Position.Len == 1 { - fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d:\n\n", - msg, pe.Position.Line, col+1) - } else { - fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d-%d:\n\n", - msg, pe.Position.Line, col, col+pe.Position.Len) - } - if pe.Position.Line > 2 { - fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, expandTab(lines[pe.Position.Line-3])) - } - if pe.Position.Line > 1 { - fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2])) - } - - /// Expand tabs, so that the ^^^s are at the correct position, but leave - /// "column 10-13" intact. Adjusting this to the visual column would be - /// better, but we don't know the tabsize of the user in their editor, which - /// can be 8, 4, 2, or something else. We can't know. So leaving it as the - /// character index is probably the "most correct". - expanded := expandTab(lines[pe.Position.Line-1]) - diff := len(expanded) - len(lines[pe.Position.Line-1]) - - fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, expanded) - fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", col+diff), strings.Repeat("^", pe.Position.Len)) - return b.String() -} - -// ErrorWithUsage returns the error with detailed location context and usage -// guidance. -// -// See the documentation on [ParseError]. -func (pe ParseError) ErrorWithUsage() string { - m := pe.ErrorWithPosition() - if u, ok := pe.err.(interface{ Usage() string }); ok && u.Usage() != "" { - lines := strings.Split(strings.TrimSpace(u.Usage()), "\n") - for i := range lines { - if lines[i] != "" { - lines[i] = " " + lines[i] - } - } - return m + "Error help:\n\n" + strings.Join(lines, "\n") + "\n" - } - return m -} - -func (pe ParseError) column(lines []string) int { - var pos, col int - for i := range lines { - ll := len(lines[i]) + 1 // +1 for the removed newline - if pos+ll >= pe.Position.Start { - col = pe.Position.Start - pos - if col < 0 { // Should never happen, but just in case. - col = 0 - } - break - } - pos += ll - } - - return col -} - -func expandTab(s string) string { - var ( - b strings.Builder - l int - fill = func(n int) string { - b := make([]byte, n) - for i := range b { - b[i] = ' ' - } - return string(b) - } - ) - b.Grow(len(s)) - for _, r := range s { - switch r { - case '\t': - tw := 8 - l%8 - b.WriteString(fill(tw)) - l += tw - default: - b.WriteRune(r) - l += 1 - } - } - return b.String() -} - -type ( - errLexControl struct{ r rune } - errLexEscape struct{ r rune } - errLexUTF8 struct{ b byte } - errParseDate struct{ v string } - errLexInlineTableNL struct{} - errLexStringNL struct{} - errParseRange struct { - i any // int or float - size string // "int64", "uint16", etc. - } - errUnsafeFloat struct { - i interface{} // float32 or float64 - size string // "float32" or "float64" - } - errParseDuration struct{ d string } -) - -func (e errLexControl) Error() string { - return fmt.Sprintf("TOML files cannot contain control characters: '0x%02x'", e.r) -} -func (e errLexControl) Usage() string { return "" } - -func (e errLexEscape) Error() string { return fmt.Sprintf(`invalid escape in string '\%c'`, e.r) } -func (e errLexEscape) Usage() string { return usageEscape } -func (e errLexUTF8) Error() string { return fmt.Sprintf("invalid UTF-8 byte: 0x%02x", e.b) } -func (e errLexUTF8) Usage() string { return "" } -func (e errParseDate) Error() string { return fmt.Sprintf("invalid datetime: %q", e.v) } -func (e errParseDate) Usage() string { return usageDate } -func (e errLexInlineTableNL) Error() string { return "newlines not allowed within inline tables" } -func (e errLexInlineTableNL) Usage() string { return usageInlineNewline } -func (e errLexStringNL) Error() string { return "strings cannot contain newlines" } -func (e errLexStringNL) Usage() string { return usageStringNewline } -func (e errParseRange) Error() string { return fmt.Sprintf("%v is out of range for %s", e.i, e.size) } -func (e errParseRange) Usage() string { return usageIntOverflow } -func (e errUnsafeFloat) Error() string { - return fmt.Sprintf("%v is out of the safe %s range", e.i, e.size) -} -func (e errUnsafeFloat) Usage() string { return usageUnsafeFloat } -func (e errParseDuration) Error() string { return fmt.Sprintf("invalid duration: %q", e.d) } -func (e errParseDuration) Usage() string { return usageDuration } - -const usageEscape = ` -A '\' inside a "-delimited string is interpreted as an escape character. - -The following escape sequences are supported: -\b, \t, \n, \f, \r, \", \\, \uXXXX, and \UXXXXXXXX - -To prevent a '\' from being recognized as an escape character, use either: - -- a ' or '''-delimited string; escape characters aren't processed in them; or -- write two backslashes to get a single backslash: '\\'. - -If you're trying to add a Windows path (e.g. "C:\Users\martin") then using '/' -instead of '\' will usually also work: "C:/Users/martin". -` - -const usageInlineNewline = ` -Inline tables must always be on a single line: - - table = {key = 42, second = 43} - -It is invalid to split them over multiple lines like so: - - # INVALID - table = { - key = 42, - second = 43 - } - -Use regular for this: - - [table] - key = 42 - second = 43 -` - -const usageStringNewline = ` -Strings must always be on a single line, and cannot span more than one line: - - # INVALID - string = "Hello, - world!" - -Instead use """ or ''' to split strings over multiple lines: - - string = """Hello, - world!""" -` - -const usageIntOverflow = ` -This number is too large; this may be an error in the TOML, but it can also be a -bug in the program that uses too small of an integer. - -The maximum and minimum values are: - - size │ lowest │ highest - ───────┼────────────────┼────────────── - int8 │ -128 │ 127 - int16 │ -32,768 │ 32,767 - int32 │ -2,147,483,648 │ 2,147,483,647 - int64 │ -9.2 × 10¹⁷ │ 9.2 × 10¹⁷ - uint8 │ 0 │ 255 - uint16 │ 0 │ 65,535 - uint32 │ 0 │ 4,294,967,295 - uint64 │ 0 │ 1.8 × 10¹⁸ - -int refers to int32 on 32-bit systems and int64 on 64-bit systems. -` - -const usageUnsafeFloat = ` -This number is outside of the "safe" range for floating point numbers; whole -(non-fractional) numbers outside the below range can not always be represented -accurately in a float, leading to some loss of accuracy. - -Explicitly mark a number as a fractional unit by adding ".0", which will incur -some loss of accuracy; for example: - - f = 2_000_000_000.0 - -Accuracy ranges: - - float32 = 16,777,215 - float64 = 9,007,199,254,740,991 -` - -const usageDuration = ` -A duration must be as "number", without any spaces. Valid units are: - - ns nanoseconds (billionth of a second) - us, µs microseconds (millionth of a second) - ms milliseconds (thousands of a second) - s seconds - m minutes - h hours - -You can combine multiple units; for example "5m10s" for 5 minutes and 10 -seconds. -` - -const usageDate = ` -A TOML datetime must be in one of the following formats: - - 2006-01-02T15:04:05Z07:00 Date and time, with timezone. - 2006-01-02T15:04:05 Date and time, but without timezone. - 2006-01-02 Date without a time or timezone. - 15:04:05 Just a time, without any timezone. - -Seconds may optionally have a fraction, up to nanosecond precision: - - 15:04:05.123 - 15:04:05.856018510 -` - -// TOML 1.1: -// The seconds part in times is optional, and may be omitted: -// 2006-01-02T15:04Z07:00 -// 2006-01-02T15:04 -// 15:04 diff --git a/vendor/github.com/BurntSushi/toml/internal/tz.go b/vendor/github.com/BurntSushi/toml/internal/tz.go deleted file mode 100644 index 022f15bc2..000000000 --- a/vendor/github.com/BurntSushi/toml/internal/tz.go +++ /dev/null @@ -1,36 +0,0 @@ -package internal - -import "time" - -// Timezones used for local datetime, date, and time TOML types. -// -// The exact way times and dates without a timezone should be interpreted is not -// well-defined in the TOML specification and left to the implementation. These -// defaults to current local timezone offset of the computer, but this can be -// changed by changing these variables before decoding. -// -// TODO: -// Ideally we'd like to offer people the ability to configure the used timezone -// by setting Decoder.Timezone and Encoder.Timezone; however, this is a bit -// tricky: the reason we use three different variables for this is to support -// round-tripping – without these specific TZ names we wouldn't know which -// format to use. -// -// There isn't a good way to encode this right now though, and passing this sort -// of information also ties in to various related issues such as string format -// encoding, encoding of comments, etc. -// -// So, for the time being, just put this in internal until we can write a good -// comprehensive API for doing all of this. -// -// The reason they're exported is because they're referred from in e.g. -// internal/tag. -// -// Note that this behaviour is valid according to the TOML spec as the exact -// behaviour is left up to implementations. -var ( - localOffset = func() int { _, o := time.Now().Zone(); return o }() - LocalDatetime = time.FixedZone("datetime-local", localOffset) - LocalDate = time.FixedZone("date-local", localOffset) - LocalTime = time.FixedZone("time-local", localOffset) -) diff --git a/vendor/github.com/BurntSushi/toml/lex.go b/vendor/github.com/BurntSushi/toml/lex.go deleted file mode 100644 index a1016d98a..000000000 --- a/vendor/github.com/BurntSushi/toml/lex.go +++ /dev/null @@ -1,1281 +0,0 @@ -package toml - -import ( - "fmt" - "reflect" - "runtime" - "strings" - "unicode" - "unicode/utf8" -) - -type itemType int - -const ( - itemError itemType = iota - itemNIL // used in the parser to indicate no type - itemEOF - itemText - itemString - itemStringEsc - itemRawString - itemMultilineString - itemRawMultilineString - itemBool - itemInteger - itemFloat - itemDatetime - itemArray // the start of an array - itemArrayEnd - itemTableStart - itemTableEnd - itemArrayTableStart - itemArrayTableEnd - itemKeyStart - itemKeyEnd - itemCommentStart - itemInlineTableStart - itemInlineTableEnd -) - -const eof = 0 - -type stateFn func(lx *lexer) stateFn - -func (p Position) String() string { - return fmt.Sprintf("at line %d; start %d; length %d", p.Line, p.Start, p.Len) -} - -type lexer struct { - input string - start int - pos int - line int - state stateFn - items chan item - tomlNext bool - esc bool - - // Allow for backing up up to 4 runes. This is necessary because TOML - // contains 3-rune tokens (""" and '''). - prevWidths [4]int - nprev int // how many of prevWidths are in use - atEOF bool // If we emit an eof, we can still back up, but it is not OK to call next again. - - // A stack of state functions used to maintain context. - // - // The idea is to reuse parts of the state machine in various places. For - // example, values can appear at the top level or within arbitrarily nested - // arrays. The last state on the stack is used after a value has been lexed. - // Similarly for comments. - stack []stateFn -} - -type item struct { - typ itemType - val string - err error - pos Position -} - -func (lx *lexer) nextItem() item { - for { - select { - case item := <-lx.items: - return item - default: - lx.state = lx.state(lx) - //fmt.Printf(" STATE %-24s current: %-10s stack: %s\n", lx.state, lx.current(), lx.stack) - } - } -} - -func lex(input string, tomlNext bool) *lexer { - lx := &lexer{ - input: input, - state: lexTop, - items: make(chan item, 10), - stack: make([]stateFn, 0, 10), - line: 1, - tomlNext: tomlNext, - } - return lx -} - -func (lx *lexer) push(state stateFn) { - lx.stack = append(lx.stack, state) -} - -func (lx *lexer) pop() stateFn { - if len(lx.stack) == 0 { - return lx.errorf("BUG in lexer: no states to pop") - } - last := lx.stack[len(lx.stack)-1] - lx.stack = lx.stack[0 : len(lx.stack)-1] - return last -} - -func (lx *lexer) current() string { - return lx.input[lx.start:lx.pos] -} - -func (lx lexer) getPos() Position { - p := Position{ - Line: lx.line, - Start: lx.start, - Len: lx.pos - lx.start, - } - if p.Len <= 0 { - p.Len = 1 - } - return p -} - -func (lx *lexer) emit(typ itemType) { - // Needed for multiline strings ending with an incomplete UTF-8 sequence. - if lx.start > lx.pos { - lx.error(errLexUTF8{lx.input[lx.pos]}) - return - } - lx.items <- item{typ: typ, pos: lx.getPos(), val: lx.current()} - lx.start = lx.pos -} - -func (lx *lexer) emitTrim(typ itemType) { - lx.items <- item{typ: typ, pos: lx.getPos(), val: strings.TrimSpace(lx.current())} - lx.start = lx.pos -} - -func (lx *lexer) next() (r rune) { - if lx.atEOF { - panic("BUG in lexer: next called after EOF") - } - if lx.pos >= len(lx.input) { - lx.atEOF = true - return eof - } - - if lx.input[lx.pos] == '\n' { - lx.line++ - } - lx.prevWidths[3] = lx.prevWidths[2] - lx.prevWidths[2] = lx.prevWidths[1] - lx.prevWidths[1] = lx.prevWidths[0] - if lx.nprev < 4 { - lx.nprev++ - } - - r, w := utf8.DecodeRuneInString(lx.input[lx.pos:]) - if r == utf8.RuneError && w == 1 { - lx.error(errLexUTF8{lx.input[lx.pos]}) - return utf8.RuneError - } - - // Note: don't use peek() here, as this calls next(). - if isControl(r) || (r == '\r' && (len(lx.input)-1 == lx.pos || lx.input[lx.pos+1] != '\n')) { - lx.errorControlChar(r) - return utf8.RuneError - } - - lx.prevWidths[0] = w - lx.pos += w - return r -} - -// ignore skips over the pending input before this point. -func (lx *lexer) ignore() { - lx.start = lx.pos -} - -// backup steps back one rune. Can be called 4 times between calls to next. -func (lx *lexer) backup() { - if lx.atEOF { - lx.atEOF = false - return - } - if lx.nprev < 1 { - panic("BUG in lexer: backed up too far") - } - w := lx.prevWidths[0] - lx.prevWidths[0] = lx.prevWidths[1] - lx.prevWidths[1] = lx.prevWidths[2] - lx.prevWidths[2] = lx.prevWidths[3] - lx.nprev-- - - lx.pos -= w - if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' { - lx.line-- - } -} - -// accept consumes the next rune if it's equal to `valid`. -func (lx *lexer) accept(valid rune) bool { - if lx.next() == valid { - return true - } - lx.backup() - return false -} - -// peek returns but does not consume the next rune in the input. -func (lx *lexer) peek() rune { - r := lx.next() - lx.backup() - return r -} - -// skip ignores all input that matches the given predicate. -func (lx *lexer) skip(pred func(rune) bool) { - for { - r := lx.next() - if pred(r) { - continue - } - lx.backup() - lx.ignore() - return - } -} - -// error stops all lexing by emitting an error and returning `nil`. -// -// Note that any value that is a character is escaped if it's a special -// character (newlines, tabs, etc.). -func (lx *lexer) error(err error) stateFn { - if lx.atEOF { - return lx.errorPrevLine(err) - } - lx.items <- item{typ: itemError, pos: lx.getPos(), err: err} - return nil -} - -// errorfPrevline is like error(), but sets the position to the last column of -// the previous line. -// -// This is so that unexpected EOF or NL errors don't show on a new blank line. -func (lx *lexer) errorPrevLine(err error) stateFn { - pos := lx.getPos() - pos.Line-- - pos.Len = 1 - pos.Start = lx.pos - 1 - lx.items <- item{typ: itemError, pos: pos, err: err} - return nil -} - -// errorPos is like error(), but allows explicitly setting the position. -func (lx *lexer) errorPos(start, length int, err error) stateFn { - pos := lx.getPos() - pos.Start = start - pos.Len = length - lx.items <- item{typ: itemError, pos: pos, err: err} - return nil -} - -// errorf is like error, and creates a new error. -func (lx *lexer) errorf(format string, values ...any) stateFn { - if lx.atEOF { - pos := lx.getPos() - pos.Line-- - pos.Len = 1 - pos.Start = lx.pos - 1 - lx.items <- item{typ: itemError, pos: pos, err: fmt.Errorf(format, values...)} - return nil - } - lx.items <- item{typ: itemError, pos: lx.getPos(), err: fmt.Errorf(format, values...)} - return nil -} - -func (lx *lexer) errorControlChar(cc rune) stateFn { - return lx.errorPos(lx.pos-1, 1, errLexControl{cc}) -} - -// lexTop consumes elements at the top level of TOML data. -func lexTop(lx *lexer) stateFn { - r := lx.next() - if isWhitespace(r) || isNL(r) { - return lexSkip(lx, lexTop) - } - switch r { - case '#': - lx.push(lexTop) - return lexCommentStart - case '[': - return lexTableStart - case eof: - if lx.pos > lx.start { - return lx.errorf("unexpected EOF") - } - lx.emit(itemEOF) - return nil - } - - // At this point, the only valid item can be a key, so we back up - // and let the key lexer do the rest. - lx.backup() - lx.push(lexTopEnd) - return lexKeyStart -} - -// lexTopEnd is entered whenever a top-level item has been consumed. (A value -// or a table.) It must see only whitespace, and will turn back to lexTop -// upon a newline. If it sees EOF, it will quit the lexer successfully. -func lexTopEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case r == '#': - // a comment will read to a newline for us. - lx.push(lexTop) - return lexCommentStart - case isWhitespace(r): - return lexTopEnd - case isNL(r): - lx.ignore() - return lexTop - case r == eof: - lx.emit(itemEOF) - return nil - } - return lx.errorf("expected a top-level item to end with a newline, comment, or EOF, but got %q instead", r) -} - -// lexTable lexes the beginning of a table. Namely, it makes sure that -// it starts with a character other than '.' and ']'. -// It assumes that '[' has already been consumed. -// It also handles the case that this is an item in an array of tables. -// e.g., '[[name]]'. -func lexTableStart(lx *lexer) stateFn { - if lx.peek() == '[' { - lx.next() - lx.emit(itemArrayTableStart) - lx.push(lexArrayTableEnd) - } else { - lx.emit(itemTableStart) - lx.push(lexTableEnd) - } - return lexTableNameStart -} - -func lexTableEnd(lx *lexer) stateFn { - lx.emit(itemTableEnd) - return lexTopEnd -} - -func lexArrayTableEnd(lx *lexer) stateFn { - if r := lx.next(); r != ']' { - return lx.errorf("expected end of table array name delimiter ']', but got %q instead", r) - } - lx.emit(itemArrayTableEnd) - return lexTopEnd -} - -func lexTableNameStart(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.peek(); { - case r == ']' || r == eof: - return lx.errorf("unexpected end of table name (table names cannot be empty)") - case r == '.': - return lx.errorf("unexpected table separator (table names cannot be empty)") - case r == '"' || r == '\'': - lx.ignore() - lx.push(lexTableNameEnd) - return lexQuotedName - default: - lx.push(lexTableNameEnd) - return lexBareName - } -} - -// lexTableNameEnd reads the end of a piece of a table name, optionally -// consuming whitespace. -func lexTableNameEnd(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.next(); { - case isWhitespace(r): - return lexTableNameEnd - case r == '.': - lx.ignore() - return lexTableNameStart - case r == ']': - return lx.pop() - default: - return lx.errorf("expected '.' or ']' to end table name, but got %q instead", r) - } -} - -// lexBareName lexes one part of a key or table. -// -// It assumes that at least one valid character for the table has already been -// read. -// -// Lexes only one part, e.g. only 'a' inside 'a.b'. -func lexBareName(lx *lexer) stateFn { - r := lx.next() - if isBareKeyChar(r, lx.tomlNext) { - return lexBareName - } - lx.backup() - lx.emit(itemText) - return lx.pop() -} - -// lexBareName lexes one part of a key or table. -// -// It assumes that at least one valid character for the table has already been -// read. -// -// Lexes only one part, e.g. only '"a"' inside '"a".b'. -func lexQuotedName(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexValue) - case r == '"': - lx.ignore() // ignore the '"' - return lexString - case r == '\'': - lx.ignore() // ignore the "'" - return lexRawString - case r == eof: - return lx.errorf("unexpected EOF; expected value") - default: - return lx.errorf("expected value but found %q instead", r) - } -} - -// lexKeyStart consumes all key parts until a '='. -func lexKeyStart(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.peek(); { - case r == '=' || r == eof: - return lx.errorf("unexpected '=': key name appears blank") - case r == '.': - return lx.errorf("unexpected '.': keys cannot start with a '.'") - case r == '"' || r == '\'': - lx.ignore() - fallthrough - default: // Bare key - lx.emit(itemKeyStart) - return lexKeyNameStart - } -} - -func lexKeyNameStart(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.peek(); { - case r == '=' || r == eof: - return lx.errorf("unexpected '='") - case r == '.': - return lx.errorf("unexpected '.'") - case r == '"' || r == '\'': - lx.ignore() - lx.push(lexKeyEnd) - return lexQuotedName - default: - lx.push(lexKeyEnd) - return lexBareName - } -} - -// lexKeyEnd consumes the end of a key and trims whitespace (up to the key -// separator). -func lexKeyEnd(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.next(); { - case isWhitespace(r): - return lexSkip(lx, lexKeyEnd) - case r == eof: - return lx.errorf("unexpected EOF; expected key separator '='") - case r == '.': - lx.ignore() - return lexKeyNameStart - case r == '=': - lx.emit(itemKeyEnd) - return lexSkip(lx, lexValue) - default: - return lx.errorf("expected '.' or '=', but got %q instead", r) - } -} - -// lexValue starts the consumption of a value anywhere a value is expected. -// lexValue will ignore whitespace. -// After a value is lexed, the last state on the next is popped and returned. -func lexValue(lx *lexer) stateFn { - // We allow whitespace to precede a value, but NOT newlines. - // In array syntax, the array states are responsible for ignoring newlines. - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexValue) - case isDigit(r): - lx.backup() // avoid an extra state and use the same as above - return lexNumberOrDateStart - } - switch r { - case '[': - lx.ignore() - lx.emit(itemArray) - return lexArrayValue - case '{': - lx.ignore() - lx.emit(itemInlineTableStart) - return lexInlineTableValue - case '"': - if lx.accept('"') { - if lx.accept('"') { - lx.ignore() // Ignore """ - return lexMultilineString - } - lx.backup() - } - lx.ignore() // ignore the '"' - return lexString - case '\'': - if lx.accept('\'') { - if lx.accept('\'') { - lx.ignore() // Ignore """ - return lexMultilineRawString - } - lx.backup() - } - lx.ignore() // ignore the "'" - return lexRawString - case '.': // special error case, be kind to users - return lx.errorf("floats must start with a digit, not '.'") - case 'i', 'n': - if (lx.accept('n') && lx.accept('f')) || (lx.accept('a') && lx.accept('n')) { - lx.emit(itemFloat) - return lx.pop() - } - case '-', '+': - return lexDecimalNumberStart - } - if unicode.IsLetter(r) { - // Be permissive here; lexBool will give a nice error if the - // user wrote something like - // x = foo - // (i.e. not 'true' or 'false' but is something else word-like.) - lx.backup() - return lexBool - } - if r == eof { - return lx.errorf("unexpected EOF; expected value") - } - return lx.errorf("expected value but found %q instead", r) -} - -// lexArrayValue consumes one value in an array. It assumes that '[' or ',' -// have already been consumed. All whitespace and newlines are ignored. -func lexArrayValue(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r) || isNL(r): - return lexSkip(lx, lexArrayValue) - case r == '#': - lx.push(lexArrayValue) - return lexCommentStart - case r == ',': - return lx.errorf("unexpected comma") - case r == ']': - return lexArrayEnd - } - - lx.backup() - lx.push(lexArrayValueEnd) - return lexValue -} - -// lexArrayValueEnd consumes everything between the end of an array value and -// the next value (or the end of the array): it ignores whitespace and newlines -// and expects either a ',' or a ']'. -func lexArrayValueEnd(lx *lexer) stateFn { - switch r := lx.next(); { - case isWhitespace(r) || isNL(r): - return lexSkip(lx, lexArrayValueEnd) - case r == '#': - lx.push(lexArrayValueEnd) - return lexCommentStart - case r == ',': - lx.ignore() - return lexArrayValue // move on to the next value - case r == ']': - return lexArrayEnd - default: - return lx.errorf("expected a comma (',') or array terminator (']'), but got %s", runeOrEOF(r)) - } -} - -// lexArrayEnd finishes the lexing of an array. -// It assumes that a ']' has just been consumed. -func lexArrayEnd(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemArrayEnd) - return lx.pop() -} - -// lexInlineTableValue consumes one key/value pair in an inline table. -// It assumes that '{' or ',' have already been consumed. Whitespace is ignored. -func lexInlineTableValue(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexInlineTableValue) - case isNL(r): - if lx.tomlNext { - return lexSkip(lx, lexInlineTableValue) - } - return lx.errorPrevLine(errLexInlineTableNL{}) - case r == '#': - lx.push(lexInlineTableValue) - return lexCommentStart - case r == ',': - return lx.errorf("unexpected comma") - case r == '}': - return lexInlineTableEnd - } - lx.backup() - lx.push(lexInlineTableValueEnd) - return lexKeyStart -} - -// lexInlineTableValueEnd consumes everything between the end of an inline table -// key/value pair and the next pair (or the end of the table): -// it ignores whitespace and expects either a ',' or a '}'. -func lexInlineTableValueEnd(lx *lexer) stateFn { - switch r := lx.next(); { - case isWhitespace(r): - return lexSkip(lx, lexInlineTableValueEnd) - case isNL(r): - if lx.tomlNext { - return lexSkip(lx, lexInlineTableValueEnd) - } - return lx.errorPrevLine(errLexInlineTableNL{}) - case r == '#': - lx.push(lexInlineTableValueEnd) - return lexCommentStart - case r == ',': - lx.ignore() - lx.skip(isWhitespace) - if lx.peek() == '}' { - if lx.tomlNext { - return lexInlineTableValueEnd - } - return lx.errorf("trailing comma not allowed in inline tables") - } - return lexInlineTableValue - case r == '}': - return lexInlineTableEnd - default: - return lx.errorf("expected a comma or an inline table terminator '}', but got %s instead", runeOrEOF(r)) - } -} - -func runeOrEOF(r rune) string { - if r == eof { - return "end of file" - } - return "'" + string(r) + "'" -} - -// lexInlineTableEnd finishes the lexing of an inline table. -// It assumes that a '}' has just been consumed. -func lexInlineTableEnd(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemInlineTableEnd) - return lx.pop() -} - -// lexString consumes the inner contents of a string. It assumes that the -// beginning '"' has already been consumed and ignored. -func lexString(lx *lexer) stateFn { - r := lx.next() - switch { - case r == eof: - return lx.errorf(`unexpected EOF; expected '"'`) - case isNL(r): - return lx.errorPrevLine(errLexStringNL{}) - case r == '\\': - lx.push(lexString) - return lexStringEscape - case r == '"': - lx.backup() - if lx.esc { - lx.esc = false - lx.emit(itemStringEsc) - } else { - lx.emit(itemString) - } - lx.next() - lx.ignore() - return lx.pop() - } - return lexString -} - -// lexMultilineString consumes the inner contents of a string. It assumes that -// the beginning '"""' has already been consumed and ignored. -func lexMultilineString(lx *lexer) stateFn { - r := lx.next() - switch r { - default: - return lexMultilineString - case eof: - return lx.errorf(`unexpected EOF; expected '"""'`) - case '\\': - return lexMultilineStringEscape - case '"': - /// Found " → try to read two more "". - if lx.accept('"') { - if lx.accept('"') { - /// Peek ahead: the string can contain " and "", including at the - /// end: """str""""" - /// 6 or more at the end, however, is an error. - if lx.peek() == '"' { - /// Check if we already lexed 5 's; if so we have 6 now, and - /// that's just too many man! - /// - /// Second check is for the edge case: - /// - /// two quotes allowed. - /// vv - /// """lol \"""""" - /// ^^ ^^^---- closing three - /// escaped - /// - /// But ugly, but it works - if strings.HasSuffix(lx.current(), `"""""`) && !strings.HasSuffix(lx.current(), `\"""""`) { - return lx.errorf(`unexpected '""""""'`) - } - lx.backup() - lx.backup() - return lexMultilineString - } - - lx.backup() /// backup: don't include the """ in the item. - lx.backup() - lx.backup() - lx.esc = false - lx.emit(itemMultilineString) - lx.next() /// Read over ''' again and discard it. - lx.next() - lx.next() - lx.ignore() - return lx.pop() - } - lx.backup() - } - return lexMultilineString - } -} - -// lexRawString consumes a raw string. Nothing can be escaped in such a string. -// It assumes that the beginning "'" has already been consumed and ignored. -func lexRawString(lx *lexer) stateFn { - r := lx.next() - switch { - default: - return lexRawString - case r == eof: - return lx.errorf(`unexpected EOF; expected "'"`) - case isNL(r): - return lx.errorPrevLine(errLexStringNL{}) - case r == '\'': - lx.backup() - lx.emit(itemRawString) - lx.next() - lx.ignore() - return lx.pop() - } -} - -// lexMultilineRawString consumes a raw string. Nothing can be escaped in such a -// string. It assumes that the beginning triple-' has already been consumed and -// ignored. -func lexMultilineRawString(lx *lexer) stateFn { - r := lx.next() - switch r { - default: - return lexMultilineRawString - case eof: - return lx.errorf(`unexpected EOF; expected "'''"`) - case '\'': - /// Found ' → try to read two more ''. - if lx.accept('\'') { - if lx.accept('\'') { - /// Peek ahead: the string can contain ' and '', including at the - /// end: '''str''''' - /// 6 or more at the end, however, is an error. - if lx.peek() == '\'' { - /// Check if we already lexed 5 's; if so we have 6 now, and - /// that's just too many man! - if strings.HasSuffix(lx.current(), "'''''") { - return lx.errorf(`unexpected "''''''"`) - } - lx.backup() - lx.backup() - return lexMultilineRawString - } - - lx.backup() /// backup: don't include the ''' in the item. - lx.backup() - lx.backup() - lx.emit(itemRawMultilineString) - lx.next() /// Read over ''' again and discard it. - lx.next() - lx.next() - lx.ignore() - return lx.pop() - } - lx.backup() - } - return lexMultilineRawString - } -} - -// lexMultilineStringEscape consumes an escaped character. It assumes that the -// preceding '\\' has already been consumed. -func lexMultilineStringEscape(lx *lexer) stateFn { - if isNL(lx.next()) { /// \ escaping newline. - return lexMultilineString - } - lx.backup() - lx.push(lexMultilineString) - return lexStringEscape(lx) -} - -func lexStringEscape(lx *lexer) stateFn { - lx.esc = true - r := lx.next() - switch r { - case 'e': - if !lx.tomlNext { - return lx.error(errLexEscape{r}) - } - fallthrough - case 'b': - fallthrough - case 't': - fallthrough - case 'n': - fallthrough - case 'f': - fallthrough - case 'r': - fallthrough - case '"': - fallthrough - case ' ', '\t': - // Inside """ .. """ strings you can use \ to escape newlines, and any - // amount of whitespace can be between the \ and \n. - fallthrough - case '\\': - return lx.pop() - case 'x': - if !lx.tomlNext { - return lx.error(errLexEscape{r}) - } - return lexHexEscape - case 'u': - return lexShortUnicodeEscape - case 'U': - return lexLongUnicodeEscape - } - return lx.error(errLexEscape{r}) -} - -func lexHexEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 2; i++ { - r = lx.next() - if !isHex(r) { - return lx.errorf(`expected two hexadecimal digits after '\x', but got %q instead`, lx.current()) - } - } - return lx.pop() -} - -func lexShortUnicodeEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 4; i++ { - r = lx.next() - if !isHex(r) { - return lx.errorf(`expected four hexadecimal digits after '\u', but got %q instead`, lx.current()) - } - } - return lx.pop() -} - -func lexLongUnicodeEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 8; i++ { - r = lx.next() - if !isHex(r) { - return lx.errorf(`expected eight hexadecimal digits after '\U', but got %q instead`, lx.current()) - } - } - return lx.pop() -} - -// lexNumberOrDateStart processes the first character of a value which begins -// with a digit. It exists to catch values starting with '0', so that -// lexBaseNumberOrDate can differentiate base prefixed integers from other -// types. -func lexNumberOrDateStart(lx *lexer) stateFn { - r := lx.next() - switch r { - case '0': - return lexBaseNumberOrDate - } - - if !isDigit(r) { - // The only way to reach this state is if the value starts - // with a digit, so specifically treat anything else as an - // error. - return lx.errorf("expected a digit but got %q", r) - } - - return lexNumberOrDate -} - -// lexNumberOrDate consumes either an integer, float or datetime. -func lexNumberOrDate(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexNumberOrDate - } - switch r { - case '-', ':': - return lexDatetime - case '_': - return lexDecimalNumber - case '.', 'e', 'E': - return lexFloat - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexDatetime consumes a Datetime, to a first approximation. -// The parser validates that it matches one of the accepted formats. -func lexDatetime(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexDatetime - } - switch r { - case '-', ':', 'T', 't', ' ', '.', 'Z', 'z', '+': - return lexDatetime - } - - lx.backup() - lx.emitTrim(itemDatetime) - return lx.pop() -} - -// lexHexInteger consumes a hexadecimal integer after seeing the '0x' prefix. -func lexHexInteger(lx *lexer) stateFn { - r := lx.next() - if isHex(r) { - return lexHexInteger - } - switch r { - case '_': - return lexHexInteger - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexOctalInteger consumes an octal integer after seeing the '0o' prefix. -func lexOctalInteger(lx *lexer) stateFn { - r := lx.next() - if isOctal(r) { - return lexOctalInteger - } - switch r { - case '_': - return lexOctalInteger - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexBinaryInteger consumes a binary integer after seeing the '0b' prefix. -func lexBinaryInteger(lx *lexer) stateFn { - r := lx.next() - if isBinary(r) { - return lexBinaryInteger - } - switch r { - case '_': - return lexBinaryInteger - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexDecimalNumber consumes a decimal float or integer. -func lexDecimalNumber(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexDecimalNumber - } - switch r { - case '.', 'e', 'E': - return lexFloat - case '_': - return lexDecimalNumber - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexDecimalNumber consumes the first digit of a number beginning with a sign. -// It assumes the sign has already been consumed. Values which start with a sign -// are only allowed to be decimal integers or floats. -// -// The special "nan" and "inf" values are also recognized. -func lexDecimalNumberStart(lx *lexer) stateFn { - r := lx.next() - - // Special error cases to give users better error messages - switch r { - case 'i': - if !lx.accept('n') || !lx.accept('f') { - return lx.errorf("invalid float: '%s'", lx.current()) - } - lx.emit(itemFloat) - return lx.pop() - case 'n': - if !lx.accept('a') || !lx.accept('n') { - return lx.errorf("invalid float: '%s'", lx.current()) - } - lx.emit(itemFloat) - return lx.pop() - case '0': - p := lx.peek() - switch p { - case 'b', 'o', 'x': - return lx.errorf("cannot use sign with non-decimal numbers: '%s%c'", lx.current(), p) - } - case '.': - return lx.errorf("floats must start with a digit, not '.'") - } - - if isDigit(r) { - return lexDecimalNumber - } - - return lx.errorf("expected a digit but got %q", r) -} - -// lexBaseNumberOrDate differentiates between the possible values which -// start with '0'. It assumes that before reaching this state, the initial '0' -// has been consumed. -func lexBaseNumberOrDate(lx *lexer) stateFn { - r := lx.next() - // Note: All datetimes start with at least two digits, so we don't - // handle date characters (':', '-', etc.) here. - if isDigit(r) { - return lexNumberOrDate - } - switch r { - case '_': - // Can only be decimal, because there can't be an underscore - // between the '0' and the base designator, and dates can't - // contain underscores. - return lexDecimalNumber - case '.', 'e', 'E': - return lexFloat - case 'b': - r = lx.peek() - if !isBinary(r) { - lx.errorf("not a binary number: '%s%c'", lx.current(), r) - } - return lexBinaryInteger - case 'o': - r = lx.peek() - if !isOctal(r) { - lx.errorf("not an octal number: '%s%c'", lx.current(), r) - } - return lexOctalInteger - case 'x': - r = lx.peek() - if !isHex(r) { - lx.errorf("not a hexidecimal number: '%s%c'", lx.current(), r) - } - return lexHexInteger - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexFloat consumes the elements of a float. It allows any sequence of -// float-like characters, so floats emitted by the lexer are only a first -// approximation and must be validated by the parser. -func lexFloat(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexFloat - } - switch r { - case '_', '.', '-', '+', 'e', 'E': - return lexFloat - } - - lx.backup() - lx.emit(itemFloat) - return lx.pop() -} - -// lexBool consumes a bool string: 'true' or 'false. -func lexBool(lx *lexer) stateFn { - var rs []rune - for { - r := lx.next() - if !unicode.IsLetter(r) { - lx.backup() - break - } - rs = append(rs, r) - } - s := string(rs) - switch s { - case "true", "false": - lx.emit(itemBool) - return lx.pop() - } - return lx.errorf("expected value but found %q instead", s) -} - -// lexCommentStart begins the lexing of a comment. It will emit -// itemCommentStart and consume no characters, passing control to lexComment. -func lexCommentStart(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemCommentStart) - return lexComment -} - -// lexComment lexes an entire comment. It assumes that '#' has been consumed. -// It will consume *up to* the first newline character, and pass control -// back to the last state on the stack. -func lexComment(lx *lexer) stateFn { - switch r := lx.next(); { - case isNL(r) || r == eof: - lx.backup() - lx.emit(itemText) - return lx.pop() - default: - return lexComment - } -} - -// lexSkip ignores all slurped input and moves on to the next state. -func lexSkip(lx *lexer, nextState stateFn) stateFn { - lx.ignore() - return nextState -} - -func (s stateFn) String() string { - name := runtime.FuncForPC(reflect.ValueOf(s).Pointer()).Name() - if i := strings.LastIndexByte(name, '.'); i > -1 { - name = name[i+1:] - } - if s == nil { - name = "" - } - return name + "()" -} - -func (itype itemType) String() string { - switch itype { - case itemError: - return "Error" - case itemNIL: - return "NIL" - case itemEOF: - return "EOF" - case itemText: - return "Text" - case itemString, itemStringEsc, itemRawString, itemMultilineString, itemRawMultilineString: - return "String" - case itemBool: - return "Bool" - case itemInteger: - return "Integer" - case itemFloat: - return "Float" - case itemDatetime: - return "DateTime" - case itemTableStart: - return "TableStart" - case itemTableEnd: - return "TableEnd" - case itemKeyStart: - return "KeyStart" - case itemKeyEnd: - return "KeyEnd" - case itemArray: - return "Array" - case itemArrayEnd: - return "ArrayEnd" - case itemCommentStart: - return "CommentStart" - case itemInlineTableStart: - return "InlineTableStart" - case itemInlineTableEnd: - return "InlineTableEnd" - } - panic(fmt.Sprintf("BUG: Unknown type '%d'.", int(itype))) -} - -func (item item) String() string { - return fmt.Sprintf("(%s, %s)", item.typ, item.val) -} - -func isWhitespace(r rune) bool { return r == '\t' || r == ' ' } -func isNL(r rune) bool { return r == '\n' || r == '\r' } -func isControl(r rune) bool { // Control characters except \t, \r, \n - switch r { - case '\t', '\r', '\n': - return false - default: - return (r >= 0x00 && r <= 0x1f) || r == 0x7f - } -} -func isDigit(r rune) bool { return r >= '0' && r <= '9' } -func isBinary(r rune) bool { return r == '0' || r == '1' } -func isOctal(r rune) bool { return r >= '0' && r <= '7' } -func isHex(r rune) bool { return (r >= '0' && r <= '9') || (r|0x20 >= 'a' && r|0x20 <= 'f') } -func isBareKeyChar(r rune, tomlNext bool) bool { - if tomlNext { - return (r >= 'A' && r <= 'Z') || - (r >= 'a' && r <= 'z') || - (r >= '0' && r <= '9') || - r == '_' || r == '-' || - r == 0xb2 || r == 0xb3 || r == 0xb9 || (r >= 0xbc && r <= 0xbe) || - (r >= 0xc0 && r <= 0xd6) || (r >= 0xd8 && r <= 0xf6) || (r >= 0xf8 && r <= 0x037d) || - (r >= 0x037f && r <= 0x1fff) || - (r >= 0x200c && r <= 0x200d) || (r >= 0x203f && r <= 0x2040) || - (r >= 0x2070 && r <= 0x218f) || (r >= 0x2460 && r <= 0x24ff) || - (r >= 0x2c00 && r <= 0x2fef) || (r >= 0x3001 && r <= 0xd7ff) || - (r >= 0xf900 && r <= 0xfdcf) || (r >= 0xfdf0 && r <= 0xfffd) || - (r >= 0x10000 && r <= 0xeffff) - } - - return (r >= 'A' && r <= 'Z') || - (r >= 'a' && r <= 'z') || - (r >= '0' && r <= '9') || - r == '_' || r == '-' -} diff --git a/vendor/github.com/BurntSushi/toml/meta.go b/vendor/github.com/BurntSushi/toml/meta.go deleted file mode 100644 index e61453730..000000000 --- a/vendor/github.com/BurntSushi/toml/meta.go +++ /dev/null @@ -1,148 +0,0 @@ -package toml - -import ( - "strings" -) - -// MetaData allows access to meta information about TOML data that's not -// accessible otherwise. -// -// It allows checking if a key is defined in the TOML data, whether any keys -// were undecoded, and the TOML type of a key. -type MetaData struct { - context Key // Used only during decoding. - - keyInfo map[string]keyInfo - mapping map[string]any - keys []Key - decoded map[string]struct{} - data []byte // Input file; for errors. -} - -// IsDefined reports if the key exists in the TOML data. -// -// The key should be specified hierarchically, for example to access the TOML -// key "a.b.c" you would use IsDefined("a", "b", "c"). Keys are case sensitive. -// -// Returns false for an empty key. -func (md *MetaData) IsDefined(key ...string) bool { - if len(key) == 0 { - return false - } - - var ( - hash map[string]any - ok bool - hashOrVal any = md.mapping - ) - for _, k := range key { - if hash, ok = hashOrVal.(map[string]any); !ok { - return false - } - if hashOrVal, ok = hash[k]; !ok { - return false - } - } - return true -} - -// Type returns a string representation of the type of the key specified. -// -// Type will return the empty string if given an empty key or a key that does -// not exist. Keys are case sensitive. -func (md *MetaData) Type(key ...string) string { - if ki, ok := md.keyInfo[Key(key).String()]; ok { - return ki.tomlType.typeString() - } - return "" -} - -// Keys returns a slice of every key in the TOML data, including key groups. -// -// Each key is itself a slice, where the first element is the top of the -// hierarchy and the last is the most specific. The list will have the same -// order as the keys appeared in the TOML data. -// -// All keys returned are non-empty. -func (md *MetaData) Keys() []Key { - return md.keys -} - -// Undecoded returns all keys that have not been decoded in the order in which -// they appear in the original TOML document. -// -// This includes keys that haven't been decoded because of a [Primitive] value. -// Once the Primitive value is decoded, the keys will be considered decoded. -// -// Also note that decoding into an empty interface will result in no decoding, -// and so no keys will be considered decoded. -// -// In this sense, the Undecoded keys correspond to keys in the TOML document -// that do not have a concrete type in your representation. -func (md *MetaData) Undecoded() []Key { - undecoded := make([]Key, 0, len(md.keys)) - for _, key := range md.keys { - if _, ok := md.decoded[key.String()]; !ok { - undecoded = append(undecoded, key) - } - } - return undecoded -} - -// Key represents any TOML key, including key groups. Use [MetaData.Keys] to get -// values of this type. -type Key []string - -func (k Key) String() string { - // This is called quite often, so it's a bit funky to make it faster. - var b strings.Builder - b.Grow(len(k) * 25) -outer: - for i, kk := range k { - if i > 0 { - b.WriteByte('.') - } - if kk == "" { - b.WriteString(`""`) - } else { - for _, r := range kk { - // "Inline" isBareKeyChar - if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-') { - b.WriteByte('"') - b.WriteString(dblQuotedReplacer.Replace(kk)) - b.WriteByte('"') - continue outer - } - } - b.WriteString(kk) - } - } - return b.String() -} - -func (k Key) maybeQuoted(i int) string { - if k[i] == "" { - return `""` - } - for _, r := range k[i] { - if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-' { - continue - } - return `"` + dblQuotedReplacer.Replace(k[i]) + `"` - } - return k[i] -} - -// Like append(), but only increase the cap by 1. -func (k Key) add(piece string) Key { - if cap(k) > len(k) { - return append(k, piece) - } - newKey := make(Key, len(k)+1) - copy(newKey, k) - newKey[len(k)] = piece - return newKey -} - -func (k Key) parent() Key { return k[:len(k)-1] } // all except the last piece. -func (k Key) last() string { return k[len(k)-1] } // last piece of this key. diff --git a/vendor/github.com/BurntSushi/toml/parse.go b/vendor/github.com/BurntSushi/toml/parse.go deleted file mode 100644 index 11ac3108b..000000000 --- a/vendor/github.com/BurntSushi/toml/parse.go +++ /dev/null @@ -1,844 +0,0 @@ -package toml - -import ( - "fmt" - "math" - "os" - "strconv" - "strings" - "time" - "unicode/utf8" - - "github.com/BurntSushi/toml/internal" -) - -type parser struct { - lx *lexer - context Key // Full key for the current hash in scope. - currentKey string // Base key name for everything except hashes. - pos Position // Current position in the TOML file. - tomlNext bool - - ordered []Key // List of keys in the order that they appear in the TOML data. - - keyInfo map[string]keyInfo // Map keyname → info about the TOML key. - mapping map[string]any // Map keyname → key value. - implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names"). -} - -type keyInfo struct { - pos Position - tomlType tomlType -} - -func parse(data string) (p *parser, err error) { - _, tomlNext := os.LookupEnv("BURNTSUSHI_TOML_110") - - defer func() { - if r := recover(); r != nil { - if pErr, ok := r.(ParseError); ok { - pErr.input = data - err = pErr - return - } - panic(r) - } - }() - - // Read over BOM; do this here as the lexer calls utf8.DecodeRuneInString() - // which mangles stuff. UTF-16 BOM isn't strictly valid, but some tools add - // it anyway. - if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") { // UTF-16 - data = data[2:] - //lint:ignore S1017 https://github.com/dominikh/go-tools/issues/1447 - } else if strings.HasPrefix(data, "\xef\xbb\xbf") { // UTF-8 - data = data[3:] - } - - // Examine first few bytes for NULL bytes; this probably means it's a UTF-16 - // file (second byte in surrogate pair being NULL). Again, do this here to - // avoid having to deal with UTF-8/16 stuff in the lexer. - ex := 6 - if len(data) < 6 { - ex = len(data) - } - if i := strings.IndexRune(data[:ex], 0); i > -1 { - return nil, ParseError{ - Message: "files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8", - Position: Position{Line: 1, Start: i, Len: 1}, - Line: 1, - input: data, - } - } - - p = &parser{ - keyInfo: make(map[string]keyInfo), - mapping: make(map[string]any), - lx: lex(data, tomlNext), - ordered: make([]Key, 0), - implicits: make(map[string]struct{}), - tomlNext: tomlNext, - } - for { - item := p.next() - if item.typ == itemEOF { - break - } - p.topLevel(item) - } - - return p, nil -} - -func (p *parser) panicErr(it item, err error) { - panic(ParseError{ - err: err, - Position: it.pos, - Line: it.pos.Len, - LastKey: p.current(), - }) -} - -func (p *parser) panicItemf(it item, format string, v ...any) { - panic(ParseError{ - Message: fmt.Sprintf(format, v...), - Position: it.pos, - Line: it.pos.Len, - LastKey: p.current(), - }) -} - -func (p *parser) panicf(format string, v ...any) { - panic(ParseError{ - Message: fmt.Sprintf(format, v...), - Position: p.pos, - Line: p.pos.Line, - LastKey: p.current(), - }) -} - -func (p *parser) next() item { - it := p.lx.nextItem() - //fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.pos.Line, it.val) - if it.typ == itemError { - if it.err != nil { - panic(ParseError{ - Position: it.pos, - Line: it.pos.Line, - LastKey: p.current(), - err: it.err, - }) - } - - p.panicItemf(it, "%s", it.val) - } - return it -} - -func (p *parser) nextPos() item { - it := p.next() - p.pos = it.pos - return it -} - -func (p *parser) bug(format string, v ...any) { - panic(fmt.Sprintf("BUG: "+format+"\n\n", v...)) -} - -func (p *parser) expect(typ itemType) item { - it := p.next() - p.assertEqual(typ, it.typ) - return it -} - -func (p *parser) assertEqual(expected, got itemType) { - if expected != got { - p.bug("Expected '%s' but got '%s'.", expected, got) - } -} - -func (p *parser) topLevel(item item) { - switch item.typ { - case itemCommentStart: // # .. - p.expect(itemText) - case itemTableStart: // [ .. ] - name := p.nextPos() - - var key Key - for ; name.typ != itemTableEnd && name.typ != itemEOF; name = p.next() { - key = append(key, p.keyString(name)) - } - p.assertEqual(itemTableEnd, name.typ) - - p.addContext(key, false) - p.setType("", tomlHash, item.pos) - p.ordered = append(p.ordered, key) - case itemArrayTableStart: // [[ .. ]] - name := p.nextPos() - - var key Key - for ; name.typ != itemArrayTableEnd && name.typ != itemEOF; name = p.next() { - key = append(key, p.keyString(name)) - } - p.assertEqual(itemArrayTableEnd, name.typ) - - p.addContext(key, true) - p.setType("", tomlArrayHash, item.pos) - p.ordered = append(p.ordered, key) - case itemKeyStart: // key = .. - outerContext := p.context - /// Read all the key parts (e.g. 'a' and 'b' in 'a.b') - k := p.nextPos() - var key Key - for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() { - key = append(key, p.keyString(k)) - } - p.assertEqual(itemKeyEnd, k.typ) - - /// The current key is the last part. - p.currentKey = key.last() - - /// All the other parts (if any) are the context; need to set each part - /// as implicit. - context := key.parent() - for i := range context { - p.addImplicitContext(append(p.context, context[i:i+1]...)) - } - p.ordered = append(p.ordered, p.context.add(p.currentKey)) - - /// Set value. - vItem := p.next() - val, typ := p.value(vItem, false) - p.setValue(p.currentKey, val) - p.setType(p.currentKey, typ, vItem.pos) - - /// Remove the context we added (preserving any context from [tbl] lines). - p.context = outerContext - p.currentKey = "" - default: - p.bug("Unexpected type at top level: %s", item.typ) - } -} - -// Gets a string for a key (or part of a key in a table name). -func (p *parser) keyString(it item) string { - switch it.typ { - case itemText: - return it.val - case itemString, itemStringEsc, itemMultilineString, - itemRawString, itemRawMultilineString: - s, _ := p.value(it, false) - return s.(string) - default: - p.bug("Unexpected key type: %s", it.typ) - } - panic("unreachable") -} - -var datetimeRepl = strings.NewReplacer( - "z", "Z", - "t", "T", - " ", "T") - -// value translates an expected value from the lexer into a Go value wrapped -// as an empty interface. -func (p *parser) value(it item, parentIsArray bool) (any, tomlType) { - switch it.typ { - case itemString: - return it.val, p.typeOfPrimitive(it) - case itemStringEsc: - return p.replaceEscapes(it, it.val), p.typeOfPrimitive(it) - case itemMultilineString: - return p.replaceEscapes(it, p.stripEscapedNewlines(stripFirstNewline(it.val))), p.typeOfPrimitive(it) - case itemRawString: - return it.val, p.typeOfPrimitive(it) - case itemRawMultilineString: - return stripFirstNewline(it.val), p.typeOfPrimitive(it) - case itemInteger: - return p.valueInteger(it) - case itemFloat: - return p.valueFloat(it) - case itemBool: - switch it.val { - case "true": - return true, p.typeOfPrimitive(it) - case "false": - return false, p.typeOfPrimitive(it) - default: - p.bug("Expected boolean value, but got '%s'.", it.val) - } - case itemDatetime: - return p.valueDatetime(it) - case itemArray: - return p.valueArray(it) - case itemInlineTableStart: - return p.valueInlineTable(it, parentIsArray) - default: - p.bug("Unexpected value type: %s", it.typ) - } - panic("unreachable") -} - -func (p *parser) valueInteger(it item) (any, tomlType) { - if !numUnderscoresOK(it.val) { - p.panicItemf(it, "Invalid integer %q: underscores must be surrounded by digits", it.val) - } - if numHasLeadingZero(it.val) { - p.panicItemf(it, "Invalid integer %q: cannot have leading zeroes", it.val) - } - - num, err := strconv.ParseInt(it.val, 0, 64) - if err != nil { - // Distinguish integer values. Normally, it'd be a bug if the lexer - // provides an invalid integer, but it's possible that the number is - // out of range of valid values (which the lexer cannot determine). - // So mark the former as a bug but the latter as a legitimate user - // error. - if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { - p.panicErr(it, errParseRange{i: it.val, size: "int64"}) - } else { - p.bug("Expected integer value, but got '%s'.", it.val) - } - } - return num, p.typeOfPrimitive(it) -} - -func (p *parser) valueFloat(it item) (any, tomlType) { - parts := strings.FieldsFunc(it.val, func(r rune) bool { - switch r { - case '.', 'e', 'E': - return true - } - return false - }) - for _, part := range parts { - if !numUnderscoresOK(part) { - p.panicItemf(it, "Invalid float %q: underscores must be surrounded by digits", it.val) - } - } - if len(parts) > 0 && numHasLeadingZero(parts[0]) { - p.panicItemf(it, "Invalid float %q: cannot have leading zeroes", it.val) - } - if !numPeriodsOK(it.val) { - // As a special case, numbers like '123.' or '1.e2', - // which are valid as far as Go/strconv are concerned, - // must be rejected because TOML says that a fractional - // part consists of '.' followed by 1+ digits. - p.panicItemf(it, "Invalid float %q: '.' must be followed by one or more digits", it.val) - } - val := strings.Replace(it.val, "_", "", -1) - signbit := false - if val == "+nan" || val == "-nan" { - signbit = val == "-nan" - val = "nan" - } - num, err := strconv.ParseFloat(val, 64) - if err != nil { - if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange { - p.panicErr(it, errParseRange{i: it.val, size: "float64"}) - } else { - p.panicItemf(it, "Invalid float value: %q", it.val) - } - } - if signbit { - num = math.Copysign(num, -1) - } - return num, p.typeOfPrimitive(it) -} - -var dtTypes = []struct { - fmt string - zone *time.Location - next bool -}{ - {time.RFC3339Nano, time.Local, false}, - {"2006-01-02T15:04:05.999999999", internal.LocalDatetime, false}, - {"2006-01-02", internal.LocalDate, false}, - {"15:04:05.999999999", internal.LocalTime, false}, - - // tomlNext - {"2006-01-02T15:04Z07:00", time.Local, true}, - {"2006-01-02T15:04", internal.LocalDatetime, true}, - {"15:04", internal.LocalTime, true}, -} - -func (p *parser) valueDatetime(it item) (any, tomlType) { - it.val = datetimeRepl.Replace(it.val) - var ( - t time.Time - ok bool - err error - ) - for _, dt := range dtTypes { - if dt.next && !p.tomlNext { - continue - } - t, err = time.ParseInLocation(dt.fmt, it.val, dt.zone) - if err == nil { - if missingLeadingZero(it.val, dt.fmt) { - p.panicErr(it, errParseDate{it.val}) - } - ok = true - break - } - } - if !ok { - p.panicErr(it, errParseDate{it.val}) - } - return t, p.typeOfPrimitive(it) -} - -// Go's time.Parse() will accept numbers without a leading zero; there isn't any -// way to require it. https://github.com/golang/go/issues/29911 -// -// Depend on the fact that the separators (- and :) should always be at the same -// location. -func missingLeadingZero(d, l string) bool { - for i, c := range []byte(l) { - if c == '.' || c == 'Z' { - return false - } - if (c < '0' || c > '9') && d[i] != c { - return true - } - } - return false -} - -func (p *parser) valueArray(it item) (any, tomlType) { - p.setType(p.currentKey, tomlArray, it.pos) - - var ( - // Initialize to a non-nil slice to make it consistent with how S = [] - // decodes into a non-nil slice inside something like struct { S - // []string }. See #338 - array = make([]any, 0, 2) - ) - for it = p.next(); it.typ != itemArrayEnd; it = p.next() { - if it.typ == itemCommentStart { - p.expect(itemText) - continue - } - - val, typ := p.value(it, true) - array = append(array, val) - - // XXX: type isn't used here, we need it to record the accurate type - // information. - // - // Not entirely sure how to best store this; could use "key[0]", - // "key[1]" notation, or maybe store it on the Array type? - _ = typ - } - return array, tomlArray -} - -func (p *parser) valueInlineTable(it item, parentIsArray bool) (any, tomlType) { - var ( - topHash = make(map[string]any) - outerContext = p.context - outerKey = p.currentKey - ) - - p.context = append(p.context, p.currentKey) - prevContext := p.context - p.currentKey = "" - - p.addImplicit(p.context) - p.addContext(p.context, parentIsArray) - - /// Loop over all table key/value pairs. - for it := p.next(); it.typ != itemInlineTableEnd; it = p.next() { - if it.typ == itemCommentStart { - p.expect(itemText) - continue - } - - /// Read all key parts. - k := p.nextPos() - var key Key - for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() { - key = append(key, p.keyString(k)) - } - p.assertEqual(itemKeyEnd, k.typ) - - /// The current key is the last part. - p.currentKey = key.last() - - /// All the other parts (if any) are the context; need to set each part - /// as implicit. - context := key.parent() - for i := range context { - p.addImplicitContext(append(p.context, context[i:i+1]...)) - } - p.ordered = append(p.ordered, p.context.add(p.currentKey)) - - /// Set the value. - val, typ := p.value(p.next(), false) - p.setValue(p.currentKey, val) - p.setType(p.currentKey, typ, it.pos) - - hash := topHash - for _, c := range context { - h, ok := hash[c] - if !ok { - h = make(map[string]any) - hash[c] = h - } - hash, ok = h.(map[string]any) - if !ok { - p.panicf("%q is not a table", p.context) - } - } - hash[p.currentKey] = val - - /// Restore context. - p.context = prevContext - } - p.context = outerContext - p.currentKey = outerKey - return topHash, tomlHash -} - -// numHasLeadingZero checks if this number has leading zeroes, allowing for '0', -// +/- signs, and base prefixes. -func numHasLeadingZero(s string) bool { - if len(s) > 1 && s[0] == '0' && !(s[1] == 'b' || s[1] == 'o' || s[1] == 'x') { // Allow 0b, 0o, 0x - return true - } - if len(s) > 2 && (s[0] == '-' || s[0] == '+') && s[1] == '0' { - return true - } - return false -} - -// numUnderscoresOK checks whether each underscore in s is surrounded by -// characters that are not underscores. -func numUnderscoresOK(s string) bool { - switch s { - case "nan", "+nan", "-nan", "inf", "-inf", "+inf": - return true - } - accept := false - for _, r := range s { - if r == '_' { - if !accept { - return false - } - } - - // isHexis a superset of all the permissable characters surrounding an - // underscore. - accept = isHex(r) - } - return accept -} - -// numPeriodsOK checks whether every period in s is followed by a digit. -func numPeriodsOK(s string) bool { - period := false - for _, r := range s { - if period && !isDigit(r) { - return false - } - period = r == '.' - } - return !period -} - -// Set the current context of the parser, where the context is either a hash or -// an array of hashes, depending on the value of the `array` parameter. -// -// Establishing the context also makes sure that the key isn't a duplicate, and -// will create implicit hashes automatically. -func (p *parser) addContext(key Key, array bool) { - /// Always start at the top level and drill down for our context. - hashContext := p.mapping - keyContext := make(Key, 0, len(key)-1) - - /// We only need implicit hashes for the parents. - for _, k := range key.parent() { - _, ok := hashContext[k] - keyContext = append(keyContext, k) - - // No key? Make an implicit hash and move on. - if !ok { - p.addImplicit(keyContext) - hashContext[k] = make(map[string]any) - } - - // If the hash context is actually an array of tables, then set - // the hash context to the last element in that array. - // - // Otherwise, it better be a table, since this MUST be a key group (by - // virtue of it not being the last element in a key). - switch t := hashContext[k].(type) { - case []map[string]any: - hashContext = t[len(t)-1] - case map[string]any: - hashContext = t - default: - p.panicf("Key '%s' was already created as a hash.", keyContext) - } - } - - p.context = keyContext - if array { - // If this is the first element for this array, then allocate a new - // list of tables for it. - k := key.last() - if _, ok := hashContext[k]; !ok { - hashContext[k] = make([]map[string]any, 0, 4) - } - - // Add a new table. But make sure the key hasn't already been used - // for something else. - if hash, ok := hashContext[k].([]map[string]any); ok { - hashContext[k] = append(hash, make(map[string]any)) - } else { - p.panicf("Key '%s' was already created and cannot be used as an array.", key) - } - } else { - p.setValue(key.last(), make(map[string]any)) - } - p.context = append(p.context, key.last()) -} - -// setValue sets the given key to the given value in the current context. -// It will make sure that the key hasn't already been defined, account for -// implicit key groups. -func (p *parser) setValue(key string, value any) { - var ( - tmpHash any - ok bool - hash = p.mapping - keyContext = make(Key, 0, len(p.context)+1) - ) - for _, k := range p.context { - keyContext = append(keyContext, k) - if tmpHash, ok = hash[k]; !ok { - p.bug("Context for key '%s' has not been established.", keyContext) - } - switch t := tmpHash.(type) { - case []map[string]any: - // The context is a table of hashes. Pick the most recent table - // defined as the current hash. - hash = t[len(t)-1] - case map[string]any: - hash = t - default: - p.panicf("Key '%s' has already been defined.", keyContext) - } - } - keyContext = append(keyContext, key) - - if _, ok := hash[key]; ok { - // Normally redefining keys isn't allowed, but the key could have been - // defined implicitly and it's allowed to be redefined concretely. (See - // the `valid/implicit-and-explicit-after.toml` in toml-test) - // - // But we have to make sure to stop marking it as an implicit. (So that - // another redefinition provokes an error.) - // - // Note that since it has already been defined (as a hash), we don't - // want to overwrite it. So our business is done. - if p.isArray(keyContext) { - p.removeImplicit(keyContext) - hash[key] = value - return - } - if p.isImplicit(keyContext) { - p.removeImplicit(keyContext) - return - } - // Otherwise, we have a concrete key trying to override a previous key, - // which is *always* wrong. - p.panicf("Key '%s' has already been defined.", keyContext) - } - - hash[key] = value -} - -// setType sets the type of a particular value at a given key. It should be -// called immediately AFTER setValue. -// -// Note that if `key` is empty, then the type given will be applied to the -// current context (which is either a table or an array of tables). -func (p *parser) setType(key string, typ tomlType, pos Position) { - keyContext := make(Key, 0, len(p.context)+1) - keyContext = append(keyContext, p.context...) - if len(key) > 0 { // allow type setting for hashes - keyContext = append(keyContext, key) - } - // Special case to make empty keys ("" = 1) work. - // Without it it will set "" rather than `""`. - // TODO: why is this needed? And why is this only needed here? - if len(keyContext) == 0 { - keyContext = Key{""} - } - p.keyInfo[keyContext.String()] = keyInfo{tomlType: typ, pos: pos} -} - -// Implicit keys need to be created when tables are implied in "a.b.c.d = 1" and -// "[a.b.c]" (the "a", "b", and "c" hashes are never created explicitly). -func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = struct{}{} } -func (p *parser) removeImplicit(key Key) { delete(p.implicits, key.String()) } -func (p *parser) isImplicit(key Key) bool { _, ok := p.implicits[key.String()]; return ok } -func (p *parser) isArray(key Key) bool { return p.keyInfo[key.String()].tomlType == tomlArray } -func (p *parser) addImplicitContext(key Key) { p.addImplicit(key); p.addContext(key, false) } - -// current returns the full key name of the current context. -func (p *parser) current() string { - if len(p.currentKey) == 0 { - return p.context.String() - } - if len(p.context) == 0 { - return p.currentKey - } - return fmt.Sprintf("%s.%s", p.context, p.currentKey) -} - -func stripFirstNewline(s string) string { - if len(s) > 0 && s[0] == '\n' { - return s[1:] - } - if len(s) > 1 && s[0] == '\r' && s[1] == '\n' { - return s[2:] - } - return s -} - -// stripEscapedNewlines removes whitespace after line-ending backslashes in -// multiline strings. -// -// A line-ending backslash is an unescaped \ followed only by whitespace until -// the next newline. After a line-ending backslash, all whitespace is removed -// until the next non-whitespace character. -func (p *parser) stripEscapedNewlines(s string) string { - var ( - b strings.Builder - i int - ) - b.Grow(len(s)) - for { - ix := strings.Index(s[i:], `\`) - if ix < 0 { - b.WriteString(s) - return b.String() - } - i += ix - - if len(s) > i+1 && s[i+1] == '\\' { - // Escaped backslash. - i += 2 - continue - } - // Scan until the next non-whitespace. - j := i + 1 - whitespaceLoop: - for ; j < len(s); j++ { - switch s[j] { - case ' ', '\t', '\r', '\n': - default: - break whitespaceLoop - } - } - if j == i+1 { - // Not a whitespace escape. - i++ - continue - } - if !strings.Contains(s[i:j], "\n") { - // This is not a line-ending backslash. (It's a bad escape sequence, - // but we can let replaceEscapes catch it.) - i++ - continue - } - b.WriteString(s[:i]) - s = s[j:] - i = 0 - } -} - -func (p *parser) replaceEscapes(it item, str string) string { - var ( - b strings.Builder - skip = 0 - ) - b.Grow(len(str)) - for i, c := range str { - if skip > 0 { - skip-- - continue - } - if c != '\\' { - b.WriteRune(c) - continue - } - - if i >= len(str) { - p.bug("Escape sequence at end of string.") - return "" - } - switch str[i+1] { - default: - p.bug("Expected valid escape code after \\, but got %q.", str[i+1]) - case ' ', '\t': - p.panicItemf(it, "invalid escape: '\\%c'", str[i+1]) - case 'b': - b.WriteByte(0x08) - skip = 1 - case 't': - b.WriteByte(0x09) - skip = 1 - case 'n': - b.WriteByte(0x0a) - skip = 1 - case 'f': - b.WriteByte(0x0c) - skip = 1 - case 'r': - b.WriteByte(0x0d) - skip = 1 - case 'e': - if p.tomlNext { - b.WriteByte(0x1b) - skip = 1 - } - case '"': - b.WriteByte(0x22) - skip = 1 - case '\\': - b.WriteByte(0x5c) - skip = 1 - // The lexer guarantees the correct number of characters are present; - // don't need to check here. - case 'x': - if p.tomlNext { - escaped := p.asciiEscapeToUnicode(it, str[i+2:i+4]) - b.WriteRune(escaped) - skip = 3 - } - case 'u': - escaped := p.asciiEscapeToUnicode(it, str[i+2:i+6]) - b.WriteRune(escaped) - skip = 5 - case 'U': - escaped := p.asciiEscapeToUnicode(it, str[i+2:i+10]) - b.WriteRune(escaped) - skip = 9 - } - } - return b.String() -} - -func (p *parser) asciiEscapeToUnicode(it item, s string) rune { - hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32) - if err != nil { - p.bug("Could not parse '%s' as a hexadecimal number, but the lexer claims it's OK: %s", s, err) - } - if !utf8.ValidRune(rune(hex)) { - p.panicItemf(it, "Escaped character '\\u%s' is not valid UTF-8.", s) - } - return rune(hex) -} diff --git a/vendor/github.com/BurntSushi/toml/type_fields.go b/vendor/github.com/BurntSushi/toml/type_fields.go deleted file mode 100644 index 10c51f7ee..000000000 --- a/vendor/github.com/BurntSushi/toml/type_fields.go +++ /dev/null @@ -1,238 +0,0 @@ -package toml - -// Struct field handling is adapted from code in encoding/json: -// -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the Go distribution. - -import ( - "reflect" - "sort" - "sync" -) - -// A field represents a single field found in a struct. -type field struct { - name string // the name of the field (`toml` tag included) - tag bool // whether field has a `toml` tag - index []int // represents the depth of an anonymous field - typ reflect.Type // the type of the field -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from toml tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that TOML should recognize for the given -// type. The algorithm is breadth-first search over the set of structs to -// include - the top struct and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - var count map[reflect.Type]int - var nextCount map[reflect.Type]int - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { // unexported - continue - } - opts := getOptions(sf.Tag) - if opts.skip { - continue - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if opts.name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := opts.name != "" - name := opts.name - if name == "" { - name = sf.Name - } - fields = append(fields, field{name, tagged, index, ft}) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - f := field{name: ft.Name(), index: index, typ: ft} - next = append(next, f) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with TOML tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// TOML tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} diff --git a/vendor/github.com/BurntSushi/toml/type_toml.go b/vendor/github.com/BurntSushi/toml/type_toml.go deleted file mode 100644 index 1c090d331..000000000 --- a/vendor/github.com/BurntSushi/toml/type_toml.go +++ /dev/null @@ -1,65 +0,0 @@ -package toml - -// tomlType represents any Go type that corresponds to a TOML type. -// While the first draft of the TOML spec has a simplistic type system that -// probably doesn't need this level of sophistication, we seem to be militating -// toward adding real composite types. -type tomlType interface { - typeString() string -} - -// typeEqual accepts any two types and returns true if they are equal. -func typeEqual(t1, t2 tomlType) bool { - if t1 == nil || t2 == nil { - return false - } - return t1.typeString() == t2.typeString() -} - -func typeIsTable(t tomlType) bool { - return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash) -} - -type tomlBaseType string - -func (btype tomlBaseType) typeString() string { return string(btype) } -func (btype tomlBaseType) String() string { return btype.typeString() } - -var ( - tomlInteger tomlBaseType = "Integer" - tomlFloat tomlBaseType = "Float" - tomlDatetime tomlBaseType = "Datetime" - tomlString tomlBaseType = "String" - tomlBool tomlBaseType = "Bool" - tomlArray tomlBaseType = "Array" - tomlHash tomlBaseType = "Hash" - tomlArrayHash tomlBaseType = "ArrayHash" -) - -// typeOfPrimitive returns a tomlType of any primitive value in TOML. -// Primitive values are: Integer, Float, Datetime, String and Bool. -// -// Passing a lexer item other than the following will cause a BUG message -// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime. -func (p *parser) typeOfPrimitive(lexItem item) tomlType { - switch lexItem.typ { - case itemInteger: - return tomlInteger - case itemFloat: - return tomlFloat - case itemDatetime: - return tomlDatetime - case itemString, itemStringEsc: - return tomlString - case itemMultilineString: - return tomlString - case itemRawString: - return tomlString - case itemRawMultilineString: - return tomlString - case itemBool: - return tomlBool - } - p.bug("Cannot infer primitive type of lex item '%s'.", lexItem) - panic("unreachable") -} diff --git a/vendor/github.com/Masterminds/semver/v3/.gitignore b/vendor/github.com/Masterminds/semver/v3/.gitignore deleted file mode 100644 index 6b061e617..000000000 --- a/vendor/github.com/Masterminds/semver/v3/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_fuzz/ \ No newline at end of file diff --git a/vendor/github.com/Masterminds/semver/v3/.golangci.yml b/vendor/github.com/Masterminds/semver/v3/.golangci.yml deleted file mode 100644 index fdbdf1448..000000000 --- a/vendor/github.com/Masterminds/semver/v3/.golangci.yml +++ /dev/null @@ -1,26 +0,0 @@ -run: - deadline: 2m - -linters: - disable-all: true - enable: - - deadcode - - dupl - - errcheck - - gofmt - - goimports - - golint - - gosimple - - govet - - ineffassign - - misspell - - nakedret - - structcheck - - unused - - varcheck - -linters-settings: - gofmt: - simplify: true - dupl: - threshold: 400 diff --git a/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md b/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md deleted file mode 100644 index 1f90c38d2..000000000 --- a/vendor/github.com/Masterminds/semver/v3/CHANGELOG.md +++ /dev/null @@ -1,194 +0,0 @@ -# Changelog - -## 3.1.1 (2020-11-23) - -### Fixed - -- #158: Fixed issue with generated regex operation order that could cause problem - -## 3.1.0 (2020-04-15) - -### Added - -- #131: Add support for serializing/deserializing SQL (thanks @ryancurrah) - -### Changed - -- #148: More accurate validation messages on constraints - -## 3.0.3 (2019-12-13) - -### Fixed - -- #141: Fixed issue with <= comparison - -## 3.0.2 (2019-11-14) - -### Fixed - -- #134: Fixed broken constraint checking with ^0.0 (thanks @krmichelos) - -## 3.0.1 (2019-09-13) - -### Fixed - -- #125: Fixes issue with module path for v3 - -## 3.0.0 (2019-09-12) - -This is a major release of the semver package which includes API changes. The Go -API is compatible with ^1. The Go API was not changed because many people are using -`go get` without Go modules for their applications and API breaking changes cause -errors which we have or would need to support. - -The changes in this release are the handling based on the data passed into the -functions. These are described in the added and changed sections below. - -### Added - -- StrictNewVersion function. This is similar to NewVersion but will return an - error if the version passed in is not a strict semantic version. For example, - 1.2.3 would pass but v1.2.3 or 1.2 would fail because they are not strictly - speaking semantic versions. This function is faster, performs fewer operations, - and uses fewer allocations than NewVersion. -- Fuzzing has been performed on NewVersion, StrictNewVersion, and NewConstraint. - The Makefile contains the operations used. For more information on you can start - on Wikipedia at https://en.wikipedia.org/wiki/Fuzzing -- Now using Go modules - -### Changed - -- NewVersion has proper prerelease and metadata validation with error messages - to signal an issue with either of them -- ^ now operates using a similar set of rules to npm/js and Rust/Cargo. If the - version is >=1 the ^ ranges works the same as v1. For major versions of 0 the - rules have changed. The minor version is treated as the stable version unless - a patch is specified and then it is equivalent to =. One difference from npm/js - is that prereleases there are only to a specific version (e.g. 1.2.3). - Prereleases here look over multiple versions and follow semantic version - ordering rules. This pattern now follows along with the expected and requested - handling of this packaged by numerous users. - -## 1.5.0 (2019-09-11) - -### Added - -- #103: Add basic fuzzing for `NewVersion()` (thanks @jesse-c) - -### Changed - -- #82: Clarify wildcard meaning in range constraints and update tests for it (thanks @greysteil) -- #83: Clarify caret operator range for pre-1.0.0 dependencies (thanks @greysteil) -- #72: Adding docs comment pointing to vert for a cli -- #71: Update the docs on pre-release comparator handling -- #89: Test with new go versions (thanks @thedevsaddam) -- #87: Added $ to ValidPrerelease for better validation (thanks @jeremycarroll) - -### Fixed - -- #78: Fix unchecked error in example code (thanks @ravron) -- #70: Fix the handling of pre-releases and the 0.0.0 release edge case -- #97: Fixed copyright file for proper display on GitHub -- #107: Fix handling prerelease when sorting alphanum and num -- #109: Fixed where Validate sometimes returns wrong message on error - -## 1.4.2 (2018-04-10) - -### Changed - -- #72: Updated the docs to point to vert for a console appliaction -- #71: Update the docs on pre-release comparator handling - -### Fixed - -- #70: Fix the handling of pre-releases and the 0.0.0 release edge case - -## 1.4.1 (2018-04-02) - -### Fixed - -- Fixed #64: Fix pre-release precedence issue (thanks @uudashr) - -## 1.4.0 (2017-10-04) - -### Changed - -- #61: Update NewVersion to parse ints with a 64bit int size (thanks @zknill) - -## 1.3.1 (2017-07-10) - -### Fixed - -- Fixed #57: number comparisons in prerelease sometimes inaccurate - -## 1.3.0 (2017-05-02) - -### Added - -- #45: Added json (un)marshaling support (thanks @mh-cbon) -- Stability marker. See https://masterminds.github.io/stability/ - -### Fixed - -- #51: Fix handling of single digit tilde constraint (thanks @dgodd) - -### Changed - -- #55: The godoc icon moved from png to svg - -## 1.2.3 (2017-04-03) - -### Fixed - -- #46: Fixed 0.x.x and 0.0.x in constraints being treated as * - -## Release 1.2.2 (2016-12-13) - -### Fixed - -- #34: Fixed issue where hyphen range was not working with pre-release parsing. - -## Release 1.2.1 (2016-11-28) - -### Fixed - -- #24: Fixed edge case issue where constraint "> 0" does not handle "0.0.1-alpha" - properly. - -## Release 1.2.0 (2016-11-04) - -### Added - -- #20: Added MustParse function for versions (thanks @adamreese) -- #15: Added increment methods on versions (thanks @mh-cbon) - -### Fixed - -- Issue #21: Per the SemVer spec (section 9) a pre-release is unstable and - might not satisfy the intended compatibility. The change here ignores pre-releases - on constraint checks (e.g., ~ or ^) when a pre-release is not part of the - constraint. For example, `^1.2.3` will ignore pre-releases while - `^1.2.3-alpha` will include them. - -## Release 1.1.1 (2016-06-30) - -### Changed - -- Issue #9: Speed up version comparison performance (thanks @sdboyer) -- Issue #8: Added benchmarks (thanks @sdboyer) -- Updated Go Report Card URL to new location -- Updated Readme to add code snippet formatting (thanks @mh-cbon) -- Updating tagging to v[SemVer] structure for compatibility with other tools. - -## Release 1.1.0 (2016-03-11) - -- Issue #2: Implemented validation to provide reasons a versions failed a - constraint. - -## Release 1.0.1 (2015-12-31) - -- Fixed #1: * constraint failing on valid versions. - -## Release 1.0.0 (2015-10-20) - -- Initial release diff --git a/vendor/github.com/Masterminds/semver/v3/LICENSE.txt b/vendor/github.com/Masterminds/semver/v3/LICENSE.txt deleted file mode 100644 index 9ff7da9c4..000000000 --- a/vendor/github.com/Masterminds/semver/v3/LICENSE.txt +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2014-2019, Matt Butcher and Matt Farina - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/Masterminds/semver/v3/Makefile b/vendor/github.com/Masterminds/semver/v3/Makefile deleted file mode 100644 index eac19178f..000000000 --- a/vendor/github.com/Masterminds/semver/v3/Makefile +++ /dev/null @@ -1,37 +0,0 @@ -GOPATH=$(shell go env GOPATH) -GOLANGCI_LINT=$(GOPATH)/bin/golangci-lint -GOFUZZBUILD = $(GOPATH)/bin/go-fuzz-build -GOFUZZ = $(GOPATH)/bin/go-fuzz - -.PHONY: lint -lint: $(GOLANGCI_LINT) - @echo "==> Linting codebase" - @$(GOLANGCI_LINT) run - -.PHONY: test -test: - @echo "==> Running tests" - GO111MODULE=on go test -v - -.PHONY: test-cover -test-cover: - @echo "==> Running Tests with coverage" - GO111MODULE=on go test -cover . - -.PHONY: fuzz -fuzz: $(GOFUZZBUILD) $(GOFUZZ) - @echo "==> Fuzz testing" - $(GOFUZZBUILD) - $(GOFUZZ) -workdir=_fuzz - -$(GOLANGCI_LINT): - # Install golangci-lint. The configuration for it is in the .golangci.yml - # file in the root of the repository - echo ${GOPATH} - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.17.1 - -$(GOFUZZBUILD): - cd / && go get -u github.com/dvyukov/go-fuzz/go-fuzz-build - -$(GOFUZZ): - cd / && go get -u github.com/dvyukov/go-fuzz/go-fuzz github.com/dvyukov/go-fuzz/go-fuzz-dep \ No newline at end of file diff --git a/vendor/github.com/Masterminds/semver/v3/README.md b/vendor/github.com/Masterminds/semver/v3/README.md deleted file mode 100644 index d8f54dcbd..000000000 --- a/vendor/github.com/Masterminds/semver/v3/README.md +++ /dev/null @@ -1,244 +0,0 @@ -# SemVer - -The `semver` package provides the ability to work with [Semantic Versions](http://semver.org) in Go. Specifically it provides the ability to: - -* Parse semantic versions -* Sort semantic versions -* Check if a semantic version fits within a set of constraints -* Optionally work with a `v` prefix - -[![Stability: -Active](https://masterminds.github.io/stability/active.svg)](https://masterminds.github.io/stability/active.html) -[![](https://github.com/Masterminds/semver/workflows/Tests/badge.svg)](https://github.com/Masterminds/semver/actions) -[![GoDoc](https://img.shields.io/static/v1?label=godoc&message=reference&color=blue)](https://pkg.go.dev/github.com/Masterminds/semver/v3) -[![Go Report Card](https://goreportcard.com/badge/github.com/Masterminds/semver)](https://goreportcard.com/report/github.com/Masterminds/semver) - -If you are looking for a command line tool for version comparisons please see -[vert](https://github.com/Masterminds/vert) which uses this library. - -## Package Versions - -There are three major versions fo the `semver` package. - -* 3.x.x is the new stable and active version. This version is focused on constraint - compatibility for range handling in other tools from other languages. It has - a similar API to the v1 releases. The development of this version is on the master - branch. The documentation for this version is below. -* 2.x was developed primarily for [dep](https://github.com/golang/dep). There are - no tagged releases and the development was performed by [@sdboyer](https://github.com/sdboyer). - There are API breaking changes from v1. This version lives on the [2.x branch](https://github.com/Masterminds/semver/tree/2.x). -* 1.x.x is the most widely used version with numerous tagged releases. This is the - previous stable and is still maintained for bug fixes. The development, to fix - bugs, occurs on the release-1 branch. You can read the documentation [here](https://github.com/Masterminds/semver/blob/release-1/README.md). - -## Parsing Semantic Versions - -There are two functions that can parse semantic versions. The `StrictNewVersion` -function only parses valid version 2 semantic versions as outlined in the -specification. The `NewVersion` function attempts to coerce a version into a -semantic version and parse it. For example, if there is a leading v or a version -listed without all 3 parts (e.g. `v1.2`) it will attempt to coerce it into a valid -semantic version (e.g., 1.2.0). In both cases a `Version` object is returned -that can be sorted, compared, and used in constraints. - -When parsing a version an error is returned if there is an issue parsing the -version. For example, - - v, err := semver.NewVersion("1.2.3-beta.1+build345") - -The version object has methods to get the parts of the version, compare it to -other versions, convert the version back into a string, and get the original -string. Getting the original string is useful if the semantic version was coerced -into a valid form. - -## Sorting Semantic Versions - -A set of versions can be sorted using the `sort` package from the standard library. -For example, - -```go -raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} -vs := make([]*semver.Version, len(raw)) -for i, r := range raw { - v, err := semver.NewVersion(r) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - vs[i] = v -} - -sort.Sort(semver.Collection(vs)) -``` - -## Checking Version Constraints - -There are two methods for comparing versions. One uses comparison methods on -`Version` instances and the other uses `Constraints`. There are some important -differences to notes between these two methods of comparison. - -1. When two versions are compared using functions such as `Compare`, `LessThan`, - and others it will follow the specification and always include prereleases - within the comparison. It will provide an answer that is valid with the - comparison section of the spec at https://semver.org/#spec-item-11 -2. When constraint checking is used for checks or validation it will follow a - different set of rules that are common for ranges with tools like npm/js - and Rust/Cargo. This includes considering prereleases to be invalid if the - ranges does not include one. If you want to have it include pre-releases a - simple solution is to include `-0` in your range. -3. Constraint ranges can have some complex rules including the shorthand use of - ~ and ^. For more details on those see the options below. - -There are differences between the two methods or checking versions because the -comparison methods on `Version` follow the specification while comparison ranges -are not part of the specification. Different packages and tools have taken it -upon themselves to come up with range rules. This has resulted in differences. -For example, npm/js and Cargo/Rust follow similar patterns while PHP has a -different pattern for ^. The comparison features in this package follow the -npm/js and Cargo/Rust lead because applications using it have followed similar -patters with their versions. - -Checking a version against version constraints is one of the most featureful -parts of the package. - -```go -c, err := semver.NewConstraint(">= 1.2.3") -if err != nil { - // Handle constraint not being parsable. -} - -v, err := semver.NewVersion("1.3") -if err != nil { - // Handle version not being parsable. -} -// Check if the version meets the constraints. The a variable will be true. -a := c.Check(v) -``` - -### Basic Comparisons - -There are two elements to the comparisons. First, a comparison string is a list -of space or comma separated AND comparisons. These are then separated by || (OR) -comparisons. For example, `">= 1.2 < 3.0.0 || >= 4.2.3"` is looking for a -comparison that's greater than or equal to 1.2 and less than 3.0.0 or is -greater than or equal to 4.2.3. - -The basic comparisons are: - -* `=`: equal (aliased to no operator) -* `!=`: not equal -* `>`: greater than -* `<`: less than -* `>=`: greater than or equal to -* `<=`: less than or equal to - -### Working With Prerelease Versions - -Pre-releases, for those not familiar with them, are used for software releases -prior to stable or generally available releases. Examples of prereleases include -development, alpha, beta, and release candidate releases. A prerelease may be -a version such as `1.2.3-beta.1` while the stable release would be `1.2.3`. In the -order of precedence, prereleases come before their associated releases. In this -example `1.2.3-beta.1 < 1.2.3`. - -According to the Semantic Version specification prereleases may not be -API compliant with their release counterpart. It says, - -> A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version. - -SemVer comparisons using constraints without a prerelease comparator will skip -prerelease versions. For example, `>=1.2.3` will skip prereleases when looking -at a list of releases while `>=1.2.3-0` will evaluate and find prereleases. - -The reason for the `0` as a pre-release version in the example comparison is -because pre-releases can only contain ASCII alphanumerics and hyphens (along with -`.` separators), per the spec. Sorting happens in ASCII sort order, again per the -spec. The lowest character is a `0` in ASCII sort order -(see an [ASCII Table](http://www.asciitable.com/)) - -Understanding ASCII sort ordering is important because A-Z comes before a-z. That -means `>=1.2.3-BETA` will return `1.2.3-alpha`. What you might expect from case -sensitivity doesn't apply here. This is due to ASCII sort ordering which is what -the spec specifies. - -### Hyphen Range Comparisons - -There are multiple methods to handle ranges and the first is hyphens ranges. -These look like: - -* `1.2 - 1.4.5` which is equivalent to `>= 1.2 <= 1.4.5` -* `2.3.4 - 4.5` which is equivalent to `>= 2.3.4 <= 4.5` - -### Wildcards In Comparisons - -The `x`, `X`, and `*` characters can be used as a wildcard character. This works -for all comparison operators. When used on the `=` operator it falls -back to the patch level comparison (see tilde below). For example, - -* `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` -* `>= 1.2.x` is equivalent to `>= 1.2.0` -* `<= 2.x` is equivalent to `< 3` -* `*` is equivalent to `>= 0.0.0` - -### Tilde Range Comparisons (Patch) - -The tilde (`~`) comparison operator is for patch level ranges when a minor -version is specified and major level changes when the minor number is missing. -For example, - -* `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` -* `~1` is equivalent to `>= 1, < 2` -* `~2.3` is equivalent to `>= 2.3, < 2.4` -* `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` -* `~1.x` is equivalent to `>= 1, < 2` - -### Caret Range Comparisons (Major) - -The caret (`^`) comparison operator is for major level changes once a stable -(1.0.0) release has occurred. Prior to a 1.0.0 release the minor versions acts -as the API stability level. This is useful when comparisons of API versions as a -major change is API breaking. For example, - -* `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` -* `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` -* `^2.3` is equivalent to `>= 2.3, < 3` -* `^2.x` is equivalent to `>= 2.0.0, < 3` -* `^0.2.3` is equivalent to `>=0.2.3 <0.3.0` -* `^0.2` is equivalent to `>=0.2.0 <0.3.0` -* `^0.0.3` is equivalent to `>=0.0.3 <0.0.4` -* `^0.0` is equivalent to `>=0.0.0 <0.1.0` -* `^0` is equivalent to `>=0.0.0 <1.0.0` - -## Validation - -In addition to testing a version against a constraint, a version can be validated -against a constraint. When validation fails a slice of errors containing why a -version didn't meet the constraint is returned. For example, - -```go -c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") -if err != nil { - // Handle constraint not being parseable. -} - -v, err := semver.NewVersion("1.3") -if err != nil { - // Handle version not being parseable. -} - -// Validate a version against a constraint. -a, msgs := c.Validate(v) -// a is false -for _, m := range msgs { - fmt.Println(m) - - // Loops over the errors which would read - // "1.3 is greater than 1.2.3" - // "1.3 is less than 1.4" -} -``` - -## Contribute - -If you find an issue or want to contribute please file an [issue](https://github.com/Masterminds/semver/issues) -or [create a pull request](https://github.com/Masterminds/semver/pulls). diff --git a/vendor/github.com/Masterminds/semver/v3/collection.go b/vendor/github.com/Masterminds/semver/v3/collection.go deleted file mode 100644 index a78235895..000000000 --- a/vendor/github.com/Masterminds/semver/v3/collection.go +++ /dev/null @@ -1,24 +0,0 @@ -package semver - -// Collection is a collection of Version instances and implements the sort -// interface. See the sort package for more details. -// https://golang.org/pkg/sort/ -type Collection []*Version - -// Len returns the length of a collection. The number of Version instances -// on the slice. -func (c Collection) Len() int { - return len(c) -} - -// Less is needed for the sort interface to compare two Version objects on the -// slice. If checks if one is less than the other. -func (c Collection) Less(i, j int) bool { - return c[i].LessThan(c[j]) -} - -// Swap is needed for the sort interface to replace the Version objects -// at two different positions in the slice. -func (c Collection) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} diff --git a/vendor/github.com/Masterminds/semver/v3/constraints.go b/vendor/github.com/Masterminds/semver/v3/constraints.go deleted file mode 100644 index 547613f04..000000000 --- a/vendor/github.com/Masterminds/semver/v3/constraints.go +++ /dev/null @@ -1,568 +0,0 @@ -package semver - -import ( - "bytes" - "errors" - "fmt" - "regexp" - "strings" -) - -// Constraints is one or more constraint that a semantic version can be -// checked against. -type Constraints struct { - constraints [][]*constraint -} - -// NewConstraint returns a Constraints instance that a Version instance can -// be checked against. If there is a parse error it will be returned. -func NewConstraint(c string) (*Constraints, error) { - - // Rewrite - ranges into a comparison operation. - c = rewriteRange(c) - - ors := strings.Split(c, "||") - or := make([][]*constraint, len(ors)) - for k, v := range ors { - - // TODO: Find a way to validate and fetch all the constraints in a simpler form - - // Validate the segment - if !validConstraintRegex.MatchString(v) { - return nil, fmt.Errorf("improper constraint: %s", v) - } - - cs := findConstraintRegex.FindAllString(v, -1) - if cs == nil { - cs = append(cs, v) - } - result := make([]*constraint, len(cs)) - for i, s := range cs { - pc, err := parseConstraint(s) - if err != nil { - return nil, err - } - - result[i] = pc - } - or[k] = result - } - - o := &Constraints{constraints: or} - return o, nil -} - -// Check tests if a version satisfies the constraints. -func (cs Constraints) Check(v *Version) bool { - // TODO(mattfarina): For v4 of this library consolidate the Check and Validate - // functions as the underlying functions make that possible now. - // loop over the ORs and check the inner ANDs - for _, o := range cs.constraints { - joy := true - for _, c := range o { - if check, _ := c.check(v); !check { - joy = false - break - } - } - - if joy { - return true - } - } - - return false -} - -// Validate checks if a version satisfies a constraint. If not a slice of -// reasons for the failure are returned in addition to a bool. -func (cs Constraints) Validate(v *Version) (bool, []error) { - // loop over the ORs and check the inner ANDs - var e []error - - // Capture the prerelease message only once. When it happens the first time - // this var is marked - var prerelesase bool - for _, o := range cs.constraints { - joy := true - for _, c := range o { - // Before running the check handle the case there the version is - // a prerelease and the check is not searching for prereleases. - if c.con.pre == "" && v.pre != "" { - if !prerelesase { - em := fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - e = append(e, em) - prerelesase = true - } - joy = false - - } else { - - if _, err := c.check(v); err != nil { - e = append(e, err) - joy = false - } - } - } - - if joy { - return true, []error{} - } - } - - return false, e -} - -func (cs Constraints) String() string { - buf := make([]string, len(cs.constraints)) - var tmp bytes.Buffer - - for k, v := range cs.constraints { - tmp.Reset() - vlen := len(v) - for kk, c := range v { - tmp.WriteString(c.string()) - - // Space separate the AND conditions - if vlen > 1 && kk < vlen-1 { - tmp.WriteString(" ") - } - } - buf[k] = tmp.String() - } - - return strings.Join(buf, " || ") -} - -var constraintOps map[string]cfunc -var constraintRegex *regexp.Regexp -var constraintRangeRegex *regexp.Regexp - -// Used to find individual constraints within a multi-constraint string -var findConstraintRegex *regexp.Regexp - -// Used to validate an segment of ANDs is valid -var validConstraintRegex *regexp.Regexp - -const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` + - `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + - `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` - -func init() { - constraintOps = map[string]cfunc{ - "": constraintTildeOrEqual, - "=": constraintTildeOrEqual, - "!=": constraintNotEqual, - ">": constraintGreaterThan, - "<": constraintLessThan, - ">=": constraintGreaterThanEqual, - "=>": constraintGreaterThanEqual, - "<=": constraintLessThanEqual, - "=<": constraintLessThanEqual, - "~": constraintTilde, - "~>": constraintTilde, - "^": constraintCaret, - } - - ops := `=||!=|>|<|>=|=>|<=|=<|~|~>|\^` - - constraintRegex = regexp.MustCompile(fmt.Sprintf( - `^\s*(%s)\s*(%s)\s*$`, - ops, - cvRegex)) - - constraintRangeRegex = regexp.MustCompile(fmt.Sprintf( - `\s*(%s)\s+-\s+(%s)\s*`, - cvRegex, cvRegex)) - - findConstraintRegex = regexp.MustCompile(fmt.Sprintf( - `(%s)\s*(%s)`, - ops, - cvRegex)) - - validConstraintRegex = regexp.MustCompile(fmt.Sprintf( - `^(\s*(%s)\s*(%s)\s*\,?)+$`, - ops, - cvRegex)) -} - -// An individual constraint -type constraint struct { - // The version used in the constraint check. For example, if a constraint - // is '<= 2.0.0' the con a version instance representing 2.0.0. - con *Version - - // The original parsed version (e.g., 4.x from != 4.x) - orig string - - // The original operator for the constraint - origfunc string - - // When an x is used as part of the version (e.g., 1.x) - minorDirty bool - dirty bool - patchDirty bool -} - -// Check if a version meets the constraint -func (c *constraint) check(v *Version) (bool, error) { - return constraintOps[c.origfunc](v, c) -} - -// String prints an individual constraint into a string -func (c *constraint) string() string { - return c.origfunc + c.orig -} - -type cfunc func(v *Version, c *constraint) (bool, error) - -func parseConstraint(c string) (*constraint, error) { - if len(c) > 0 { - m := constraintRegex.FindStringSubmatch(c) - if m == nil { - return nil, fmt.Errorf("improper constraint: %s", c) - } - - cs := &constraint{ - orig: m[2], - origfunc: m[1], - } - - ver := m[2] - minorDirty := false - patchDirty := false - dirty := false - if isX(m[3]) || m[3] == "" { - ver = "0.0.0" - dirty = true - } else if isX(strings.TrimPrefix(m[4], ".")) || m[4] == "" { - minorDirty = true - dirty = true - ver = fmt.Sprintf("%s.0.0%s", m[3], m[6]) - } else if isX(strings.TrimPrefix(m[5], ".")) || m[5] == "" { - dirty = true - patchDirty = true - ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6]) - } - - con, err := NewVersion(ver) - if err != nil { - - // The constraintRegex should catch any regex parsing errors. So, - // we should never get here. - return nil, errors.New("constraint Parser Error") - } - - cs.con = con - cs.minorDirty = minorDirty - cs.patchDirty = patchDirty - cs.dirty = dirty - - return cs, nil - } - - // The rest is the special case where an empty string was passed in which - // is equivalent to * or >=0.0.0 - con, err := StrictNewVersion("0.0.0") - if err != nil { - - // The constraintRegex should catch any regex parsing errors. So, - // we should never get here. - return nil, errors.New("constraint Parser Error") - } - - cs := &constraint{ - con: con, - orig: c, - origfunc: "", - minorDirty: false, - patchDirty: false, - dirty: true, - } - return cs, nil -} - -// Constraint functions -func constraintNotEqual(v *Version, c *constraint) (bool, error) { - if c.dirty { - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - if c.con.Major() != v.Major() { - return true, nil - } - if c.con.Minor() != v.Minor() && !c.minorDirty { - return true, nil - } else if c.minorDirty { - return false, fmt.Errorf("%s is equal to %s", v, c.orig) - } else if c.con.Patch() != v.Patch() && !c.patchDirty { - return true, nil - } else if c.patchDirty { - // Need to handle prereleases if present - if v.Prerelease() != "" || c.con.Prerelease() != "" { - eq := comparePrerelease(v.Prerelease(), c.con.Prerelease()) != 0 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is equal to %s", v, c.orig) - } - return false, fmt.Errorf("%s is equal to %s", v, c.orig) - } - } - - eq := v.Equal(c.con) - if eq { - return false, fmt.Errorf("%s is equal to %s", v, c.orig) - } - - return true, nil -} - -func constraintGreaterThan(v *Version, c *constraint) (bool, error) { - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - var eq bool - - if !c.dirty { - eq = v.Compare(c.con) == 1 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) - } - - if v.Major() > c.con.Major() { - return true, nil - } else if v.Major() < c.con.Major() { - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) - } else if c.minorDirty { - // This is a range case such as >11. When the version is something like - // 11.1.0 is it not > 11. For that we would need 12 or higher - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) - } else if c.patchDirty { - // This is for ranges such as >11.1. A version of 11.1.1 is not greater - // which one of 11.2.1 is greater - eq = v.Minor() > c.con.Minor() - if eq { - return true, nil - } - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) - } - - // If we have gotten here we are not comparing pre-preleases and can use the - // Compare function to accomplish that. - eq = v.Compare(c.con) == 1 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) -} - -func constraintLessThan(v *Version, c *constraint) (bool, error) { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - eq := v.Compare(c.con) < 0 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is greater than or equal to %s", v, c.orig) -} - -func constraintGreaterThanEqual(v *Version, c *constraint) (bool, error) { - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - eq := v.Compare(c.con) >= 0 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is less than %s", v, c.orig) -} - -func constraintLessThanEqual(v *Version, c *constraint) (bool, error) { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - var eq bool - - if !c.dirty { - eq = v.Compare(c.con) <= 0 - if eq { - return true, nil - } - return false, fmt.Errorf("%s is greater than %s", v, c.orig) - } - - if v.Major() > c.con.Major() { - return false, fmt.Errorf("%s is greater than %s", v, c.orig) - } else if v.Major() == c.con.Major() && v.Minor() > c.con.Minor() && !c.minorDirty { - return false, fmt.Errorf("%s is greater than %s", v, c.orig) - } - - return true, nil -} - -// ~*, ~>* --> >= 0.0.0 (any) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0, <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0, <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0 -func constraintTilde(v *Version, c *constraint) (bool, error) { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - if v.LessThan(c.con) { - return false, fmt.Errorf("%s is less than %s", v, c.orig) - } - - // ~0.0.0 is a special case where all constraints are accepted. It's - // equivalent to >= 0.0.0. - if c.con.Major() == 0 && c.con.Minor() == 0 && c.con.Patch() == 0 && - !c.minorDirty && !c.patchDirty { - return true, nil - } - - if v.Major() != c.con.Major() { - return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) - } - - if v.Minor() != c.con.Minor() && !c.minorDirty { - return false, fmt.Errorf("%s does not have same major and minor version as %s", v, c.orig) - } - - return true, nil -} - -// When there is a .x (dirty) status it automatically opts in to ~. Otherwise -// it's a straight = -func constraintTildeOrEqual(v *Version, c *constraint) (bool, error) { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - if c.dirty { - return constraintTilde(v, c) - } - - eq := v.Equal(c.con) - if eq { - return true, nil - } - - return false, fmt.Errorf("%s is not equal to %s", v, c.orig) -} - -// ^* --> (any) -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2 --> >=1.2.0 <2.0.0 -// ^1 --> >=1.0.0 <2.0.0 -// ^0.2.3 --> >=0.2.3 <0.3.0 -// ^0.2 --> >=0.2.0 <0.3.0 -// ^0.0.3 --> >=0.0.3 <0.0.4 -// ^0.0 --> >=0.0.0 <0.1.0 -// ^0 --> >=0.0.0 <1.0.0 -func constraintCaret(v *Version, c *constraint) (bool, error) { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) - } - - // This less than handles prereleases - if v.LessThan(c.con) { - return false, fmt.Errorf("%s is less than %s", v, c.orig) - } - - var eq bool - - // ^ when the major > 0 is >=x.y.z < x+1 - if c.con.Major() > 0 || c.minorDirty { - - // ^ has to be within a major range for > 0. Everything less than was - // filtered out with the LessThan call above. This filters out those - // that greater but not within the same major range. - eq = v.Major() == c.con.Major() - if eq { - return true, nil - } - return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) - } - - // ^ when the major is 0 and minor > 0 is >=0.y.z < 0.y+1 - if c.con.Major() == 0 && v.Major() > 0 { - return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) - } - // If the con Minor is > 0 it is not dirty - if c.con.Minor() > 0 || c.patchDirty { - eq = v.Minor() == c.con.Minor() - if eq { - return true, nil - } - return false, fmt.Errorf("%s does not have same minor version as %s. Expected minor versions to match when constraint major version is 0", v, c.orig) - } - - // At this point the major is 0 and the minor is 0 and not dirty. The patch - // is not dirty so we need to check if they are equal. If they are not equal - eq = c.con.Patch() == v.Patch() - if eq { - return true, nil - } - return false, fmt.Errorf("%s does not equal %s. Expect version and constraint to equal when major and minor versions are 0", v, c.orig) -} - -func isX(x string) bool { - switch x { - case "x", "*", "X": - return true - default: - return false - } -} - -func rewriteRange(i string) string { - m := constraintRangeRegex.FindAllStringSubmatch(i, -1) - if m == nil { - return i - } - o := i - for _, v := range m { - t := fmt.Sprintf(">= %s, <= %s", v[1], v[11]) - o = strings.Replace(o, v[0], t, 1) - } - - return o -} diff --git a/vendor/github.com/Masterminds/semver/v3/doc.go b/vendor/github.com/Masterminds/semver/v3/doc.go deleted file mode 100644 index 391aa46b7..000000000 --- a/vendor/github.com/Masterminds/semver/v3/doc.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Package semver provides the ability to work with Semantic Versions (http://semver.org) in Go. - -Specifically it provides the ability to: - - * Parse semantic versions - * Sort semantic versions - * Check if a semantic version fits within a set of constraints - * Optionally work with a `v` prefix - -Parsing Semantic Versions - -There are two functions that can parse semantic versions. The `StrictNewVersion` -function only parses valid version 2 semantic versions as outlined in the -specification. The `NewVersion` function attempts to coerce a version into a -semantic version and parse it. For example, if there is a leading v or a version -listed without all 3 parts (e.g. 1.2) it will attempt to coerce it into a valid -semantic version (e.g., 1.2.0). In both cases a `Version` object is returned -that can be sorted, compared, and used in constraints. - -When parsing a version an optional error can be returned if there is an issue -parsing the version. For example, - - v, err := semver.NewVersion("1.2.3-beta.1+b345") - -The version object has methods to get the parts of the version, compare it to -other versions, convert the version back into a string, and get the original -string. For more details please see the documentation -at https://godoc.org/github.com/Masterminds/semver. - -Sorting Semantic Versions - -A set of versions can be sorted using the `sort` package from the standard library. -For example, - - raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} - vs := make([]*semver.Version, len(raw)) - for i, r := range raw { - v, err := semver.NewVersion(r) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - vs[i] = v - } - - sort.Sort(semver.Collection(vs)) - -Checking Version Constraints and Comparing Versions - -There are two methods for comparing versions. One uses comparison methods on -`Version` instances and the other is using Constraints. There are some important -differences to notes between these two methods of comparison. - -1. When two versions are compared using functions such as `Compare`, `LessThan`, - and others it will follow the specification and always include prereleases - within the comparison. It will provide an answer valid with the comparison - spec section at https://semver.org/#spec-item-11 -2. When constraint checking is used for checks or validation it will follow a - different set of rules that are common for ranges with tools like npm/js - and Rust/Cargo. This includes considering prereleases to be invalid if the - ranges does not include on. If you want to have it include pre-releases a - simple solution is to include `-0` in your range. -3. Constraint ranges can have some complex rules including the shorthard use of - ~ and ^. For more details on those see the options below. - -There are differences between the two methods or checking versions because the -comparison methods on `Version` follow the specification while comparison ranges -are not part of the specification. Different packages and tools have taken it -upon themselves to come up with range rules. This has resulted in differences. -For example, npm/js and Cargo/Rust follow similar patterns which PHP has a -different pattern for ^. The comparison features in this package follow the -npm/js and Cargo/Rust lead because applications using it have followed similar -patters with their versions. - -Checking a version against version constraints is one of the most featureful -parts of the package. - - c, err := semver.NewConstraint(">= 1.2.3") - if err != nil { - // Handle constraint not being parsable. - } - - v, err := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parsable. - } - // Check if the version meets the constraints. The a variable will be true. - a := c.Check(v) - -Basic Comparisons - -There are two elements to the comparisons. First, a comparison string is a list -of comma or space separated AND comparisons. These are then separated by || (OR) -comparisons. For example, `">= 1.2 < 3.0.0 || >= 4.2.3"` is looking for a -comparison that's greater than or equal to 1.2 and less than 3.0.0 or is -greater than or equal to 4.2.3. This can also be written as -`">= 1.2, < 3.0.0 || >= 4.2.3"` - -The basic comparisons are: - - * `=`: equal (aliased to no operator) - * `!=`: not equal - * `>`: greater than - * `<`: less than - * `>=`: greater than or equal to - * `<=`: less than or equal to - -Hyphen Range Comparisons - -There are multiple methods to handle ranges and the first is hyphens ranges. -These look like: - - * `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` - * `2.3.4 - 4.5` which is equivalent to `>= 2.3.4 <= 4.5` - -Wildcards In Comparisons - -The `x`, `X`, and `*` characters can be used as a wildcard character. This works -for all comparison operators. When used on the `=` operator it falls -back to the tilde operation. For example, - - * `1.2.x` is equivalent to `>= 1.2.0 < 1.3.0` - * `>= 1.2.x` is equivalent to `>= 1.2.0` - * `<= 2.x` is equivalent to `<= 3` - * `*` is equivalent to `>= 0.0.0` - -Tilde Range Comparisons (Patch) - -The tilde (`~`) comparison operator is for patch level ranges when a minor -version is specified and major level changes when the minor number is missing. -For example, - - * `~1.2.3` is equivalent to `>= 1.2.3 < 1.3.0` - * `~1` is equivalent to `>= 1, < 2` - * `~2.3` is equivalent to `>= 2.3 < 2.4` - * `~1.2.x` is equivalent to `>= 1.2.0 < 1.3.0` - * `~1.x` is equivalent to `>= 1 < 2` - -Caret Range Comparisons (Major) - -The caret (`^`) comparison operator is for major level changes once a stable -(1.0.0) release has occurred. Prior to a 1.0.0 release the minor versions acts -as the API stability level. This is useful when comparisons of API versions as a -major change is API breaking. For example, - - * `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` - * `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` - * `^2.3` is equivalent to `>= 2.3, < 3` - * `^2.x` is equivalent to `>= 2.0.0, < 3` - * `^0.2.3` is equivalent to `>=0.2.3 <0.3.0` - * `^0.2` is equivalent to `>=0.2.0 <0.3.0` - * `^0.0.3` is equivalent to `>=0.0.3 <0.0.4` - * `^0.0` is equivalent to `>=0.0.0 <0.1.0` - * `^0` is equivalent to `>=0.0.0 <1.0.0` - -Validation - -In addition to testing a version against a constraint, a version can be validated -against a constraint. When validation fails a slice of errors containing why a -version didn't meet the constraint is returned. For example, - - c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") - if err != nil { - // Handle constraint not being parseable. - } - - v, _ := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parseable. - } - - // Validate a version against a constraint. - a, msgs := c.Validate(v) - // a is false - for _, m := range msgs { - fmt.Println(m) - - // Loops over the errors which would read - // "1.3 is greater than 1.2.3" - // "1.3 is less than 1.4" - } -*/ -package semver diff --git a/vendor/github.com/Masterminds/semver/v3/fuzz.go b/vendor/github.com/Masterminds/semver/v3/fuzz.go deleted file mode 100644 index a242ad705..000000000 --- a/vendor/github.com/Masterminds/semver/v3/fuzz.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build gofuzz - -package semver - -func Fuzz(data []byte) int { - d := string(data) - - // Test NewVersion - _, _ = NewVersion(d) - - // Test StrictNewVersion - _, _ = StrictNewVersion(d) - - // Test NewConstraint - _, _ = NewConstraint(d) - - // The return value should be 0 normally, 1 if the priority in future tests - // should be increased, and -1 if future tests should skip passing in that - // data. We do not have a reason to change priority so 0 is always returned. - // There are example tests that do this. - return 0 -} diff --git a/vendor/github.com/Masterminds/semver/v3/version.go b/vendor/github.com/Masterminds/semver/v3/version.go deleted file mode 100644 index d6b9cda3e..000000000 --- a/vendor/github.com/Masterminds/semver/v3/version.go +++ /dev/null @@ -1,606 +0,0 @@ -package semver - -import ( - "bytes" - "database/sql/driver" - "encoding/json" - "errors" - "fmt" - "regexp" - "strconv" - "strings" -) - -// The compiled version of the regex created at init() is cached here so it -// only needs to be created once. -var versionRegex *regexp.Regexp - -var ( - // ErrInvalidSemVer is returned a version is found to be invalid when - // being parsed. - ErrInvalidSemVer = errors.New("Invalid Semantic Version") - - // ErrEmptyString is returned when an empty string is passed in for parsing. - ErrEmptyString = errors.New("Version string empty") - - // ErrInvalidCharacters is returned when invalid characters are found as - // part of a version - ErrInvalidCharacters = errors.New("Invalid characters in version") - - // ErrSegmentStartsZero is returned when a version segment starts with 0. - // This is invalid in SemVer. - ErrSegmentStartsZero = errors.New("Version segment starts with 0") - - // ErrInvalidMetadata is returned when the metadata is an invalid format - ErrInvalidMetadata = errors.New("Invalid Metadata string") - - // ErrInvalidPrerelease is returned when the pre-release is an invalid format - ErrInvalidPrerelease = errors.New("Invalid Prerelease string") -) - -// semVerRegex is the regular expression used to parse a semantic version. -const semVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` + - `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + - `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` - -// Version represents a single semantic version. -type Version struct { - major, minor, patch uint64 - pre string - metadata string - original string -} - -func init() { - versionRegex = regexp.MustCompile("^" + semVerRegex + "$") -} - -const num string = "0123456789" -const allowed string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-" + num - -// StrictNewVersion parses a given version and returns an instance of Version or -// an error if unable to parse the version. Only parses valid semantic versions. -// Performs checking that can find errors within the version. -// If you want to coerce a version, such as 1 or 1.2, and perse that as the 1.x -// releases of semver provided use the NewSemver() function. -func StrictNewVersion(v string) (*Version, error) { - // Parsing here does not use RegEx in order to increase performance and reduce - // allocations. - - if len(v) == 0 { - return nil, ErrEmptyString - } - - // Split the parts into [0]major, [1]minor, and [2]patch,prerelease,build - parts := strings.SplitN(v, ".", 3) - if len(parts) != 3 { - return nil, ErrInvalidSemVer - } - - sv := &Version{ - original: v, - } - - // check for prerelease or build metadata - var extra []string - if strings.ContainsAny(parts[2], "-+") { - // Start with the build metadata first as it needs to be on the right - extra = strings.SplitN(parts[2], "+", 2) - if len(extra) > 1 { - // build metadata found - sv.metadata = extra[1] - parts[2] = extra[0] - } - - extra = strings.SplitN(parts[2], "-", 2) - if len(extra) > 1 { - // prerelease found - sv.pre = extra[1] - parts[2] = extra[0] - } - } - - // Validate the number segments are valid. This includes only having positive - // numbers and no leading 0's. - for _, p := range parts { - if !containsOnly(p, num) { - return nil, ErrInvalidCharacters - } - - if len(p) > 1 && p[0] == '0' { - return nil, ErrSegmentStartsZero - } - } - - // Extract the major, minor, and patch elements onto the returned Version - var err error - sv.major, err = strconv.ParseUint(parts[0], 10, 64) - if err != nil { - return nil, err - } - - sv.minor, err = strconv.ParseUint(parts[1], 10, 64) - if err != nil { - return nil, err - } - - sv.patch, err = strconv.ParseUint(parts[2], 10, 64) - if err != nil { - return nil, err - } - - // No prerelease or build metadata found so returning now as a fastpath. - if sv.pre == "" && sv.metadata == "" { - return sv, nil - } - - if sv.pre != "" { - if err = validatePrerelease(sv.pre); err != nil { - return nil, err - } - } - - if sv.metadata != "" { - if err = validateMetadata(sv.metadata); err != nil { - return nil, err - } - } - - return sv, nil -} - -// NewVersion parses a given version and returns an instance of Version or -// an error if unable to parse the version. If the version is SemVer-ish it -// attempts to convert it to SemVer. If you want to validate it was a strict -// semantic version at parse time see StrictNewVersion(). -func NewVersion(v string) (*Version, error) { - m := versionRegex.FindStringSubmatch(v) - if m == nil { - return nil, ErrInvalidSemVer - } - - sv := &Version{ - metadata: m[8], - pre: m[5], - original: v, - } - - var err error - sv.major, err = strconv.ParseUint(m[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - - if m[2] != "" { - sv.minor, err = strconv.ParseUint(strings.TrimPrefix(m[2], "."), 10, 64) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - } else { - sv.minor = 0 - } - - if m[3] != "" { - sv.patch, err = strconv.ParseUint(strings.TrimPrefix(m[3], "."), 10, 64) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - } else { - sv.patch = 0 - } - - // Perform some basic due diligence on the extra parts to ensure they are - // valid. - - if sv.pre != "" { - if err = validatePrerelease(sv.pre); err != nil { - return nil, err - } - } - - if sv.metadata != "" { - if err = validateMetadata(sv.metadata); err != nil { - return nil, err - } - } - - return sv, nil -} - -// MustParse parses a given version and panics on error. -func MustParse(v string) *Version { - sv, err := NewVersion(v) - if err != nil { - panic(err) - } - return sv -} - -// String converts a Version object to a string. -// Note, if the original version contained a leading v this version will not. -// See the Original() method to retrieve the original value. Semantic Versions -// don't contain a leading v per the spec. Instead it's optional on -// implementation. -func (v Version) String() string { - var buf bytes.Buffer - - fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch) - if v.pre != "" { - fmt.Fprintf(&buf, "-%s", v.pre) - } - if v.metadata != "" { - fmt.Fprintf(&buf, "+%s", v.metadata) - } - - return buf.String() -} - -// Original returns the original value passed in to be parsed. -func (v *Version) Original() string { - return v.original -} - -// Major returns the major version. -func (v Version) Major() uint64 { - return v.major -} - -// Minor returns the minor version. -func (v Version) Minor() uint64 { - return v.minor -} - -// Patch returns the patch version. -func (v Version) Patch() uint64 { - return v.patch -} - -// Prerelease returns the pre-release version. -func (v Version) Prerelease() string { - return v.pre -} - -// Metadata returns the metadata on the version. -func (v Version) Metadata() string { - return v.metadata -} - -// originalVPrefix returns the original 'v' prefix if any. -func (v Version) originalVPrefix() string { - - // Note, only lowercase v is supported as a prefix by the parser. - if v.original != "" && v.original[:1] == "v" { - return v.original[:1] - } - return "" -} - -// IncPatch produces the next patch version. -// If the current version does not have prerelease/metadata information, -// it unsets metadata and prerelease values, increments patch number. -// If the current version has any of prerelease or metadata information, -// it unsets both values and keeps current patch value -func (v Version) IncPatch() Version { - vNext := v - // according to http://semver.org/#spec-item-9 - // Pre-release versions have a lower precedence than the associated normal version. - // according to http://semver.org/#spec-item-10 - // Build metadata SHOULD be ignored when determining version precedence. - if v.pre != "" { - vNext.metadata = "" - vNext.pre = "" - } else { - vNext.metadata = "" - vNext.pre = "" - vNext.patch = v.patch + 1 - } - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext -} - -// IncMinor produces the next minor version. -// Sets patch to 0. -// Increments minor number. -// Unsets metadata. -// Unsets prerelease status. -func (v Version) IncMinor() Version { - vNext := v - vNext.metadata = "" - vNext.pre = "" - vNext.patch = 0 - vNext.minor = v.minor + 1 - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext -} - -// IncMajor produces the next major version. -// Sets patch to 0. -// Sets minor to 0. -// Increments major number. -// Unsets metadata. -// Unsets prerelease status. -func (v Version) IncMajor() Version { - vNext := v - vNext.metadata = "" - vNext.pre = "" - vNext.patch = 0 - vNext.minor = 0 - vNext.major = v.major + 1 - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext -} - -// SetPrerelease defines the prerelease value. -// Value must not include the required 'hyphen' prefix. -func (v Version) SetPrerelease(prerelease string) (Version, error) { - vNext := v - if len(prerelease) > 0 { - if err := validatePrerelease(prerelease); err != nil { - return vNext, err - } - } - vNext.pre = prerelease - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext, nil -} - -// SetMetadata defines metadata value. -// Value must not include the required 'plus' prefix. -func (v Version) SetMetadata(metadata string) (Version, error) { - vNext := v - if len(metadata) > 0 { - if err := validateMetadata(metadata); err != nil { - return vNext, err - } - } - vNext.metadata = metadata - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext, nil -} - -// LessThan tests if one version is less than another one. -func (v *Version) LessThan(o *Version) bool { - return v.Compare(o) < 0 -} - -// GreaterThan tests if one version is greater than another one. -func (v *Version) GreaterThan(o *Version) bool { - return v.Compare(o) > 0 -} - -// Equal tests if two versions are equal to each other. -// Note, versions can be equal with different metadata since metadata -// is not considered part of the comparable version. -func (v *Version) Equal(o *Version) bool { - return v.Compare(o) == 0 -} - -// Compare compares this version to another one. It returns -1, 0, or 1 if -// the version smaller, equal, or larger than the other version. -// -// Versions are compared by X.Y.Z. Build metadata is ignored. Prerelease is -// lower than the version without a prerelease. Compare always takes into account -// prereleases. If you want to work with ranges using typical range syntaxes that -// skip prereleases if the range is not looking for them use constraints. -func (v *Version) Compare(o *Version) int { - // Compare the major, minor, and patch version for differences. If a - // difference is found return the comparison. - if d := compareSegment(v.Major(), o.Major()); d != 0 { - return d - } - if d := compareSegment(v.Minor(), o.Minor()); d != 0 { - return d - } - if d := compareSegment(v.Patch(), o.Patch()); d != 0 { - return d - } - - // At this point the major, minor, and patch versions are the same. - ps := v.pre - po := o.Prerelease() - - if ps == "" && po == "" { - return 0 - } - if ps == "" { - return 1 - } - if po == "" { - return -1 - } - - return comparePrerelease(ps, po) -} - -// UnmarshalJSON implements JSON.Unmarshaler interface. -func (v *Version) UnmarshalJSON(b []byte) error { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - temp, err := NewVersion(s) - if err != nil { - return err - } - v.major = temp.major - v.minor = temp.minor - v.patch = temp.patch - v.pre = temp.pre - v.metadata = temp.metadata - v.original = temp.original - return nil -} - -// MarshalJSON implements JSON.Marshaler interface. -func (v Version) MarshalJSON() ([]byte, error) { - return json.Marshal(v.String()) -} - -// Scan implements the SQL.Scanner interface. -func (v *Version) Scan(value interface{}) error { - var s string - s, _ = value.(string) - temp, err := NewVersion(s) - if err != nil { - return err - } - v.major = temp.major - v.minor = temp.minor - v.patch = temp.patch - v.pre = temp.pre - v.metadata = temp.metadata - v.original = temp.original - return nil -} - -// Value implements the Driver.Valuer interface. -func (v Version) Value() (driver.Value, error) { - return v.String(), nil -} - -func compareSegment(v, o uint64) int { - if v < o { - return -1 - } - if v > o { - return 1 - } - - return 0 -} - -func comparePrerelease(v, o string) int { - - // split the prelease versions by their part. The separator, per the spec, - // is a . - sparts := strings.Split(v, ".") - oparts := strings.Split(o, ".") - - // Find the longer length of the parts to know how many loop iterations to - // go through. - slen := len(sparts) - olen := len(oparts) - - l := slen - if olen > slen { - l = olen - } - - // Iterate over each part of the prereleases to compare the differences. - for i := 0; i < l; i++ { - // Since the lentgh of the parts can be different we need to create - // a placeholder. This is to avoid out of bounds issues. - stemp := "" - if i < slen { - stemp = sparts[i] - } - - otemp := "" - if i < olen { - otemp = oparts[i] - } - - d := comparePrePart(stemp, otemp) - if d != 0 { - return d - } - } - - // Reaching here means two versions are of equal value but have different - // metadata (the part following a +). They are not identical in string form - // but the version comparison finds them to be equal. - return 0 -} - -func comparePrePart(s, o string) int { - // Fastpath if they are equal - if s == o { - return 0 - } - - // When s or o are empty we can use the other in an attempt to determine - // the response. - if s == "" { - if o != "" { - return -1 - } - return 1 - } - - if o == "" { - if s != "" { - return 1 - } - return -1 - } - - // When comparing strings "99" is greater than "103". To handle - // cases like this we need to detect numbers and compare them. According - // to the semver spec, numbers are always positive. If there is a - at the - // start like -99 this is to be evaluated as an alphanum. numbers always - // have precedence over alphanum. Parsing as Uints because negative numbers - // are ignored. - - oi, n1 := strconv.ParseUint(o, 10, 64) - si, n2 := strconv.ParseUint(s, 10, 64) - - // The case where both are strings compare the strings - if n1 != nil && n2 != nil { - if s > o { - return 1 - } - return -1 - } else if n1 != nil { - // o is a string and s is a number - return -1 - } else if n2 != nil { - // s is a string and o is a number - return 1 - } - // Both are numbers - if si > oi { - return 1 - } - return -1 - -} - -// Like strings.ContainsAny but does an only instead of any. -func containsOnly(s string, comp string) bool { - return strings.IndexFunc(s, func(r rune) bool { - return !strings.ContainsRune(comp, r) - }) == -1 -} - -// From the spec, "Identifiers MUST comprise only -// ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. -// Numeric identifiers MUST NOT include leading zeroes.". These segments can -// be dot separated. -func validatePrerelease(p string) error { - eparts := strings.Split(p, ".") - for _, p := range eparts { - if containsOnly(p, num) { - if len(p) > 1 && p[0] == '0' { - return ErrSegmentStartsZero - } - } else if !containsOnly(p, allowed) { - return ErrInvalidPrerelease - } - } - - return nil -} - -// From the spec, "Build metadata MAY be denoted by -// appending a plus sign and a series of dot separated identifiers immediately -// following the patch or pre-release version. Identifiers MUST comprise only -// ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty." -func validateMetadata(m string) error { - eparts := strings.Split(m, ".") - for _, p := range eparts { - if !containsOnly(p, allowed) { - return ErrInvalidMetadata - } - } - return nil -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/.gitignore b/vendor/github.com/Unleash/unleash-client-go/v4/.gitignore deleted file mode 100644 index 3090f8101..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/.gitignore +++ /dev/null @@ -1,46 +0,0 @@ -# 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 -*.cov - -### Go template -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib - -# Test data -testdata/ - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -.idea/ - -#vs code -.vscode diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/LICENSE b/vendor/github.com/Unleash/unleash-client-go/v4/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/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/vendor/github.com/Unleash/unleash-client-go/v4/Makefile b/vendor/github.com/Unleash/unleash-client-go/v4/Makefile deleted file mode 100644 index 4651b4afb..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -SHELL := /bin/bash - -# go source files, ignore testdata directory -SRC = $(shell find . -type f -name '*.go' -not -path './testdata/*') - -.PHONY: all fmt fmt-check vet check strict-check test test-race - -all: test - -fmt: - gofmt -l -w $(SRC) - -fmt-check: - test -z $$(gofmt -l $(SRC)) - -vet: - go vet ./... - -check: vet - -strict-check: check - golint ./... - -test: check - go test ./... - -test-race: check - go test -race ./... -tags='!norace' diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/README.md b/vendor/github.com/Unleash/unleash-client-go/v4/README.md deleted file mode 100644 index a15ece6d1..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/README.md +++ /dev/null @@ -1,349 +0,0 @@ -[![Build Status](https://github.com/Unleash/unleash-client-go/actions/workflows/build.yml/badge.svg)](https://github.com/Unleash/unleash-client-go/actions/workflows/build.yml) [![GoDoc](https://pkg.go.dev/badge/github.com/Unleash/unleash-client-go/v4?status.svg)](https://pkg.go.dev/github.com/Unleash/unleash-client-go/v4) [![Go Report Card](https://goreportcard.com/badge/github.com/Unleash/unleash-client-go)](https://goreportcard.com/report/github.com/Unleash/unleash-client-go) -[![Coverage Status](https://coveralls.io/repos/github/Unleash/unleash-client-go/badge.svg?branch=v4)](https://coveralls.io/github/Unleash/unleash-client-go?branch=v4) - -# unleash-client-go - -Unleash Client for Go. Read more about the [Unleash project](https://github.com/Unleash/unleash) - -**Version 3.x of the client requires `unleash-server` v4.x or higher.** - -## Go Version - -The client is currently tested against Go 1.10.x and 1.13.x. These versions will be updated -as new versions of Go are released. - -The client may work on older versions of Go as well, but is not actively tested. - -## Getting started - -### 1. Install unleash-client-go - -To install the latest version of the client use: - -```bash -go get github.com/Unleash/unleash-client-go/v4 -``` - -If you are still using Unleash Server v2.x.x, then you should use: - -```bash -go get github.com/Unleash/unleash-client-go -``` - -### 2. Initialize unleash - -The easiest way to get started with Unleash is to initialize it early in your application code: - -**Asynchronous initialization example:** -```go -import ( - "github.com/Unleash/unleash-client-go/v4" -) - -func init() { - unleash.Initialize( - unleash.WithListener(&unleash.DebugListener{}), - unleash.WithAppName("my-application"), - unleash.WithUrl("http://unleash.herokuapp.com/api/"), - unleash.WithCustomHeaders(http.Header{"Authorization": {""}}), - ) -} -``` - -**Synchronous initialization example:** - -```go -import ( - "github.com/Unleash/unleash-client-go/v4" -) - -func init() { - unleash.Initialize( - unleash.WithListener(&unleash.DebugListener{}), - unleash.WithAppName("my-application"), - unleash.WithUrl("http://unleash.herokuapp.com/api/"), - unleash.WithCustomHeaders(http.Header{"Authorization": {""}}), - ) - - // Note this will block until the default client is ready - unleash.WaitForReady() -} -``` - -#### Preloading feature toggles - -If you'd like to prebake your application with feature toggles (maybe you're working without persistent storage, so Unleash's backup isn't available), you can replace the defaultStorage implementation with a BootstrapStorage. This allows you to pass in a reader to where data in the format of `/api/client/features` can be found. - -#### Bootstrapping from file - -Bootstrapping from file on disk is then done using something similar to: - -```go -import ( - "github.com/Unleash/unleash-client-go/v4" -) - -func init() { - myBootstrap := os.Open("bootstrapfile.json") // or wherever your file is located at runtime - // BootstrapStorage handles the case where Reader is nil - unleash.Initialize( - unleash.WithListener(&unleash.DebugListener{}), - unleash.WithAppName("my-application"), - unleash.WithUrl("http://unleash.herokuapp.com/api/"), - unleash.WithStorage(&BootstrapStorage{Reader: myBootstrap}) - ) -} -``` - -#### Bootstrapping from S3 - -Bootstrapping from S3 is then done by downloading the file using the AWS library and then passing in a Reader to the just downloaded file: - -```go -import ( - "github.com/Unleash/unleash-client-go/v4" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/config" - "github.com/aws/aws-sdk-go-v2/service/s3" -) - -func init() { - // Load the shared AWS config - cfg, err := config.LoadDefaultConfig(context.TODO()) - if err != nil { - log.Fatal(err) - } - - // Create an S3 client - client := s3.NewFromConfig(cfg) - - obj, err := client.GetObject(context.TODO(), &s3.GetObjectInput{ - Bucket: aws.String("YOURBUCKET"), - Key: aws.String("YOURKEY"), - }) - - if err != nil { - log.Fatal(err) - } - - reader := obj.Body - defer reader.Close() - - // BootstrapStorage handles the case where Reader is nil - unleash.Initialize( - unleash.WithListener(&unleash.DebugListener{}), - unleash.WithAppName("YOURAPPNAME"), - unleash.WithUrl("YOURINSTANCE_URL"), - unleash.WithStorage(&BootstrapStorage{Reader: reader}) - ) -} -``` - -#### Bootstrapping from Google - -Since the Google Cloud Storage API returns a Reader, implementing a Bootstrap from GCS is done using something similar to - -```go -import ( - "github.com/Unleash/unleash-client-go/v4" - "cloud.google.com/go/storage" -) - -func init() { - ctx := context.Background() // Configure Google Cloud context - client, err := storage.NewClient(ctx) // Configure your client - if err != nil { - // TODO: Handle error. - } - defer client.Close() - - // Fetch the bucket, then object and then create a reader - reader := client.Bucket(bucketName).Object("my-bootstrap.json").NewReader(ctx) - - // BootstrapStorage handles the case where Reader is nil - unleash.Initialize( - unleash.WithListener(&unleash.DebugListener{}), - unleash.WithAppName("my-application"), - unleash.WithUrl("http://unleash.herokuapp.com/api/"), - unleash.WithStorage(&unleash.BootstrapStorage{Reader: reader}) - ) -} -``` - -### 3. Use unleash - -After you have initialized the unleash-client you can easily check if a feature -toggle is enabled or not. - -```go -unleash.IsEnabled("app.ToggleX") -``` - -### 4. Stop unleash - -To shut down the client (turn off the polling) you can simply call the -destroy-method. This is typically not required. - -unleash.Close() - -### Built in activation strategies - -The Go client comes with implementations for the built-in activation strategies -provided by unleash. - -- DefaultStrategy -- UserIdStrategy -- FlexibleRolloutStrategy -- GradualRolloutUserIdStrategy -- GradualRolloutSessionIdStrategy -- GradualRolloutRandomStrategy -- RemoteAddressStrategy -- ApplicationHostnameStrategy - -[Read more about activation strategies in the docs](https://docs.getunleash.io/reference/activation-strategies). - -### Unleash context - -In order to use some of the common activation strategies you must provide an -[unleash-context](https://docs.getunleash.io/reference/unleash-context). -This client SDK allows you to send in the unleash context as part of the `isEnabled` call: - -```go -ctx := context.Context{ - UserId: "123", - SessionId: "some-session-id", - RemoteAddress: "127.0.0.1", -} - -unleash.IsEnabled("someToggle", unleash.WithContext(ctx)) -``` - -### Caveat - -This client uses go routines to report several events and doesn't drain the channel by default. So you need to either register a listener using `WithListener` or drain the channel "manually" (demonstrated in [this example](https://github.com/Unleash/unleash-client-go/blob/master/example_with_instance_test.go)). - -### Feature Resolver - -`FeatureResolver` is a `FeatureOption` used in `IsEnabled` via the `WithResolver`. - -The `FeatureResolver` can be used to provide a feature instance in a different way than the client would normally retrieve it. This alternative resolver can be useful if you already have the feature instance and don't want to incur the cost to retrieve it from the repository. - -An example of its usage is below: - -```go -ctx := context.Context{ - UserId: "123", - SessionId: "some-session-id", - RemoteAddress: "127.0.0.1", -} - -// the FeatureResolver function that will be passed into WithResolver -resolver := func(featureName string) *api.Feature { - if featureName == "someToggle" { - // Feature being created in place for sake of example, but it is preferable an existing feature instance is used - return &api.Feature{ - Name: "someToggle", - Description: "Example of someToggle", - Enabled: true, - Strategies: []api.Strategy{ - { - Id: 1, - Name: "default", - }, - }, - CreatedAt: time.Time{}, - Strategy: "default-strategy", - } - } else { - // it shouldn't reach this block because the name will match above "someToggle" for this example - return nil - } -} - -// This would return true because the matched strategy is default and the feature is Enabled -unleash.IsEnabled("someToggle", unleash.WithContext(ctx), unleash.WithResolver(resolver)) -``` - -## Development - -To override dependency on unleash-client-go github repository to a local development folder (for instance when building a local test-app for the SDK), -you can add the following to your apps `go.mod`: - -```mod - replace github.com/Unleash/unleash-client-go/v4 => ../unleash-client-go/ -``` - - - -## Steps to release - -- Update the clientVersion in `client.go` -- Tag the repository with the new tag - -## Adding client specifications - -In order to make sure the unleash clients uphold their contract, we have defined a set of -client specifications that define this contract. These are used to make sure that each unleash client -at any time adhere to the contract, and define a set of functionality that is core to unleash. You can view -the [client specifications here](https://github.com/Unleash/client-specification). - -In order to make the tests run please do the following steps. - -``` -// in repository root -// testdata is gitignored -mkdir testdata -cd testdata -git clone https://github.com/Unleash/client-specification.git -``` - -Requirements: - -- make -- golint (go get -u golang.org/x/lint/golint) - -Run tests: - - make - -Run lint check: - - make lint - -Run code-style checks:(currently failing) - - make strict-check - -Run race-tests: - - make test-race - -## Benchmarking - -You can benchmark feature toggle evaluation by running: - -``` -go test -run=^$ -bench=BenchmarkFeatureToggleEvaluation -benchtime=10s -``` - -Here's an example of how the output could look like: - -``` -goos: darwin -goarch: arm64 -pkg: github.com/Unleash/unleash-client-go/v4 -BenchmarkFeatureToggleEvaluation-8 Final Estimated Operations Per Day: 101.131 billion (1.011315e+11) -13635154 854.3 ns/op -PASS -ok github.com/Unleash/unleash-client-go/v4 13.388s -``` - -In this example the benchmark was run on a MacBook Pro (M1 Pro, 2021) with 16GB RAM. - -We can see a result of **854.3 ns/op**, which means around **101.131 billion** feature toggle evaluations per day. - -**Note**: The benchmark is run with a single CPU core, no parallelism. - -## Design philsophy - -This feature flag SDK is designed according to our design philosophy. You can [read more about that here](https://docs.getunleash.io/topics/feature-flags/feature-flag-best-practices). diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/api/constraint.go b/vendor/github.com/Unleash/unleash-client-go/v4/api/constraint.go deleted file mode 100644 index ce7e7908c..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/api/constraint.go +++ /dev/null @@ -1,87 +0,0 @@ -package api - -// Operator is a type representing a constraint operator -type Operator string - -const ( - // OperatorIn indicates that the context values must be - // contained within those specified in the constraint. - OperatorIn Operator = "IN" - - // OperatorNotIn indicates that the context values must - // NOT be contained within those specified in the constraint. - OperatorNotIn Operator = "NOT_IN" - - // OperatorStrContains indicates that the context value - // must contain the specified substring. - OperatorStrContains Operator = "STR_CONTAINS" - - // OperatorStrStartsWith indicates that the context value - // must have the specified prefix. - OperatorStrStartsWith Operator = "STR_STARTS_WITH" - - // OperatorStrEndsWith indicates that the context value - // must have the specified suffix. - OperatorStrEndsWith Operator = "STR_ENDS_WITH" - - // OperatorNumEq indicates that the context value - // must be equal to the specified number. - OperatorNumEq Operator = "NUM_EQ" - - // OperatorNumLt indicates that the context value - // must be less than the specified number. - OperatorNumLt Operator = "NUM_LT" - - // OperatorNumLte indicates that the context value - // must be less than or equal to the specified number. - OperatorNumLte Operator = "NUM_LTE" - - // OperatorNumGt indicates that the context value - // must be greater than the specified number. - OperatorNumGt Operator = "NUM_GT" - - // OperatorNumGte indicates that the context value - // must be greater than or equal to the specified number. - OperatorNumGte Operator = "NUM_GTE" - - // OperatorDateBefore indicates that the context value - // must be before the specified date. - OperatorDateBefore Operator = "DATE_BEFORE" - - // OperatorDateAfter indicates that the context value - // must be after the specified date. - OperatorDateAfter Operator = "DATE_AFTER" - - // OperatorSemverEq indicates that the context value - // must be equal to the specified SemVer version. - OperatorSemverEq Operator = "SEMVER_EQ" - - // OperatorSemverLt indicates that the context value - // must be less than the specified SemVer version. - OperatorSemverLt Operator = "SEMVER_LT" - - // OperatorSemverGt indicates that the context value - // must be greater than the specified SemVer version. - OperatorSemverGt Operator = "SEMVER_GT" -) - -// Constraint represents a constraint on a particular context value. -type Constraint struct { - // ContextName is the context name of the constraint. - ContextName string `json:"contextName"` - - // Operator is the operator of the constraint. - Operator Operator `json:"operator"` - - // Values is the list of target values for multi-valued constraints. - Values []string `json:"values"` - - // Value is the target value single-value constraints. - Value string `json:"value"` - - // CaseInsensitive makes the string operators case-insensitive. - CaseInsensitive bool `json:"caseInsensitive"` - - // Inverted flips the constraint check result. - Inverted bool `json:"inverted"` -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/api/feature.go b/vendor/github.com/Unleash/unleash-client-go/v4/api/feature.go deleted file mode 100644 index e736a4e1e..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/api/feature.go +++ /dev/null @@ -1,156 +0,0 @@ -package api - -import ( - "math/rand" - "strconv" - "time" - - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/internal/strategies" -) - -type ParameterMap map[string]interface{} - -type FeatureResponse struct { - Response - Features []Feature `json:"features"` - Segments []Segment `json:"segments"` -} - -type Segment struct { - Id int `json:"id"` - Constraints []Constraint `json:"constraints"` -} - -type Feature struct { - // Name is the name of the feature toggle. - Name string `json:"name"` - - // Type is the type of the feature toggle. - Type string `json:"type"` - - // Description is a description of the feature toggle. - Description string `json:"description"` - - // Enabled indicates whether the feature was enabled or not. - Enabled bool `json:"enabled"` - - // Strategies is a list of names of the strategies supported by the client. - Strategies []Strategy `json:"strategies"` - - // CreatedAt is the creation time of the feature toggle. - CreatedAt time.Time `json:"createdAt"` - - // Strategy is the strategy of the feature toggle. - Strategy string `json:"strategy"` - - // Parameters is the parameters of the feature toggle. - Parameters ParameterMap `json:"parameters"` - - // Variants is a list of variants of the feature toggle. - Variants []VariantInternal `json:"variants"` - - // Dependencies is a list of feature toggle dependency objects - Dependencies *[]Dependency `json:"dependencies"` - - // ImpressionData indicates whether the client SDK should emit an impression event - ImpressionData bool `json:"impressionData"` -} - -type Dependency struct { - // Feature is the name of the feature toggle we depend upon - Feature string `json:"feature"` - // Variants contains a string of variants that the dependency should resolve to - Variants *[]string `json:"variants"` - // Enabled is the property that determines whether the dependency should be on or off - // If the property is absent from the payload it's assumed to be default on - Enabled *bool `json:"enabled"` -} - -func (fr FeatureResponse) FeatureMap() map[string]interface{} { - features := map[string]interface{}{} - for _, f := range fr.Features { - features[f.Name] = f - } - return features -} - -func (fr FeatureResponse) SegmentsMap() map[int][]Constraint { - segments := map[int][]Constraint{} - for _, segment := range fr.Segments { - segments[segment.Id] = segment.Constraints - } - - return segments -} - -// Get variant for a given feature which is considered as enabled -func (vc VariantCollection) GetVariant(ctx *context.Context) *Variant { - if len(vc.Variants) > 0 { - v := vc.getOverrideVariant(ctx) - var variant *Variant - if v == nil { - variant = vc.getVariantFromWeights(ctx) - } else { - variant = &v.Variant - } - variant.Enabled = true - variant.FeatureEnabled = true - return variant - } - return DISABLED_VARIANT -} - -func (vc VariantCollection) getVariantFromWeights(ctx *context.Context) *Variant { - totalWeight := 0 - for _, variant := range vc.Variants { - totalWeight += variant.Weight - } - if totalWeight == 0 { - return DISABLED_VARIANT - } - stickiness := vc.Variants[0].Stickiness - - target := strategies.NormalizedVariantValue(getSeed(ctx, stickiness), vc.GroupId, totalWeight, strategies.VariantNormalizationSeed) - counter := uint32(0) - for _, variant := range vc.Variants { - counter += uint32(variant.Weight) - - if counter >= target { - return &variant.Variant - } - } - return DISABLED_VARIANT -} - -func (vc VariantCollection) getOverrideVariant(ctx *context.Context) *VariantInternal { - for _, variant := range vc.Variants { - for _, override := range variant.Overrides { - if override.matchValue(ctx) { - variant.Overrides = nil - return &variant - } - } - } - return nil -} - -func getSeed(ctx *context.Context, stickiness string) string { - if stickiness != "default" && stickiness != "" { - value := ctx.Field(stickiness) - if value == "" { - return strconv.Itoa(rand.Intn(10000)) - } - - return value - } - - if ctx.UserId != "" { - return ctx.UserId - } else if ctx.SessionId != "" { - return ctx.SessionId - } else if ctx.RemoteAddress != "" { - return ctx.RemoteAddress - } - return strconv.Itoa(rand.Intn(10000)) -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/api/response.go b/vendor/github.com/Unleash/unleash-client-go/v4/api/response.go deleted file mode 100644 index 49e06545f..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/api/response.go +++ /dev/null @@ -1,5 +0,0 @@ -package api - -type Response struct { - Version int `json:"version"` -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/api/strategy.go b/vendor/github.com/Unleash/unleash-client-go/v4/api/strategy.go deleted file mode 100644 index d30b673d0..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/api/strategy.go +++ /dev/null @@ -1,43 +0,0 @@ -package api - -type StrategyResponse struct { - Response - Strategies []StrategyDescription `json:"strategies"` -} - -type Strategy struct { - // Id is the name of the strategy. - Id int `json:"id"` - - // Name is the name of the strategy. - Name string `json:"name"` - - // Constraints is the constraints of the strategy. - Constraints []Constraint `json:"constraints"` - - // Parameters is the parameters of the strategy. - Parameters ParameterMap `json:"parameters"` - - Segments []int `json:"segments"` - - // Variants for a strategy - Variants []VariantInternal `json:"variants"` -} - -type ParameterDescription struct { - Name string `json:"name"` - Type string `json:"type"` - Description string `json:"description"` - Required bool `json:"required"` -} - -type StrategyDescription struct { - Name string `json:"name"` - Description string `json:"description"` - Parameters []ParameterDescription `json:"parameters"` -} - -type StrategyResult struct { - Enabled bool - Variant *Variant -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/api/variant.go b/vendor/github.com/Unleash/unleash-client-go/v4/api/variant.go deleted file mode 100644 index c92af767e..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/api/variant.go +++ /dev/null @@ -1,98 +0,0 @@ -package api - -import "github.com/Unleash/unleash-client-go/v4/context" - -var DISABLED_VARIANT = &Variant{ - Name: "disabled", - Enabled: false, - FeatureEnabled: false, -} - -type Payload struct { - // Type is the type of the payload - Type string `json:"type"` - // Value is the value of the payload type - Value string `json:"value"` -} - -type Override struct { - // ContextName is the value of attribute context name - ContextName string `json:"contextName"` - // Values is the value of attribute values - Values []string `json:"values"` -} - -type Variant struct { - // Name is the value of the variant name. - Name string `json:"name"` - // Payload is the value of the variant payload - Payload Payload `json:"payload"` - // Enabled indicates whether the variant is enabled. This is only false when - // it's a default variant. - Enabled bool `json:"enabled"` - // FeatureEnabled indicates whether the Feature for this variant is enabled. - FeatureEnabled bool `json:"featureEnabled"` -} - -type VariantInternal struct { - Variant - // Weight is the traffic ratio for the request - Weight int `json:"weight"` - // WeightType can be fixed or variable - WeightType string `json:"weightType"` - Stickiness string `json:"stickiness"` - // Override is used to get a variant accoording to the Unleash context field - Overrides []Override `json:"overrides"` -} - -type VariantCollection struct { - // groupId to evaluate the variant - GroupId string - // variants for a feature toggle or feature strategy - Variants []VariantInternal -} - -func (o Override) getIdentifier(ctx *context.Context) string { - var value string - switch o.ContextName { - case "userId": - value = ctx.UserId - case "sessionId": - value = ctx.SessionId - case "remoteAddress": - value = ctx.RemoteAddress - case "environment": - value = ctx.Environment - case "appName": - value = ctx.AppName - default: - if len(ctx.Properties) > 0 { - for k, v := range ctx.Properties { - if k == o.ContextName { - value = v - } - } - } - } - return value -} - -func (o Override) matchValue(ctx *context.Context) bool { - if len(o.Values) == 0 { - return false - } - for _, value := range o.Values { - if value == o.getIdentifier(ctx) { - return true - } - } - return false -} - -// Get default variant if feature is not found or if the feature is disabled. -// -// Rather than checking against this particular variant you should be checking -// the returned variant's Enabled and FeatureEnabled properties. -func GetDefaultVariant() *Variant { - return DISABLED_VARIANT -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/bootstrap_storage.go b/vendor/github.com/Unleash/unleash-client-go/v4/bootstrap_storage.go deleted file mode 100644 index c04fb59b2..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/bootstrap_storage.go +++ /dev/null @@ -1,55 +0,0 @@ -package unleash - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/Unleash/unleash-client-go/v4/api" -) - -type BootstrapStorage struct { - backingStore DefaultStorage - Reader io.Reader -} - -func (bs *BootstrapStorage) Load() error { - if len(bs.backingStore.data) > 0 || bs.Reader == nil { - return nil - } - - dec := json.NewDecoder(bs.Reader) - clientFeatures := api.FeatureResponse{} - if err := dec.Decode(&clientFeatures); err != nil { - return err - } - - bs.backingStore.data = clientFeatures.FeatureMap() - return nil -} - -func (bs *BootstrapStorage) Init(backupPath string, appName string) { - bs.backingStore.Init(backupPath, appName) - err := bs.Load() - - if err != nil { - fmt.Printf("Could not load bootstrap storage, because: %s", err.Error()) - return - } -} - -func (bs *BootstrapStorage) Reset(data map[string]interface{}, persist bool) error { - return bs.backingStore.Reset(data, persist) -} - -func (bs *BootstrapStorage) Persist() error { - return bs.backingStore.Persist() -} - -func (bs *BootstrapStorage) Get(key string) (interface{}, bool) { - return bs.backingStore.Get(key) -} - -func (bs *BootstrapStorage) List() []interface{} { - return bs.backingStore.List() -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/client.go b/vendor/github.com/Unleash/unleash-client-go/v4/client.go deleted file mode 100644 index 33f09e07f..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/client.go +++ /dev/null @@ -1,549 +0,0 @@ -package unleash - -import ( - "fmt" - - "net/url" - "strings" - "time" - - "github.com/Unleash/unleash-client-go/v4/api" - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/internal/constraints" - s "github.com/Unleash/unleash-client-go/v4/internal/strategies" - "github.com/Unleash/unleash-client-go/v4/strategy" -) - -const ( - deprecatedSuffix = "/features" - clientName = "unleash-client-go" - clientVersion = "4.1.4" - specVersion = "4.3.1" -) - -var defaultStrategies = []strategy.Strategy{ - *s.NewDefaultStrategy(), - *s.NewApplicationHostnameStrategy(), - *s.NewGradualRolloutRandomStrategy(), - *s.NewGradualRolloutSessionId(), - *s.NewGradualRolloutUserId(), - *s.NewRemoteAddressStrategy(), - *s.NewUserWithIdStrategy(), - *s.NewFlexibleRolloutStrategy(), -} - -// disabledVariantFeatureEnabled is similar to api.DISABLED_VARIANT but we want -// to discourage public usage so it's internal until there's a need to expose it. -var disabledVariantFeatureEnabled = &api.Variant{ - Name: "disabled", - Enabled: false, - FeatureEnabled: true, -} - -// Client is a structure representing an API client of an Unleash server. -type Client struct { - errorChannels - options configOption - repository *repository - metrics *metrics - strategies []strategy.Strategy - errorListener ErrorListener - metricsListener MetricListener - repositoryListener RepositoryListener - ready chan bool - onReady chan struct{} - close chan struct{} - closed chan struct{} - count chan metric - sent chan MetricsData - registered chan ClientData - staticContext *context.Context -} - -type errorChannels struct { - errors chan error - warnings chan error -} - -func (ec errorChannels) warn(err error) { - ec.warnings <- err -} - -func (ec errorChannels) err(err error) { - ec.errors <- err -} - -type repositoryChannels struct { - errorChannels - ready chan bool -} - -type metricsChannels struct { - errorChannels - count chan metric - sent chan MetricsData - registered chan ClientData -} - -// NewClient creates a new client instance with the given options. -func NewClient(options ...ConfigOption) (*Client, error) { - - errChannels := errorChannels{ - errors: make(chan error, 3), - warnings: make(chan error, 3), - } - - uc := &Client{ - options: configOption{ - environment: "default", - refreshInterval: 15 * time.Second, - metricsInterval: 60 * time.Second, - disableMetrics: false, - backupPath: getTmpDirPath(), - strategies: []strategy.Strategy{}, - }, - errorChannels: errChannels, - onReady: make(chan struct{}), - ready: make(chan bool, 1), - count: make(chan metric), - sent: make(chan MetricsData), - registered: make(chan ClientData, 1), - close: make(chan struct{}), - closed: make(chan struct{}), - } - - for _, opt := range options { - opt(&uc.options) - } - - uc.staticContext = &context.Context{ - Environment: uc.options.environment, - AppName: uc.options.appName, - } - - if uc.options.listener == nil { - uc.options.listener = &NoopListener{} - } - - if eListener, ok := uc.options.listener.(ErrorListener); ok { - uc.errorListener = eListener - } - if rListener, ok := uc.options.listener.(RepositoryListener); ok { - uc.repositoryListener = rListener - } - if mListener, ok := uc.options.listener.(MetricListener); ok { - uc.metricsListener = mListener - } - defer func() { - go uc.sync() - }() - - if uc.options.url == "" { - return nil, fmt.Errorf("unleash server URL missing") - } - - if strings.HasSuffix(uc.options.url, deprecatedSuffix) { - uc.warn(fmt.Errorf("unleash server URL %s should no longer link directly to /features", uc.options.url)) - uc.options.url = strings.TrimSuffix(uc.options.url, deprecatedSuffix) - } - - if !strings.HasSuffix(uc.options.url, "/") { - uc.options.url += "/" - } - - parsedUrl, err := url.Parse(uc.options.url) - if err != nil { - return nil, err - } - - if uc.options.appName == "" { - return nil, fmt.Errorf("unleash client appName missing") - } - - if uc.options.instanceId == "" { - uc.options.instanceId = generateInstanceId() - } - - uc.repository = newRepository( - repositoryOptions{ - backupPath: uc.options.backupPath, - url: *parsedUrl, - appName: uc.options.appName, - projectName: uc.options.projectName, - instanceId: uc.options.instanceId, - refreshInterval: uc.options.refreshInterval, - storage: uc.options.storage, - httpClient: uc.options.httpClient, - customHeaders: uc.options.customHeaders, - }, - repositoryChannels{ - errorChannels: errChannels, - ready: uc.ready, - }, - ) - - uc.strategies = append(defaultStrategies, uc.options.strategies...) - - strategyNames := make([]string, len(uc.strategies)) - for i, strategy := range uc.strategies { - strategyNames[i] = strategy.Name() - } - - uc.metrics = newMetrics( - metricsOptions{ - appName: uc.options.appName, - instanceId: uc.options.instanceId, - strategies: strategyNames, - metricsInterval: uc.options.metricsInterval, - url: *parsedUrl, - httpClient: uc.options.httpClient, - customHeaders: uc.options.customHeaders, - disableMetrics: uc.options.disableMetrics, - }, - metricsChannels{ - errorChannels: errChannels, - count: uc.count, - sent: uc.sent, - registered: uc.registered, - }, - ) - - return uc, nil -} - -func (uc *Client) sync() { - for { - select { - case e := <-uc.errors: - if uc.errorListener != nil { - uc.errorListener.OnError(e) - } - case w := <-uc.warnings: - if uc.errorListener != nil { - uc.errorListener.OnWarning(w) - } - case <-uc.ready: - close(uc.onReady) - if uc.repositoryListener != nil { - uc.repositoryListener.OnReady() - } - case m := <-uc.count: - if uc.metricsListener != nil { - uc.metricsListener.OnCount(m.Name, m.Enabled) - } - case md := <-uc.sent: - if uc.metricsListener != nil { - uc.metricsListener.OnSent(md) - } - case cd := <-uc.registered: - if uc.metricsListener != nil { - uc.metricsListener.OnRegistered(cd) - } - case <-uc.close: - close(uc.closed) - return - } - } -} - -// IsEnabled queries whether the specified feature is enabled or not. -// -// It is safe to call this method from multiple goroutines concurrently. -func (uc *Client) IsEnabled(feature string, options ...FeatureOption) (enabled bool) { - defer func() { - uc.metrics.count(feature, enabled) - }() - - result, _ := uc.isEnabled(feature, options...) - return result.Enabled -} - -// isEnabled abstracts away the details of checking if a toggle is turned on or off -// without metrics -func (uc *Client) isEnabled(feature string, options ...FeatureOption) (api.StrategyResult, *api.Feature) { - var opts featureOption - for _, o := range options { - o(&opts) - } - - f := resolveToggle(uc, opts, feature) - - ctx := uc.staticContext - if opts.ctx != nil { - ctx = ctx.Override(*opts.ctx) - } - - if f == nil { - return handleFallback(opts, feature, ctx), nil - } - - if f.Dependencies != nil && len(*f.Dependencies) > 0 { - dependenciesSatisfied := uc.isParentDependencySatisfied(f, *ctx) - - if !dependenciesSatisfied { - return api.StrategyResult{ - Enabled: false, - }, f - } - } - - if !f.Enabled { - return api.StrategyResult{ - Enabled: false, - }, f - } - - if len(f.Strategies) == 0 { - return api.StrategyResult{ - Enabled: f.Enabled, - }, f - } - - for _, s := range f.Strategies { - foundStrategy := uc.getStrategy(s.Name) - if foundStrategy == nil { - // TODO: warnOnce missingStrategy - continue - } - - segmentConstraints, err := uc.repository.resolveSegmentConstraints(s) - - if err != nil { - uc.errors <- err - return api.StrategyResult{ - Enabled: false, - }, f - } - - allConstraints := make([]api.Constraint, 0) - allConstraints = append(allConstraints, segmentConstraints...) - allConstraints = append(allConstraints, s.Constraints...) - - if ok, err := constraints.Check(ctx, allConstraints); err != nil { - uc.errors <- err - } else if ok && foundStrategy.IsEnabled(s.Parameters, ctx) { - if s.Variants != nil && len(s.Variants) > 0 { - groupIdValue := s.Parameters[strategy.ParamGroupId] - groupId, ok := groupIdValue.(string) - if !ok { - return api.StrategyResult{ - Enabled: false, - }, f - } - - return api.StrategyResult{ - Enabled: true, - Variant: api.VariantCollection{ - GroupId: groupId, - Variants: s.Variants, - }.GetVariant(ctx), - }, f - } else { - return api.StrategyResult{ - Enabled: true, - }, f - } - } - } - - return api.StrategyResult{ - Enabled: false, - }, f -} - -func (uc *Client) isParentDependencySatisfied(feature *api.Feature, context context.Context) bool { - warnOnce := &WarnOnce{} - - dependenciesSatisfied := func(parent api.Dependency) bool { - parentToggle := uc.repository.getToggle(parent.Feature) - - if parentToggle == nil { - warnOnce.Warn("the parent toggle was not found in the cache, the evaluation of this dependency will always be false") - return false - } - - if parentToggle.Dependencies != nil && len(*parentToggle.Dependencies) > 0 { - return false - } - - enabledResult, _ := uc.isEnabled(parent.Feature, WithContext(context)) - // According to the schema, if the enabled property is absent we assume it's true. - if parent.Enabled == nil || *parent.Enabled { - if parent.Variants != nil && len(*parent.Variants) > 0 && enabledResult.Variant != nil { - return enabledResult.Enabled && contains(*parent.Variants, enabledResult.Variant.Name) - } - return enabledResult.Enabled - } - - return !enabledResult.Enabled - } - - allDependenciesSatisfied := every(*feature.Dependencies, func(parent interface{}) bool { - return dependenciesSatisfied(parent.(api.Dependency)) - }) - - return allDependenciesSatisfied -} - -// GetVariant queries a variant as the specified feature is enabled. -// -// It is safe to call this method from multiple goroutines concurrently. -func (uc *Client) GetVariant(feature string, options ...VariantOption) *api.Variant { - variant := uc.getVariantWithoutMetrics(feature, options...) - defer func() { - uc.metrics.countVariants(feature, variant.FeatureEnabled, variant.Name) - }() - return variant -} - -// getVariantWithoutMetrics abstracts away the logic for resolving a variant without metrics -func (uc *Client) getVariantWithoutMetrics(feature string, options ...VariantOption) *api.Variant { - defaultVariant := api.GetDefaultVariant() - var opts variantOption - for _, o := range options { - o(&opts) - } - - ctx := uc.staticContext - if opts.ctx != nil { - ctx = ctx.Override(*opts.ctx) - } - - var strategyResult api.StrategyResult - var f *api.Feature - if opts.resolver != nil { - strategyResult, f = uc.isEnabled(feature, WithContext(*ctx), WithResolver(opts.resolver)) - } else { - strategyResult, f = uc.isEnabled(feature, WithContext(*ctx)) - } - - getFallbackVariant := func(featureEnabled bool) *api.Variant { - if opts.variantFallbackFunc != nil { - return opts.variantFallbackFunc(feature, ctx) - } else if opts.variantFallback != nil { - return opts.variantFallback - } - - if featureEnabled { - return disabledVariantFeatureEnabled - } - return defaultVariant - } - - if !strategyResult.Enabled { - return getFallbackVariant(false) - } - - if f == nil || !f.Enabled { - return getFallbackVariant(false) - } - - if strategyResult.Variant != nil { - return strategyResult.Variant - } - - if len(f.Variants) == 0 { - return getFallbackVariant(true) - } - - return api.VariantCollection{ - GroupId: f.Name, - Variants: f.Variants, - }.GetVariant(ctx) -} - -// Close stops the client from syncing data from the server. -func (uc *Client) Close() error { - uc.repository.Close() - uc.metrics.Close() - if uc.options.listener != nil { - // Wait for sync to exit. - close(uc.close) - <-uc.closed - } - return nil -} - -// Errors returns the error channel for the client. -func (uc *Client) Errors() <-chan error { - return uc.errors -} - -// Warnings returns the warnings channel for the client. -func (uc *Client) Warnings() <-chan error { - return uc.warnings -} - -// Ready returns the ready channel for the client. A value will be available on -// the channel when the feature toggles have been loaded from the Unleash -// server. -func (uc *Client) Ready() <-chan bool { - return uc.ready -} - -// Count returns the count channel which gives an update when a toggle has been queried. -func (uc *Client) Count() <-chan metric { - return uc.count -} - -// Registered returns the registered signal indicating that the client has successfully connected to the -// metrics service. -func (uc *Client) Registered() <-chan ClientData { - return uc.registered -} - -// Sent returns the sent channel which receives data whenever the client has successfully sent metrics to -// the metrics service. -func (uc *Client) Sent() <-chan MetricsData { - return uc.sent -} - -func (uc *Client) getStrategy(name string) strategy.Strategy { - for _, strategy := range uc.strategies { - if strategy.Name() == name { - return strategy - } - } - return nil -} - -// WaitForReady will block until the client has loaded the feature toggles from -// the Unleash server. It will return immediately if the toggles have already -// been loaded, -// -// It is safe to call this method from multiple goroutines concurrently. -func (uc *Client) WaitForReady() { - <-uc.onReady -} - -// ListFeatures returns all available features toggles. -func (uc *Client) ListFeatures() []api.Feature { - return uc.repository.list() -} - -func resolveToggle(unleashClient *Client, opts featureOption, featureName string) *api.Feature { - var feature *api.Feature - if opts.resolver != nil { - feature = opts.resolver(featureName) - } else { - feature = unleashClient.repository.getToggle(featureName) - } - - return feature -} - -func handleFallback(opts featureOption, featureName string, ctx *context.Context) api.StrategyResult { - if opts.fallbackFunc != nil { - return api.StrategyResult{ - Enabled: opts.fallbackFunc(featureName, ctx), - } - } else if opts.fallback != nil { - return api.StrategyResult{ - Enabled: *opts.fallback, - } - } - - return api.StrategyResult{ - Enabled: false, - } -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/config.go b/vendor/github.com/Unleash/unleash-client-go/v4/config.go deleted file mode 100644 index 8fb1a40e7..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/config.go +++ /dev/null @@ -1,269 +0,0 @@ -package unleash - -import ( - "net/http" - "net/url" - "time" - - "github.com/Unleash/unleash-client-go/v4/api" - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/strategy" -) - -type configOption struct { - appName string - environment string - instanceId string - url string - projectName string - refreshInterval time.Duration - metricsInterval time.Duration - disableMetrics bool - backupPath string - strategies []strategy.Strategy - listener interface{} - storage Storage - httpClient *http.Client - customHeaders http.Header -} - -// ConfigOption represents a option for configuring the client. -type ConfigOption func(*configOption) - -// WithListener allows users to register a type that implements one or more of -// the listener interfaces. If no listener is registered then the user is responsible -// for draining the various channels on the client. Failure to do so will stop the client -// from working as the worker routines will be blocked. -func WithListener(listener interface{}) ConfigOption { - return func(o *configOption) { - o.listener = listener - } -} - -// WithAppName specifies the name of the application. -func WithAppName(appName string) ConfigOption { - return func(o *configOption) { - o.appName = appName - } -} - -// WithEnvironment specifies the environment -func WithEnvironment(env string) ConfigOption { - return func(o *configOption) { - o.environment = env - } -} - -// WithInstanceId specifies the instance identifier of the current instance. If not provided, -// one will be generated based on various parameters such as current user and hostname. -func WithInstanceId(instanceId string) ConfigOption { - return func(o *configOption) { - o.instanceId = instanceId - } -} - -// WithUrl specifies the url of the unleash server the user is connecting to. -func WithUrl(url string) ConfigOption { - return func(o *configOption) { - o.url = url - } -} - -// WithRefreshInterval specifies the time interval with which the client should sync the -// feature toggles from the unleash server (default 15s). -func WithRefreshInterval(refreshInterval time.Duration) ConfigOption { - return func(o *configOption) { - o.refreshInterval = refreshInterval - } -} - -// WithMetricsInterval specifies the time interval with which the client should upload -// the metrics data to the unleash server (default 60s). -func WithMetricsInterval(metricsInterval time.Duration) ConfigOption { - return func(o *configOption) { - o.metricsInterval = metricsInterval - } -} - -// WithDisableMetrics specifies that the client should not log metrics to the unleash server. -func WithDisableMetrics(disableMetrics bool) ConfigOption { - return func(o *configOption) { - o.disableMetrics = disableMetrics - } -} - -// WithBackupPath specifies the path that is passed to the storage implementation for storing -// the feature toggles locally. -func WithBackupPath(backupPath string) ConfigOption { - return func(o *configOption) { - o.backupPath = backupPath - } -} - -// WithStrategies specifies which strategies (in addition to the defaults) should be used by the -// client. -func WithStrategies(strategies ...strategy.Strategy) ConfigOption { - return func(o *configOption) { - o.strategies = strategies - } -} - -// WithStorage specifies which storage implementation the repository should use for storing feature -// toggles. -func WithStorage(storage Storage) ConfigOption { - return func(o *configOption) { - o.storage = storage - } -} - -// WithHttpClient specifies which HttpClient the client should use for making requests to the server. -func WithHttpClient(client *http.Client) ConfigOption { - return func(o *configOption) { - o.httpClient = client - } -} - -// WithCustomHeaders specifies any custom headers that should be sent along with requests to the -// server. -func WithCustomHeaders(headers http.Header) ConfigOption { - return func(o *configOption) { - o.customHeaders = headers - } -} - -// WithProjectName defines a projectName on the config object and is used to -// filter toggles by project name. -func WithProjectName(projectName string) ConfigOption { - return func(o *configOption) { - o.projectName = projectName - } -} - -// FeatureResolver represents a function to be called to resolve the feature instead of using the repository -type FeatureResolver func(feature string) *api.Feature - -// WithResolver allows you to bypass the repository when resolving a feature name to its actual instance. -func WithResolver(resolver FeatureResolver) FeatureOption { - return func(opts *featureOption) { - opts.resolver = resolver - } -} - -// FallbackFunc represents a function to be called if the feature is not found. -type FallbackFunc func(feature string, ctx *context.Context) bool - -type featureOption struct { - fallback *bool - fallbackFunc FallbackFunc - ctx *context.Context - resolver FeatureResolver -} - -// FeatureOption provides options for querying if a feature is enabled or not. -type FeatureOption func(*featureOption) - -// WithFallback specifies what the value should be if the feature toggle is not found on the -// unleash service. -func WithFallback(fallback bool) FeatureOption { - return func(opts *featureOption) { - opts.fallback = &fallback - } -} - -// WithFallbackFunc specifies a fallback function to evaluate a feature -// toggle in the event that it is not found on the service. -func WithFallbackFunc(fallback FallbackFunc) FeatureOption { - return func(opts *featureOption) { - opts.fallbackFunc = fallback - } -} - -// WithContext allows the user to provide a context that will be passed into the active strategy -// for determining if a specified feature should be enabled or not. -func WithContext(ctx context.Context) FeatureOption { - return func(opts *featureOption) { - opts.ctx = &ctx - } -} - -// WithVariantContext specifies a context for the GetVariant -// call -func WithVariantContext(ctx context.Context) VariantOption { - return func(opts *variantOption) { - opts.ctx = &ctx - } -} - -// WithVariantResolver allows you to bypass the repository when resolving a feature name to its actual instance. -func WithVariantResolver(resolver FeatureResolver) VariantOption { - return func(opts *variantOption) { - opts.resolver = resolver - } -} - -// VariantFallbackFunc represents a function to be called if the variant is not found. -type VariantFallbackFunc func(feature string, ctx *context.Context) *api.Variant - -type variantOption struct { - variantFallback *api.Variant - variantFallbackFunc VariantFallbackFunc - ctx *context.Context - resolver FeatureResolver -} - -// VariantOption provides options for querying if a variant is found or not. -type VariantOption func(*variantOption) - -// WithVariantFallback specifies what the value should be if the -// variant is not found on the unleash service. This could be because -// the feature doesn't exist, because it is disabled, or because it -// has no variants. -// -// If you specify a fallback variant, note that its `FeatureEnabled` -// field will be set to whatever you pass in or `false` by default. In -// other words, it will not reflect the feature's actual enabled -// state. -func WithVariantFallback(variantFallback *api.Variant) VariantOption { - return func(opts *variantOption) { - opts.variantFallback = variantFallback - } -} - -// WithVariantFallbackFunc specifies a fallback function to evaluate -// to a variant when a variant is not found for a feature. This could -// be because the feature doesn't exist, because it is disabled, or -// because it has no variants. -// -// If you specify a fallback variant, note that its `FeatureEnabled` -// field will be set to whatever you pass in or `false` by default. In -// other words, it will not reflect the feature's actual enabled -// state. -func WithVariantFallbackFunc(variantFallbackFunc VariantFallbackFunc) VariantOption { - return func(opts *variantOption) { - opts.variantFallbackFunc = variantFallbackFunc - } -} - -type repositoryOptions struct { - appName string - instanceId string - projectName string - url url.URL - backupPath string - refreshInterval time.Duration - storage Storage - httpClient *http.Client - customHeaders http.Header -} - -type metricsOptions struct { - appName string - instanceId string - url url.URL - strategies []string - metricsInterval time.Duration - disableMetrics bool - httpClient *http.Client - customHeaders http.Header - started *time.Time -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/context/context.go b/vendor/github.com/Unleash/unleash-client-go/v4/context/context.go deleted file mode 100644 index b2fc533de..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/context/context.go +++ /dev/null @@ -1,75 +0,0 @@ -package context - -// Context specifies the context in which a feature toggle should be considered -// to be enabled or not. -type Context struct { - // UserId is the the id of the user. - UserId string - - // SessionId is the id of the session. - SessionId string - - // RemoteAddress is the IP address of the machine. - RemoteAddress string - - // Environment is the environment this application is running in. - Environment string - - // AppName is the application name. - AppName string - - // CurrentTime is used for date constraints. Defaults to time.Now if not set. - CurrentTime string - - // Properties is a map of additional properties. - Properties map[string]string -} - -// Override will take all non-empty values in 'src' and replace the -// corresponding values in this context with those. -func (ctx Context) Override(src Context) *Context { - if src.UserId != "" { - ctx.UserId = src.UserId - } - if src.SessionId != "" { - ctx.SessionId = src.SessionId - } - if src.RemoteAddress != "" { - ctx.RemoteAddress = src.RemoteAddress - } - if src.Environment != "" { - ctx.Environment = src.Environment - } - if src.AppName != "" { - ctx.AppName = src.AppName - } - if src.CurrentTime != "" { - ctx.CurrentTime = src.CurrentTime - } - if src.Properties != nil { - ctx.Properties = src.Properties - } - - return &ctx -} - -// Field allows accessing the fields of the context by name. The typed fields are searched -// first and if nothing matches, it will search the properties. -func (ctx Context) Field(name string) string { - switch name { - case "userId": - return ctx.UserId - case "sessionId": - return ctx.SessionId - case "remoteAddress": - return ctx.RemoteAddress - case "environment": - return ctx.Environment - case "appName": - return ctx.AppName - case "currentTime": - return ctx.CurrentTime - default: - return ctx.Properties[name] - } -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/debuglistener.go b/vendor/github.com/Unleash/unleash-client-go/v4/debuglistener.go deleted file mode 100644 index 79526a906..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/debuglistener.go +++ /dev/null @@ -1,40 +0,0 @@ -package unleash - -import ( - "fmt" -) - -// DebugListener is an implementation of all of the listener interfaces that simply logs -// debug info to stdout. It is meant for debugging purposes and an example of implementing -// the listener interfaces. -type DebugListener struct{} - -// OnError prints out errors. -func (l DebugListener) OnError(err error) { - fmt.Printf("ERROR: %s\n", err.Error()) -} - -// OnWarning prints out warning. -func (l DebugListener) OnWarning(warning error) { - fmt.Printf("WARNING: %s\n", warning.Error()) -} - -// OnReady prints to the console when the repository is ready. -func (l DebugListener) OnReady() { - fmt.Printf("READY\n") -} - -// OnCount prints to the console when the feature is queried. -func (l DebugListener) OnCount(name string, enabled bool) { - fmt.Printf("Counted '%s' as enabled? %v\n", name, enabled) -} - -// OnSent prints to the console when the server has uploaded metrics. -func (l DebugListener) OnSent(payload MetricsData) { - fmt.Printf("Sent: %+v\n", payload) -} - -// OnRegistered prints to the console when the client has registered. -func (l DebugListener) OnRegistered(payload ClientData) { - fmt.Printf("Registered: %+v\n", payload) -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/demo_app_toggles.json b/vendor/github.com/Unleash/unleash-client-go/v4/demo_app_toggles.json deleted file mode 100644 index 4223e483c..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/demo_app_toggles.json +++ /dev/null @@ -1,4509 +0,0 @@ -{ - "version": 1, - "features": [ - { - "name": "083db41c-c6c8-427b-815b-f735c3c6da60", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 49, - "stickiness": "default", - "groupId": "083db41c-c6c8-427b-815b-f735c3c6da60" - }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 50, - "stickiness": "default", - "groupId": "083db41c-6c8-427b-815b-f735c3c6da60" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "asdfasdf", - "weight": 500, - "weightType": "variable", - "overrides": [], - "stickiness": "default" - }, - { - "name": "agasdgaegagse", - "weight": 500, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "21", - "type": "permission", - "enabled": true, - "stale": true, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "asd,asda,1223" }, - "constraints": [] - }, - { - "name": "as", - "parameters": { "asd": "123", "asdasd": 45, "isProd": "true" }, - "constraints": [] - } - ], - "variants": [ - { - "name": "v1", - "weight": 1000, - "weightType": "variable", - "overrides": [], - "stickiness": "default" - } - ] - }, - { - "name": "2afc3854-6157-4abf-a87b-e59510bc96e9", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "OPR_CODE", - "parameters": { "OPR_CODE": "" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "A123", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "CustomId", - "parameters": { "CustomerId": "a,b,c,e" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "aaa", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "foobar", - "parameters": { "bar_p": "100", "ENVIRONMENT": "DEV" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "aaaasdw", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "aasas", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "abc", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "" } - } - ], - "variants": [] - }, - { - "name": "abca", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "" } } - ], - "variants": [] - }, - { - "name": "accounts.reset-password.random.rollout", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "ActivityLog", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "", - "QA": "", - "Test": "", - "Training": "", - "Prod": "" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "type_1", - "weight": 500, - "payload": { "type": "string", "value": "opt_1" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - }, - { - "name": "type_2", - "weight": 500, - "payload": { "type": "string", "value": "opt_2" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "ActivityLogTesting", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "gradualRolloutSessionId", - "parameters": { - "percentage": 50, - "groupId": "ActivityLogTesting" - }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 75, - "stickiness": "default", - "groupId": "ActivityLogTesting" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "a-demo", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "82", - "stickiness": "default", - "groupId": "a-demo" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "adsda", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "50", - "stickiness": "random", - "groupId": "adsda" - }, - "constraints": [] - }, - { - "name": "forClient", - "parameters": { "clientName": "Android,IOS" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "aerronpro", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "agasdfasdf", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "34", - "stickiness": "default", - "groupId": "agasdfasdf" - }, - "constraints": [] - }, - { "name": "default", "parameters": {}, "constraints": [] }, - { - "name": "foobar", - "parameters": { "ENVIRONMENT": "" }, - "constraints": [] - }, - { "name": "default", "parameters": {}, "constraints": [] }, - { - "name": "userWithId", - "parameters": { "userIds": "" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "alloe", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Aname", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "de" }, - "constraints": [] - }, - { - "name": "userWithId", - "parameters": { "userIds": "de_23456,fr_5667789" }, - "constraints": [] - } - ], - "variants": [ - { - "name": "v1", - "weight": 1000, - "payload": { "type": "string", "value": "test" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "A-new.one", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "", - "Test": "", - "Training": "", - "Prod": "" - } - }, - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [ - { - "name": "foobar", - "weight": 1000, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "another-toggle", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "anotta-toggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "aoeu", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "app", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "46", - "stickiness": "default", - "groupId": "app" - } - } - ], - "variants": [] - }, - { - "name": "app.main", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "laci" } } - ], - "variants": [] - }, - { - "name": "app.ToggleX", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Aruba-Switch", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "asasas", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "test1", - "parameters": { "codes": "sas,{sas: \"\"sa sasasas\" }" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "ASASASAS", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "OPR_CODE", - "parameters": { "OPR_CODE": "CUST" }, - "constraints": [] - }, - { - "name": "userWithId", - "parameters": { "userIds": "" }, - "constraints": [] - }, - { - "name": "userWithId", - "parameters": { "userIds": "123,4,5" }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "41", - "stickiness": "default", - "groupId": "ASASASAS" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "v1", - "weight": 1000, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "asd", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "asd" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "asd22", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "50", - "stickiness": "default", - "groupId": "asd22" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "asd22dsf", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "asd2asd", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": 33, - "stickiness": "default", - "groupId": "asd2asd" - }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 46, - "stickiness": "default", - "groupId": "asd2asd" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "asdasd", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "asdasd" - } - } - ], - "variants": [] - }, - { - "name": "asdasd2", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "asdf", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "asdfasdfasdf", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "asdqddq", - "type": "permission", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "rollout_schemas", - "parameters": { "schemas": "let" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "Asdqwe1we", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "aaaa", - "weight": 1000, - "payload": { "type": "json", "value": "{ a: 1 }" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "asmallname", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "version", "parameters": { "version code": "15" } } - ], - "variants": [ - { - "name": "apilevel", - "weight": 1000, - "payload": { "type": "string", "value": "100" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "auto-grading", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "50", - "stickiness": "default", - "groupId": "auto-grading" - }, - "constraints": [] - }, - { - "name": "userWithId", - "parameters": { "userIds": "123,1234,4441" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "AwesomeFeature", - "type": "permission", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [] - }, - { - "name": "AwesomeFF", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "47", - "stickiness": "userId", - "groupId": "AwesomeFF" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "bbbbb", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "hhhhh", "parameters": { "8": "58" } }], - "variants": [] - }, - { - "name": "bbbbbbb", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "bccnj", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "bfg_feature", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userParam", "parameters": { "userType": "basic" } } - ], - "variants": [] - }, - { - "name": "bla", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "demo", "parameters": { "demoGroup": "" } } - ], - "variants": [] - }, - { - "name": "bnmbmnb", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": 75, - "stickiness": "default", - "groupId": "" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "bookable_authorized", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "20" } } - ], - "variants": [] - }, - { - "name": "Booyeah-Who-Is-The-King", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "v1", - "weight": 1000, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "by-users", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "111,234" } } - ], - "variants": [] - }, - { - "name": "c79422b2-5c8e-407a-a389-77bdb5b6ad0a", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "cf", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "CID-SFDC", - "type": "operational", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "cid-strategy", - "parameters": { "solution": "VCF,SYN" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "CoffeeShop", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "covid-19", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "create", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "cross_featrure", - "type": "operational", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "dark-theme", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "1,2,3" }, - "constraints": [] - }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "" }, - "constraints": [] - }, - { "name": "remoteAddress", "parameters": { "IPs": "" } } - ], - "variants": [] - }, - { - "name": "dashboard_enabled", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "DateExample", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Demo", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "52", - "stickiness": "default", - "groupId": "Demo" - }, - "constraints": [] - }, - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [ - { - "name": "small", - "weight": 500, - "weightType": "variable", - "payload": { "type": "string", "value": "35" }, - "overrides": [], - "stickiness": "default" - }, - { - "name": "medium", - "weight": 500, - "payload": { "type": "string", "value": "55" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "Demo123", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Demo22", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Demo33", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "24", - "stickiness": "default", - "groupId": "Demo33" - }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "25", - "stickiness": "default", - "groupId": "Demo33" - }, - "constraints": [] - }, - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [ - { - "name": "dfsd", - "weight": 500, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - }, - { - "name": "asdasd", - "weight": 500, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "Demo43", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": 56, - "stickiness": "default", - "groupId": "" - }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 49, - "stickiness": "default", - "groupId": "Demo43" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "Demo44", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "de_sro" }, - "constraints": [] - }, - { "name": "default", "parameters": {}, "constraints": [] }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "47", - "stickiness": "default", - "groupId": "Demo44" - }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "50", - "stickiness": "default", - "groupId": "Demo44" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "Demo.Slack", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Demossss", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "test1", - "parameters": { "services": "", "solutions": "" } - } - ], - "variants": [] - }, - { - "name": "Devtools", - "type": "permission", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "dfgfdg", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "" }, - "constraints": [] - }, - { - "name": "remoteAddress", - "parameters": { "IPs": "tyhtyh" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "dghjm", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "dinesh-t", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "1234" } } - ], - "variants": [] - }, - { - "name": "Doemaariets", - "type": "kill-switch", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Domain", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "true", - "Test": "", - "Training": "", - "Prod": "" - } - }, - { - "name": "customerWithId", - "parameters": { "CustomerId": "123,321,123321" } - } - ], - "variants": [] - }, - { - "name": "eee", - "type": "permission", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "TestGroup", - "parameters": { "Group": "kjherkjqwehrkew" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "eeee", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "example-experiment", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "domain.com" } - } - ], - "variants": [] - }, - { - "name": "ExampleFeature", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "nishtha.kakkar.8@gmail.com" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "Experiment", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "forClient", - "parameters": { "clientName": "bob,yay" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "Experiment-", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Experiment-Test", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "blue", - "weight": 800, - "weightType": "variable", - "payload": { "type": "string", "value": "blueblue" }, - "overrides": [] - }, - { - "name": "red", - "weight": 200, - "weightType": "fix", - "overrides": [] - } - ] - }, - { - "name": "experiment-toggle", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "123456" }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "userId", - "groupId": "experiment-toggle" - } - } - ], - "variants": [] - }, - { - "name": "fadfafaf", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Feature12", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [] - }, - { - "name": "feature1.subfeature1", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "var1", - "weight": 1000, - "payload": { "type": "json", "value": "test" }, - "overrides": [{ "contextName": "userId", "values": ["test2"] }], - "weightType": "variable" - } - ] - }, - { - "name": "feature-2", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "", - "Test": "", - "Training": "", - "Prod": "" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "featureFlagYeah", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "FeatureToggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "featureX", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "23", - "stickiness": "default", - "groupId": "featureX" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "fetch-2-feature", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "fetch-2-feature-2", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "fetch-toggle", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "fe-test-1", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "FF", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "fff", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "remoteAddress", "parameters": { "IPs": "ffff,fff" } } - ], - "variants": [] - }, - { - "name": "Fffff", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "finish-him", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "15", - "stickiness": "random", - "groupId": "finish-him" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "first", - "type": "kill-switch", - "enabled": false, - "stale": true, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "first" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "Demo", - "weight": 1000, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "fix-invalid-date", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "foo2", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "foobar", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "" } - } - ], - "variants": [] - }, - { - "name": "foobar2", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "foobar-shazam", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "foobar" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "foobar-toogle", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "foobar", "parameters": { "bar_p": "47" } } - ], - "variants": [] - }, - { - "name": "for-min-egen-del", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "" }, - "constraints": [] - }, - { - "name": "demo", - "parameters": { "demoGroup": "test" }, - "constraints": [] - } - ], - "variants": [ - { - "name": "myvariant", - "weight": 1000, - "payload": { "type": "string", "value": "test" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "fvjnfgjh", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": 61, - "stickiness": "userId", - "groupId": "fvjnfgjh" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "gdgfd", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "gerg", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "gjhbjhb", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "GoPower", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "hack", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "hackweek-22-test-feature", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [] - }, - { - "name": "hc-testing", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "hello", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "cooks", "parameters": { "Ttt": "" } }], - "variants": [] - }, - { - "name": "Hello", - "type": "kill-switch", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "hello_there", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "11", - "stickiness": "default", - "groupId": "hello_there" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "blue", - "weight": 500, - "payload": { "type": "string", "value": "blue" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - }, - { - "name": "green", - "weight": 500, - "payload": { "type": "string", "value": "xx" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "hello-world", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "HelloWorld", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "" } - } - ], - "variants": [] - }, - { - "name": "helloworldtoggle", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "hello-world-two-toggle", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "hgfhgf", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "", - "QA": "", - "Test": "", - "Training": "", - "Prod": "true" - } - } - ], - "variants": [] - }, - { - "name": "hggfhf", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "MyStrategy", - "parameters": { "param1": "jhghf", "param2": "kjlhkgjfhf" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "hjfghgfhf", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "", - "QA": "", - "Test": "", - "Training": "", - "Prod": "" - } - } - ], - "variants": [] - }, - { - "name": "hjkhjkhjkhjk", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "50", - "stickiness": "default", - "groupId": "hjkhjkhjkhjk" - } - } - ], - "variants": [] - }, - { - "name": "hjklhghj", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "jhkjhkj", - "Test": "hjkhjkhkj", - "Training": "jkhjkhjk", - "Prod": "hjkhkj" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "hock", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Hola", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "HookbasedSytem", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "hot-instead-of-cold-salad", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Httgghghg", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "H" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "Hghg", - "weight": 500, - "weightType": "fix", - "payload": { "type": "string", "value": "Red" }, - "overrides": [], - "stickiness": "default" - }, - { - "name": "Blue", - "weight": 500, - "weightType": "variable", - "payload": { "type": "string", "value": "blue" }, - "overrides": [], - "stickiness": "default" - } - ] - }, - { - "name": "InativarProdutos", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "jeroku.test", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "jjjjjjj", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "MyStrategy", - "parameters": { "param1": "8", "param2": "9" } - } - ], - "variants": [] - }, - { - "name": "jknkjbhkjvjhk", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "jknkjbhkjvjhk" - } - }, - { "name": "cid-strategy", "parameters": { "solution": "kjn" } } - ], - "variants": [] - }, - { - "name": "Jorge", - "type": "permission", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "remoteAddress", - "parameters": { "IPs": "tttt" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "josh-unique-flag", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "killswitch", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "1234" } - }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "12345" } - } - ], - "variants": [] - }, - { - "name": "KillWiFi", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "13", - "stickiness": "random", - "groupId": "KillWiFi" - } - } - ], - "variants": [] - }, - { - "name": "KS", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "lala", - "type": "experiment", - "enabled": true, - "stale": true, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "liroy", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "variant1", - "weight": 550, - "weightType": "fix", - "payload": { "type": "string", "value": "value1" }, - "overrides": [], - "stickiness": "default" - }, - { - "name": "variant2", - "weight": 150, - "payload": { "type": "string", "value": "value2" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - }, - { - "name": "variant3", - "weight": 300, - "weightType": "fix", - "payload": { "type": "string", "value": "value3" }, - "overrides": [], - "stickiness": "default" - } - ] - }, - { - "name": "lkmasd", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "lkmasd" - } - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "lkmasd" - } - } - ], - "variants": [] - }, - { - "name": "LLCampaign", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "location", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "LocationTags", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "awsomeUserStategy", - "parameters": { "userId": "23" }, - "constraints": [] - } - ], - "variants": [ - { - "name": "color", - "weight": 500, - "weightType": "variable", - "payload": { "type": "string", "value": "red" }, - "overrides": [ - { "contextName": "appName", "values": ["appppp"] } - ], - "stickiness": "default" - }, - { - "name": "color2", - "weight": 500, - "payload": { "type": "string", "value": "123" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "LodeKaSarKaarHai", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "lof", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "ly_test", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "mahshad-pyladies", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "123456" } } - ], - "variants": [] - }, - { - "name": "mahshad-second-test", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "0", - "stickiness": "default", - "groupId": "mahshad-second-test" - }, - "constraints": [] - }, - { - "name": "userWithId", - "parameters": { "userIds": "1,2,3,sss,sssss" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "mahshad-unleash-test", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "mahshad-unleash-test" - } - }, - { "name": "userWithId", "parameters": { "userIds": "" } } - ], - "variants": [] - }, - { - "name": "max-feature", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "mcast", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "roleBasedStrategy", - "parameters": { "roleId": "admin" }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 14, - "stickiness": "random", - "groupId": "mcast" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "mklasdm", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": 30, - "stickiness": "default", - "groupId": "mklasdm" - }, - "constraints": [] - }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "mehome" }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 30, - "stickiness": "default", - "groupId": "mklasdm" - }, - "constraints": [] - }, - { - "name": "gradualRolloutRandom", - "parameters": { "percentage": 46 }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "mmmm", - "type": "kill-switch", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "userWithId", - "parameters": { "userIds": "1" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "mobile", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "mockTimeRecordingData", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "RuntimeEnvironmentBased", - "parameters": { "runtimeEnvironmentId": "TEST" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "my-application.hack", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "my-debug-feature", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "My_feature", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "home", - "weight": 500, - "weightType": "variable", - "overrides": [], - "stickiness": "default" - }, - { - "name": "type", - "weight": 500, - "payload": { "type": "string", "value": "abc" }, - "overrides": [ - { "contextName": "userId", "values": ["1"] }, - { "contextName": "userId", "values": ["2"] } - ], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "myFeatureToggle", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "MyGreatAlgorithm", - "type": "permission", - "enabled": false, - "stale": true, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "MyGreatAlgorithm" - }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "56", - "stickiness": "default", - "groupId": "MyGreatAlgorithm" - }, - "constraints": [] - }, - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [] - }, - { - "name": "my-hero-comp", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "shan.dev.com" } - } - ], - "variants": [] - }, - { - "name": "mykey", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "50", - "stickiness": "default", - "groupId": "mykey" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "my-new-feature", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "my-new-feature-1", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "my-new-toggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "mynew-toggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "mytest", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "my-test-boyz", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "9", - "stickiness": "sessionId", - "groupId": "my-test-boyz" - }, - "constraints": [] - }, - { - "name": "Specialgroup", - "parameters": { "mail": "ciao" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "my-test-feature", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "123" } } - ], - "variants": [] - }, - { - "name": "my-testing-toggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "my-test-toggle", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "my-test-toggle2", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "my-test-toggle-2", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "My-toggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": 48, - "stickiness": "sessionId", - "groupId": "My-toggle" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "my-unique-test-name", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "random", - "groupId": "my-unique-test-name" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "my-unique-toggel", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "my-very-unique-toggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 84, - "stickiness": "default", - "groupId": "my-very-unique-toggle" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "asdfasdf", - "weight": 500, - "weightType": "variable", - "overrides": [], - "stickiness": "default" - }, - { - "name": "agasdgaegagse", - "weight": 500, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "name-tester", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "ok" } } - ], - "variants": [ - { - "name": "T1", - "weight": 500, - "weightType": "variable", - "payload": { "type": "string", "value": "T1" }, - "overrides": [], - "stickiness": "default" - }, - { - "name": "CC", - "weight": 500, - "weightType": "variable", - "payload": { "type": "string", "value": "C" }, - "overrides": [], - "stickiness": "default" - } - ] - }, - { - "name": "NarendraPatil", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { "name": "remoteAddress", "parameters": { "IPs": "" } }, - { "name": "default", "parameters": {} }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "" } - }, - { "name": "demo", "parameters": { "demoGroup": "" } }, - { "name": "userWithId", "parameters": { "userIds": "" } } - ], - "variants": [] - }, - { - "name": "NarendraTesting", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "nar,rus" } } - ], - "variants": [] - }, - { - "name": "needs-improvement", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "new-api", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [ - { - "name": "v1", - "weight": 1000, - "weightType": "fix", - "payload": { "type": "string", "value": "v1" }, - "overrides": [], - "stickiness": "default" - }, - { - "name": "v2", - "weight": 0, - "weightType": "variable", - "payload": { "type": "string", "value": "v2" }, - "overrides": [{ "contextName": "userId", "values": ["me"] }], - "stickiness": "default" - } - ] - }, - { - "name": "new-feature-815", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "newFeatureCustomerId", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "customerWithId", - "parameters": { "CustomerId": "104057243,104067509" }, - "constraints": [] - }, - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "true", - "Test": "false", - "Training": "true", - "Prod": "" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "newFeatureDiscount", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "HugeDiscount", - "weight": 500, - "weightType": "variable", - "payload": { "type": "string", "value": "50" }, - "overrides": [ - { "contextName": "userId", "values": ["kvajars"] } - ], - "stickiness": "default" - }, - { - "name": "SmallDiscount", - "weight": 500, - "weightType": "variable", - "payload": { "type": "string", "value": "5" }, - "overrides": [ - { "contextName": "userId", "values": ["aksoles"] } - ], - "stickiness": "default" - } - ] - }, - { - "name": "newFeatureToggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "server1" }, - "constraints": [] - }, - { - "name": "remoteAddress", - "parameters": { "IPs": "172.10.0.0" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "newFeatureUserId", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "50", - "stickiness": "userId", - "groupId": "newFeatureUserId" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "NewFet", - "type": "kill-switch", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "newKillSwitch", - "type": "kill-switch", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "PayloadVariant", - "weight": 1000, - "weightType": "variable", - "payload": { - "type": "string", - "value": "TFF er for tiden utilgjengelig. Det jobbes med saken og vi forventer at det vil være løst innen 15:00." - }, - "overrides": [], - "stickiness": "default" - } - ] - }, - { - "name": "OW", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "permissiontoggle", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "plannified-down-time", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "poc-forms-hub", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [] - }, - { - "name": "qweqweawe", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] }, - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "", - "Test": "", - "Training": "true", - "Prod": "" - }, - "constraints": [] - }, - { - "name": "generaltest", - "parameters": { - "rollout": 49, - "userIds": "TH,ERT", - "On/off": "true" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "RC", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Reallycoolfeature", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "cid-strategy", "parameters": { "solution": "" } } - ], - "variants": [] - }, - { - "name": "RecruiterPortalFeedback", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "RecruiterPortalFeedbackswsss", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "regra", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "" } - } - ], - "variants": [] - }, - { - "name": "relaseWhenReady", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "ResponseFeature", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "ResponseFeature2", - "weight": 1000, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "RiccardoTest", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "RiccardoTest" - } - } - ], - "variants": [] - }, - { - "name": "robert", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "", - "QA": "", - "Test": "", - "Training": "", - "Prod": "" - } - } - ], - "variants": [] - }, - { - "name": "Roman", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [] - }, - { - "name": "rs-fs-1929", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "10", - "stickiness": "userId", - "groupId": "rs-fs-1929" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "S3Conversion", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "CustomId", "parameters": { "CustomerId": "123" } }, - { - "name": "CustomId", - "parameters": { "CustomerId": "321" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "sad", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "sadasd", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "sadasd" - }, - "constraints": [] - }, - { "name": "default", "parameters": {}, "constraints": [] }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "sadasd" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "sadasdsa", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "dasda" } - } - ], - "variants": [] - }, - { - "name": "SCID", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "foobar", - "parameters": { "ENVIRONMENT": "DEV" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "ScreeningQ", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "sdasd", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "" } - }, - { "name": "default", "parameters": {} } - ], - "variants": [] - }, - { - "name": "sdasdasd", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "default", - "groupId": "sdasdasd" - } - } - ], - "variants": [] - }, - { - "name": "sdfgsdfg", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "sdfsdf", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "sdfsdfdfdfd", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "gradualRolloutRandom", - "parameters": { "percentage": 41 }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "sdfsdfsdf", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "sadasd,sad" }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "63", - "stickiness": "default", - "groupId": "sdfsdfsdf" - }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "68", - "stickiness": "default", - "groupId": "sdfsdfsdf" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "sdsf", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "sdfbbbbb", - "weight": 1000, - "weightType": "variable", - "payload": { "type": "string", "value": "ffff" }, - "overrides": [ - { "contextName": "userId", "values": ["gggg"] }, - { "contextName": "userId", "values": ["v1"] } - ] - } - ] - }, - { - "name": "secure-installation", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "1,2" } } - ], - "variants": [] - }, - { - "name": "Shop", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "shutdown", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Some-new-toggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "41", - "stickiness": "default", - "groupId": "Some-new-toggle" - } - } - ], - "variants": [] - }, - { - "name": "Something", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Somethingcool", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "spring-variants", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "75", - "stickiness": "default", - "groupId": "spring-variants" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "test", - "weight": 800, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - }, - { - "name": "this-is-fun", - "weight": 200, - "weightType": "fix", - "overrides": [], - "stickiness": "default" - } - ] - }, - { - "name": "sss", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "SuperAwesomeFeature", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "superfeature", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "super-truper", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "Implicit", "parameters": { "macro": "6" } } - ], - "variants": [] - }, - { - "name": "sweetness", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "75", - "stickiness": "default", - "groupId": "sweetness" - } - } - ], - "variants": [] - }, - { - "name": "SwitchFeature", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "SwitchOnline", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Taco", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "123,1" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "Test", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "TEST", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-01", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "foruser", - "weight": 1000, - "overrides": [{ "contextName": "userId", "values": ["1"] }], - "weightType": "variable" - } - ] - }, - { - "name": "test1", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "test1", - "parameters": { "codes": "" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test-11111-kill-feature-ever-released", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "70", - "stickiness": "default", - "groupId": "test-11111-kill-feature-ever-released" - } - } - ], - "variants": [] - }, - { - "name": "test123", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-123", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "RuntimeEnvironmentBased", - "parameters": { "runtimeEnvironmentId": "" } - }, - { "name": "test1", "parameters": { "codes": "" } } - ], - "variants": [] - }, - { - "name": "Test-123", - "type": "release", - "enabled": true, - "stale": true, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "jjjjjjj" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test1231231", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test1234214", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Test234", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "true", - "Test": "", - "Training": "", - "Prod": "false" - } - } - ], - "variants": [] - }, - { - "name": "test2345", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "32", - "stickiness": "default", - "groupId": "test2345" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test256", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "sdzxfsdf" }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": 38, - "stickiness": "default", - "groupId": "test256" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test.3.12.0", - "type": "experiment", - "enabled": true, - "stale": true, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "47", - "stickiness": "default", - "groupId": "test.3.12.0" - }, - "constraints": [] - }, - { - "name": "test-env", - "parameters": { "prod": "true", "dev": "true" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "Test33", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "50", - "stickiness": "userId", - "groupId": "Test33" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test777", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test8878687", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "test", "parameters": { "users": "tttt,hhjgj" } } - ], - "variants": [] - }, - { - "name": "test-cid", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "cid-strategy", - "parameters": { "solution": "VCF,SYN,VCF_4.10" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test.create", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Test.create", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "demo", - "parameters": { "demoGroup": "" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test.create.adddon", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "teste", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "teste1", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "test1", "parameters": {}, "constraints": [] } - ], - "variants": [] - }, - { - "name": "teste123123", - "type": "kill-switch", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "asd,teste,tesasd" } - } - ], - "variants": [] - }, - { - "name": "Tester", - "type": "kill-switch", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-feature", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { "name": "userWithId", "parameters": { "userIds": "" } } - ], - "variants": [] - }, - { - "name": "testFeature", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-feature-1", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "selected-schools", - "parameters": { "schoolId": "bla" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test-feature-99999", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Test-FF", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "demo", - "parameters": { "demoGroup": "abc" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test-for-me", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "TestGroup", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "TestGroup", "parameters": { "Group": "Foo" } }, - { "name": "TestGroup", "parameters": { "Group": "Bar" } } - ], - "variants": [] - }, - { - "name": "testgtasdas", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "" } - } - ], - "variants": [] - }, - { - "name": "Testing", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "" } - } - ], - "variants": [] - }, - { - "name": "testing123", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "testing-toggle-12", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "testlog", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-new-feature", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "userWithId", "parameters": { "userIds": "5" } } - ], - "variants": [] - }, - { - "name": "Test_Permission1", - "type": "permission", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "test1", - "parameters": { "codes": "code1,code2" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "test.ping", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "testproduct", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-raf", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-release-flag", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "endpoint", - "weight": 1000, - "payload": { "type": "string", "value": "this_is_the_endpoint" }, - "overrides": [], - "weightType": "variable" - } - ] - }, - { - "name": "TestSwitch1", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-t", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "testtertogle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "testtest", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { "name": "dfazza", "parameters": { "asdfasdf": "afasd" } } - ], - "variants": [] - }, - { - "name": "test-test", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "test,test1,test2" }, - "constraints": [] - }, - { "name": "default", "parameters": {}, "constraints": [] } - ], - "variants": [ - { - "name": "t1", - "weight": 750, - "weightType": "fix", - "payload": { "type": "string", "value": "t1" }, - "overrides": [{ "contextName": "userId", "values": ["abcdef"] }], - "stickiness": "default" - }, - { - "name": "t2", - "weight": 250, - "payload": { "type": "string", "value": "t2" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "test-test-and-some-more-test", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "", - "QA": "", - "Test": "", - "Training": "", - "Prod": "true" - } - } - ], - "variants": [] - }, - { - "name": "TestTesting", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "default", "parameters": {} }, - { - "name": "asd", - "parameters": { "asd": "asd", "sdf": "" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "testtoggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test-toggle", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "testtt", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "test_variant", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "version", - "weight": 1000, - "payload": { "type": "string", "value": "v1" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "test-w", - "type": "operational", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Testymctestface", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "true", - "Test": "", - "Training": "", - "Prod": "true" - } - } - ], - "variants": [] - }, - { - "name": "tgtg", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "the-awesome-feature", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Theone", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "ticket", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "demo", "parameters": { "demoGroup": "dsfasfd" } } - ], - "variants": [ - { - "name": "bool", - "weight": 1000, - "weightType": "variable", - "payload": { "type": "string", "value": "valuess" }, - "overrides": [], - "stickiness": "default" - } - ] - }, - { - "name": "TotesMcGoats", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "trololo", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "tryion.dev.auth", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "Ttt", - "type": "operational", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "uname", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "unique", - "type": "kill-switch", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "UniqueCreateContractFeature", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "unleaseh-my-mama", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "demo", "parameters": { "demoGroup": "you" } } - ], - "variants": [] - }, - { - "name": "unleash_aws_s3", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "gradualRolloutRandom", - "parameters": { "percentage": "60" } - } - ], - "variants": [ - { - "name": "s3", - "weight": 333, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - }, - { - "name": "gcp", - "weight": 333, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - }, - { - "name": "azure", - "weight": 333, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "unleash-demo.avansert", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "testbruker" }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "47", - "stickiness": "default", - "groupId": "unleash-demo.avansert" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "unleash-demo.hjemmelagd", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "byEnhet", - "parameters": { "valgtEnhet": "456" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "unleash-demo.scheduler", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "unleash-demo.scheduler.default-pa", - "type": "release", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "user.pornFilter", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "UserID", - "parameters": { "AD_GRP_1, AD_GRP_2": "asdf,asdf2,asdf3,asdf4" } - } - ], - "variants": [] - }, - { - "name": "vartest", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [ - { - "name": "v1", - "weight": 333, - "payload": { "type": "string", "value": "v1" }, - "overrides": [], - "weightType": "variable" - }, - { - "name": "v2", - "weight": 333, - "payload": { "type": "string", "value": "v2" }, - "overrides": [], - "weightType": "variable" - }, - { - "name": "v3", - "weight": 333, - "payload": { "type": "string", "value": "v3" }, - "overrides": [], - "weightType": "variable" - } - ] - }, - { - "name": "vcvcvc-test-feature", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { "name": "foobar", "parameters": { "ENVIRONMENT": "DEV" } }, - { - "name": "applicationHostname", - "parameters": { "hostNames": "test" }, - "constraints": [] - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "49", - "stickiness": "default", - "groupId": "vcvcvc-test-feature" - }, - "constraints": [] - }, - { - "name": "remoteAddress", - "parameters": { "IPs": "1.1.1.1" }, - "constraints": [] - }, - { - "name": "Environment", - "parameters": { - "Dev": "true", - "QA": "", - "Test": "", - "Training": "", - "Prod": "" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "Very.cool.toggle", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "49", - "stickiness": "default", - "groupId": "Very.cool.toggle" - } - }, - { - "name": "flexibleRollout", - "parameters": { - "rollout": "25", - "stickiness": "default", - "groupId": "Very.cool.toggle" - }, - "constraints": [] - } - ], - "variants": [ - { - "name": "xc", - "weight": 500, - "payload": { "type": "string", "value": "sdf" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - }, - { - "name": "dsfsdf", - "weight": 500, - "payload": { "type": "string", "value": "sdf" }, - "overrides": [], - "weightType": "variable", - "stickiness": "default" - } - ] - }, - { - "name": "vlad", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "wasd", - "type": "experiment", - "enabled": false, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "51", - "stickiness": "default", - "groupId": "wasd" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "whitelabel", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "whitelist", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "userWithId", - "parameters": { "userIds": "juan@gmail.com" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "wwwwwwww", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "39", - "stickiness": "default", - "groupId": "wwwwwwww" - }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "xcvh", - "type": "kill-switch", - "enabled": false, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "xxx", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "flexibleRollout", - "parameters": { - "rollout": "100", - "stickiness": "userId", - "groupId": "xxx" - } - } - ], - "variants": [] - }, - { - "name": "yest", - "type": "experiment", - "enabled": true, - "stale": false, - "strategies": [{ "name": "default", "parameters": {} }], - "variants": [] - }, - { - "name": "zxc", - "type": "operational", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "trunk,testing" }, - "constraints": [] - } - ], - "variants": [] - }, - { - "name": "zXVa", - "type": "release", - "enabled": true, - "stale": false, - "strategies": [ - { - "name": "applicationHostname", - "parameters": { "hostNames": "dsagfa,asdfadf" }, - "constraints": [] - } - ], - "variants": [] - } - ] -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/doc.go b/vendor/github.com/Unleash/unleash-client-go/v4/doc.go deleted file mode 100644 index a505430ac..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/doc.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Package unleash is a client library for connecting to an Unleash feature toggle server. - -See https://github.com/Unleash/unleash for more information. - -# Basics - -The API is very simple. The main functions of interest are Initialize and IsEnabled. Calling Initialize -will create a default client and if a listener is supplied, it will start the sync loop. Internally the client -consists of two components. The first is the repository which runs in a separate Go routine and polls the -server to get the latest feature toggles. Once the feature toggles are fetched, they are stored by sending -the data to an instance of the Storage interface which is responsible for storing the data both in memory -and also persisting it somewhere. The second component is the metrics component which is responsible for tracking -how often features were queried and whether or not they were enabled. The metrics components also runs in a -separate Go routine and will occasionally upload the latest metrics to the Unleash server. The client struct -creates a set of channels that it passes to both of the above components and it uses those for communicating -asynchronously. It is important to ensure that these channels get regularly drained to avoid blocking those -Go routines. There are two ways this can be done. - -# Using the Listener Interfaces - -The first and perhaps simplest way to "drive" the synchronization loop in the client is to provide a type -that implements one or more of the listener interfaces. There are 3 interfaces and you can choose which ones -you should implement: - - ErrorListener - - RepositoryListener - - MetricsListener - -If you are only interesting in tracking errors and warnings and don't care about any of the other signals, -then you only need to implement the ErrorListener and pass this instance to WithListener(). The DebugListener -shows an example of implementing all of the listeners in a single type. - -# Reading the channels directly - -If you would prefer to have control over draining the channels yourself, then you must not call WithListener(). -Instead, you should read all of the channels continuously inside a select. The WithInstance example shows how -to do this. Note that all channels must be drained, even if you are not interested in the result. - -# Examples - -The following examples show how to use the client in different scenarios. -*/ -package unleash diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/api/event.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/api/event.go deleted file mode 100644 index 0e0516921..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/api/event.go +++ /dev/null @@ -1,36 +0,0 @@ -package api - -import ( - "time" - - "github.com/Unleash/unleash-client-go/v4/api" -) - -type EventResponse struct { - api.Response - Events []Event `json:"events"` -} - -type Event struct { - Id int `json:"id"` - Type string `json:"type"` - CreatedBy string `json:"createdBy"` - CreatedAt time.Time `json:"createdAt"` - Data EventData `json:"data"` - Diffs *[]EventDiff `json:"diffs"` -} - -type EventData struct { - Name string `json:"name"` - Description string `json:"description"` - Enabled bool `json:"enabled"` - Strategies []api.Strategy `json:"strategies"` - CreatedAt time.Time `json:"createdAt"` -} - -type EventDiff struct { - Kind string `json:"kind"` - Path []string `json:"path"` - Lhs bool `json:"lhs"` - Rhs bool `json:"rhs"` -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/api/metrics.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/api/metrics.go deleted file mode 100644 index 66d6553cb..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/api/metrics.go +++ /dev/null @@ -1,19 +0,0 @@ -package api - -import "time" - -type ToggleCount struct { - Yes int32 `json:"yes"` - No int32 `json:"no"` - Variants map[string]int32 `json:"variants"` -} - -type Bucket struct { - Start time.Time `json:"start"` - Stop time.Time `json:"stop"` - Toggles map[string]ToggleCount `json:"toggles"` -} - -func (b Bucket) IsEmpty() bool { - return len(b.Toggles) == 0 -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/check.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/check.go deleted file mode 100644 index 2d5c2932d..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/check.go +++ /dev/null @@ -1,68 +0,0 @@ -package constraints - -import ( - "fmt" - - "github.com/Unleash/unleash-client-go/v4/api" - "github.com/Unleash/unleash-client-go/v4/context" -) - -// Check checks if all the constraints are fulfilled by the context. -func Check(ctx *context.Context, constraints []api.Constraint) (bool, error) { - for _, c := range constraints { - if ok, err := checkConstraintInvertible(ctx, c); !ok || err != nil { - return false, err - } - } - - return true, nil -} - -// checkConstraintInvertible inverts the result from checkConstraint if required. -func checkConstraintInvertible(ctx *context.Context, constraint api.Constraint) (bool, error) { - ok, err := checkConstraint(ctx, constraint) - - if constraint.Inverted { - return !ok, err - } - - return ok, err -} - -// checkConstraint checks if a specific constraint is fulfilled by the context. -func checkConstraint(ctx *context.Context, constraint api.Constraint) (bool, error) { - switch constraint.Operator { - case api.OperatorIn: - return operatorIn(ctx, constraint), nil - case api.OperatorNotIn: - return operatorNotIn(ctx, constraint), nil - case api.OperatorStrContains: - return operatorStrContains(ctx, constraint), nil - case api.OperatorStrStartsWith: - return operatorStrStartsWith(ctx, constraint), nil - case api.OperatorStrEndsWith: - return operatorStrEndsWith(ctx, constraint), nil - case api.OperatorNumEq: - return operatorNumEq(ctx, constraint) - case api.OperatorNumLt: - return operatorNumLt(ctx, constraint) - case api.OperatorNumLte: - return operatorNumLte(ctx, constraint) - case api.OperatorNumGt: - return operatorNumGt(ctx, constraint) - case api.OperatorNumGte: - return operatorNumGte(ctx, constraint) - case api.OperatorDateBefore: - return operatorDateBefore(ctx, constraint) - case api.OperatorDateAfter: - return operatorDateAfter(ctx, constraint) - case api.OperatorSemverEq: - return operatorSemverEq(ctx, constraint) - case api.OperatorSemverLt: - return operatorSemverLt(ctx, constraint) - case api.OperatorSemverGt: - return operatorSemverGt(ctx, constraint) - default: - return false, fmt.Errorf("unknown constraint operator: %s", constraint.Operator) - } -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_date.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_date.go deleted file mode 100644 index ffb0a1d15..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_date.go +++ /dev/null @@ -1,48 +0,0 @@ -package constraints - -import ( - "github.com/Unleash/unleash-client-go/v4/api" - "github.com/Unleash/unleash-client-go/v4/context" - "time" -) - -func operatorDateBefore(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorDate(ctx, constraint, func(context time.Time, constraint time.Time) bool { - return context.Before(constraint) - }) -} - -func operatorDateAfter(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorDate(ctx, constraint, func(context time.Time, constraint time.Time) bool { - return context.After(constraint) - }) -} - -func operatorDate( - ctx *context.Context, - constraint api.Constraint, - check func(context time.Time, constraint time.Time) bool, -) (bool, error) { - contextParsed, contextErr := contextDateValueOrNow(ctx, constraint) - constraintParsed, constraintErr := time.Parse(time.RFC3339, constraint.Value) - - if contextErr != nil { - return false, contextErr - } - - if constraintErr != nil { - return false, constraintErr - } - - return check(contextParsed, constraintParsed), nil -} - -func contextDateValueOrNow(ctx *context.Context, constraint api.Constraint) (time.Time, error) { - contextValue := ctx.Field(constraint.ContextName) - - if contextValue != "" { - return time.Parse(time.RFC3339, contextValue) - } - - return time.Now(), nil -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_in.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_in.go deleted file mode 100644 index 4844e9511..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_in.go +++ /dev/null @@ -1,22 +0,0 @@ -package constraints - -import ( - "github.com/Unleash/unleash-client-go/v4/api" - "github.com/Unleash/unleash-client-go/v4/context" -) - -func operatorNotIn(ctx *context.Context, constraint api.Constraint) bool { - return !operatorIn(ctx, constraint) -} - -func operatorIn(ctx *context.Context, constraint api.Constraint) bool { - contextValue := ctx.Field(constraint.ContextName) - - for _, constraint := range constraint.Values { - if contextValue == constraint { - return true - } - } - - return false -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_num.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_num.go deleted file mode 100644 index 6f1c4c440..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_num.go +++ /dev/null @@ -1,57 +0,0 @@ -package constraints - -import ( - "github.com/Unleash/unleash-client-go/v4/api" - "github.com/Unleash/unleash-client-go/v4/context" - "math/big" -) - -func operatorNumEq(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorNum(ctx, constraint, func(context *big.Float, constraint *big.Float) bool { - return context.Cmp(constraint) == 0 - }) -} - -func operatorNumLt(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorNum(ctx, constraint, func(context *big.Float, constraint *big.Float) bool { - return context.Cmp(constraint) < 0 - }) -} - -func operatorNumLte(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorNum(ctx, constraint, func(context *big.Float, constraint *big.Float) bool { - return context.Cmp(constraint) <= 0 - }) -} - -func operatorNumGt(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorNum(ctx, constraint, func(context *big.Float, constraint *big.Float) bool { - return context.Cmp(constraint) > 0 - }) -} - -func operatorNumGte(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorNum(ctx, constraint, func(context *big.Float, constraint *big.Float) bool { - return context.Cmp(constraint) >= 0 - }) -} - -func operatorNum( - ctx *context.Context, - constraint api.Constraint, - check func(context *big.Float, constraint *big.Float) bool, -) (bool, error) { - contextValue := ctx.Field(constraint.ContextName) - contextParsed, _, contextErr := big.ParseFloat(contextValue, 10, 0, big.ToNearestEven) - constraintParsed, _, constraintErr := big.ParseFloat(constraint.Value, 10, 0, big.ToNearestEven) - - if contextErr != nil { - return false, contextErr - } - - if constraintErr != nil { - return false, constraintErr - } - - return check(contextParsed, constraintParsed), nil -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_semver.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_semver.go deleted file mode 100644 index 767549aab..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_semver.go +++ /dev/null @@ -1,45 +0,0 @@ -package constraints - -import ( - "github.com/Masterminds/semver/v3" - "github.com/Unleash/unleash-client-go/v4/api" - "github.com/Unleash/unleash-client-go/v4/context" -) - -func operatorSemverEq(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorSemver(ctx, constraint, func(context *semver.Version, constraint *semver.Version) bool { - return context.Equal(constraint) - }) -} - -func operatorSemverLt(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorSemver(ctx, constraint, func(context *semver.Version, constraint *semver.Version) bool { - return context.LessThan(constraint) - }) -} - -func operatorSemverGt(ctx *context.Context, constraint api.Constraint) (bool, error) { - return operatorSemver(ctx, constraint, func(context *semver.Version, constraint *semver.Version) bool { - return context.GreaterThan(constraint) - }) -} - -func operatorSemver( - ctx *context.Context, - constraint api.Constraint, - check func(context *semver.Version, constraint *semver.Version) bool, -) (bool, error) { - contextValue := ctx.Field(constraint.ContextName) - contextParsed, contextErr := semver.StrictNewVersion(contextValue) - constraintParsed, constraintErr := semver.StrictNewVersion(constraint.Value) - - if contextErr != nil { - return false, contextErr - } - - if constraintErr != nil { - return false, constraintErr - } - - return check(contextParsed, constraintParsed), nil -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_str.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_str.go deleted file mode 100644 index fd8eddba2..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/constraints/operator_str.go +++ /dev/null @@ -1,43 +0,0 @@ -package constraints - -import ( - "github.com/Unleash/unleash-client-go/v4/api" - "github.com/Unleash/unleash-client-go/v4/context" - "strings" -) - -func operatorStrContains(ctx *context.Context, constraint api.Constraint) bool { - return operatorStr(ctx, constraint, strings.Contains) -} - -func operatorStrStartsWith(ctx *context.Context, constraint api.Constraint) bool { - return operatorStr(ctx, constraint, strings.HasPrefix) -} - -func operatorStrEndsWith(ctx *context.Context, constraint api.Constraint) bool { - return operatorStr(ctx, constraint, strings.HasSuffix) -} - -func operatorStr( - ctx *context.Context, - constraint api.Constraint, - check func(context string, constraint string) bool, -) bool { - contextValue := toLowerIfCaseInsensitive(constraint, ctx.Field(constraint.ContextName)) - - for _, constraintValue := range constraint.Values { - if check(contextValue, toLowerIfCaseInsensitive(constraint, constraintValue)) { - return true - } - } - - return false -} - -func toLowerIfCaseInsensitive(constraint api.Constraint, value string) string { - if constraint.CaseInsensitive { - return strings.ToLower(value) - } else { - return value - } -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/application_hostname.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/application_hostname.go deleted file mode 100644 index 576a429ad..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/application_hostname.go +++ /dev/null @@ -1,41 +0,0 @@ -package strategies - -import ( - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/strategy" - "strings" -) - -type applicationHostnameStrategy struct { - hostname string -} - -func NewApplicationHostnameStrategy() *applicationHostnameStrategy { - hostname, _ := resolveHostname() - return &applicationHostnameStrategy{ - strings.ToLower(hostname), - } -} - -func (s applicationHostnameStrategy) Name() string { - return "applicationHostname" -} - -func (s applicationHostnameStrategy) IsEnabled(params map[string]interface{}, _ *context.Context) bool { - value, found := params[strategy.ParamHostNames] - if !found { - return false - } - - hostnames, ok := value.(string) - if !ok { - return false - } - - for _, h := range strings.Split(hostnames, ",") { - if strings.ToLower(h) == s.hostname { - return true - } - } - return false -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/default.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/default.go deleted file mode 100644 index cbe56759b..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/default.go +++ /dev/null @@ -1,17 +0,0 @@ -package strategies - -import "github.com/Unleash/unleash-client-go/v4/context" - -type defaultStrategy struct{} - -func NewDefaultStrategy() *defaultStrategy { - return &defaultStrategy{} -} - -func (s defaultStrategy) Name() string { - return "default" -} - -func (s defaultStrategy) IsEnabled(_ map[string]interface{}, _ *context.Context) bool { - return true -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/flexible_rollout.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/flexible_rollout.go deleted file mode 100644 index fb02eba4e..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/flexible_rollout.go +++ /dev/null @@ -1,67 +0,0 @@ -package strategies - -import ( - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/strategy" -) - -type stickiness string - -const ( - defaultStickiness stickiness = "default" - randomStickiness stickiness = "random" -) - -type flexibleRolloutStrategy struct { - random *rng -} - -// NewFlexibleRolloutStrategy creates a new instance of the flexible rollout strategy. -func NewFlexibleRolloutStrategy() *flexibleRolloutStrategy { - s := &flexibleRolloutStrategy{ - random: newRng(), - } - return s -} - -func (s flexibleRolloutStrategy) Name() string { - return "flexibleRollout" -} - -func (s flexibleRolloutStrategy) resolveStickiness(st stickiness, ctx context.Context) string { - switch st { - case defaultStickiness: - return coalesce(ctx.UserId, ctx.SessionId, s.random.string()) - case randomStickiness: - return s.random.string() - default: - return ctx.Field(string(st)) - } -} - -func (s flexibleRolloutStrategy) IsEnabled(params map[string]interface{}, ctx *context.Context) bool { - groupID := "" - if gID, found := params[strategy.ParamGroupId]; found { - groupID = gID.(string) - } - - rollout, found := params[strategy.ParamRollout] - if !found { - return false - } - - percentage, ok := parameterAsFloat64(rollout) - if !ok { - return false - } - - sticky := coalesce(params[strategy.ParamStickiness].(string), string(defaultStickiness)) - stickinessID := s.resolveStickiness(stickiness(sticky), *ctx) - - if stickinessID == "" { - return false - } - - normalizedID := normalizedRolloutValue(stickinessID, groupID) - return percentage > 0 && float64(normalizedID) <= percentage -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_random.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_random.go deleted file mode 100644 index 42da29eba..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_random.go +++ /dev/null @@ -1,35 +0,0 @@ -package strategies - -import ( - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/strategy" -) - -type gradualRolloutRandomStrategy struct { - random *rng -} - -func NewGradualRolloutRandomStrategy() *gradualRolloutRandomStrategy { - s := &gradualRolloutRandomStrategy{ - newRng(), - } - return s -} - -func (s gradualRolloutRandomStrategy) Name() string { - return "gradualRolloutRandom" -} - -func (s gradualRolloutRandomStrategy) IsEnabled(params map[string]interface{}, _ *context.Context) bool { - value, found := params[strategy.ParamPercentage] - if !found { - return false - } - - percentage, ok := parameterAsFloat64(value) - if !ok { - return false - } - - return percentage >= s.random.float() -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_session_id.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_session_id.go deleted file mode 100644 index afd6ef02b..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_session_id.go +++ /dev/null @@ -1,44 +0,0 @@ -package strategies - -import ( - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/strategy" -) - -type gradualRolloutSessionId struct { -} - -func NewGradualRolloutSessionId() *gradualRolloutSessionId { - s := &gradualRolloutSessionId{} - return s -} - -func (s gradualRolloutSessionId) Name() string { - return "gradualRolloutSessionId" -} - -func (s gradualRolloutSessionId) IsEnabled(params map[string]interface{}, ctx *context.Context) bool { - if ctx == nil || ctx.SessionId == "" { - return false - } - - value, found := params[strategy.ParamPercentage] - if !found { - return false - } - - percentage, ok := parameterAsFloat64(value) - if !ok { - return false - } - - groupIdValue := params[strategy.ParamGroupId] - groupId, ok := groupIdValue.(string) - if !ok { - return false - } - - normalizedId := normalizedRolloutValue(ctx.SessionId, groupId) - - return percentage > 0.0 && float64(normalizedId) <= percentage -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_user_id.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_user_id.go deleted file mode 100644 index 09e099920..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/gradual_rollout_user_id.go +++ /dev/null @@ -1,44 +0,0 @@ -package strategies - -import ( - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/strategy" -) - -type gradualRolloutUserId struct { -} - -func NewGradualRolloutUserId() *gradualRolloutUserId { - s := &gradualRolloutUserId{} - return s -} - -func (s gradualRolloutUserId) Name() string { - return "gradualRolloutUserId" -} - -func (s gradualRolloutUserId) IsEnabled(params map[string]interface{}, ctx *context.Context) bool { - if ctx == nil || ctx.UserId == "" { - return false - } - - value, found := params[strategy.ParamPercentage] - if !found { - return false - } - - percentage, ok := parameterAsFloat64(value) - if !ok { - return false - } - - groupIdValue := params[strategy.ParamGroupId] - groupId, ok := groupIdValue.(string) - if !ok { - return false - } - - normalizedId := normalizedRolloutValue(ctx.UserId, groupId) - - return percentage > 0.0 && float64(normalizedId) <= percentage -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/helpers.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/helpers.go deleted file mode 100644 index fa876c392..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/helpers.go +++ /dev/null @@ -1,104 +0,0 @@ -package strategies - -import ( - "math/rand" - "os" - "strconv" - "sync" - "time" - - "github.com/twmb/murmur3" -) - -var VariantNormalizationSeed uint32 = 86028157 - -func round(f float64) int { - if f < -0.5 { - return int(f - 0.5) - } - if f > 0.5 { - return int(f + 0.5) - } - return 0 -} - -func resolveHostname() (string, error) { - var err error - hostname := os.Getenv("HOSTNAME") - if hostname == "" { - hostname, err = os.Hostname() - if err != nil { - hostname = "undefined" - } - } - return hostname, err -} - -func parameterAsFloat64(param interface{}) (result float64, ok bool) { - if f, isFloat := param.(float64); isFloat { - result, ok = f, true - } else if i, isInt := param.(int); isInt { - result, ok = float64(i), true - } else if i, isInt := param.(uint32); isInt { - result, ok = float64(i), true - } else if i, isInt := param.(int64); isInt { - result, ok = float64(i), true - } else if s, isString := param.(string); isString { - f, err := strconv.ParseFloat(s, 64) - if err == nil { - result, ok = f, true - } - } - return -} - -func normalizedRolloutValue(id string, groupId string) uint32 { - return NormalizedVariantValue(id, groupId, 100, 0) -} - -func NormalizedVariantValue(id string, groupId string, normalizer int, seed uint32) uint32 { - hash := murmur3.SeedNew32(seed) - hash.Write([]byte(groupId + ":" + id)) - hashCode := hash.Sum32() - return hashCode%uint32(normalizer) + 1 -} - -// coalesce returns the first non-empty string in the list of arguments -func coalesce(str ...string) string { - for _, s := range str { - if s != "" { - return s - } - } - return "" -} - -type rng struct { - sync.Mutex - random *rand.Rand -} - -func (r *rng) int() int { - r.Lock() - n := r.random.Intn(100) + 1 - r.Unlock() - return n -} - -func (r *rng) float() float64 { - return float64(r.int()) -} - -func (r *rng) string() string { - r.Lock() - n := r.random.Intn(10000) + 1 - r.Unlock() - return strconv.Itoa(n) -} - -// newRng creates a new random number generator and uses a mutex -// internally to ensure safe concurrent reads. -func newRng() *rng { - seed := time.Now().UnixNano() + int64(os.Getpid()) - return &rng{random: rand.New(rand.NewSource(seed))} -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/remote_addresss.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/remote_addresss.go deleted file mode 100644 index 4cb688fa9..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/remote_addresss.go +++ /dev/null @@ -1,46 +0,0 @@ -package strategies - -import ( - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/strategy" - "net" - "strings" -) - -type remoteAddressStrategy struct { -} - -func NewRemoteAddressStrategy() *remoteAddressStrategy { - return &remoteAddressStrategy{} -} - -func (s remoteAddressStrategy) Name() string { - return "remoteAddress" -} - -func (s remoteAddressStrategy) IsEnabled(params map[string]interface{}, ctx *context.Context) bool { - value, found := params[strategy.ParamIps] - if !found { - return false - } - - remoteAddress := net.ParseIP(strings.TrimSpace(ctx.RemoteAddress)) - if remoteAddress == nil { - return false - } - - ips, ok := value.(string) - if !ok { - return false - } - - for _, ip := range strings.Split(ips, ",") { - ip = strings.TrimSpace(ip) - if remoteAddress.Equal(net.ParseIP(ip)) { - return true - } else if _, ipNet, _ := net.ParseCIDR(ip); ipNet != nil && ipNet.Contains(remoteAddress) { - return true - } - } - return false -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/user_with_id.go b/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/user_with_id.go deleted file mode 100644 index a9ef403f8..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/internal/strategies/user_with_id.go +++ /dev/null @@ -1,36 +0,0 @@ -package strategies - -import ( - "github.com/Unleash/unleash-client-go/v4/context" - "github.com/Unleash/unleash-client-go/v4/strategy" - "strings" -) - -type userWithIdStrategy struct{} - -func NewUserWithIdStrategy() *userWithIdStrategy { - return &userWithIdStrategy{} -} - -func (s userWithIdStrategy) Name() string { - return "userWithId" -} - -func (s userWithIdStrategy) IsEnabled(params map[string]interface{}, ctx *context.Context) bool { - value, found := params[strategy.ParamUserIds] - if !found { - return false - } - - userIds, ok := value.(string) - if !ok || userIds == "" { - return false - } - - for _, u := range strings.Split(userIds, ",") { - if strings.TrimSpace(u) == ctx.UserId { - return true - } - } - return false -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/metrics.go b/vendor/github.com/Unleash/unleash-client-go/v4/metrics.go deleted file mode 100644 index 3788eb885..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/metrics.go +++ /dev/null @@ -1,343 +0,0 @@ -package unleash - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "math" - "net/http" - "net/url" - "runtime" - "sync" - "time" - - "github.com/Unleash/unleash-client-go/v4/internal/api" -) - -// MetricsData represents the data sent to the unleash server. -type MetricsData struct { - // AppName is the name of the application. - AppName string `json:"appName"` - - // InstanceID is the instance identifier. - InstanceID string `json:"instanceId"` - - // Bucket is the payload data sent to the server. - Bucket api.Bucket `json:"bucket"` - - // The runtime version of our Platform - PlatformVersion string `json:"platformVersion"` - - // The runtime name of our Platform - PlatformName string `json:"platformName"` - - // Which version of Yggdrasil is being used - YggdrasilVersion *string `json:"yggdrasilVersion"` - - // Optional field that describes the sdk version (name:version) - SDKVersion string `json:"sdkVersion"` - - // Which version of the Unleash-Client-Spec is this SDK validated against - SpecVersion string `json:"specVersion"` -} - -// ClientData represents the data sent to the unleash during registration. -type ClientData struct { - // AppName is the name of the application. - AppName string `json:"appName"` - - // InstanceID is the instance identifier. - InstanceID string `json:"instanceId"` - - // Optional field that describes the sdk version (name:version) - SDKVersion string `json:"sdkVersion"` - - // Strategies is a list of names of the strategies supported by the client. - Strategies []string `json:"strategies"` - - // Started indicates the time at which the client was created. - Started time.Time `json:"started"` - - // Interval specifies the time interval (in ms) that the client is using for refreshing - // feature toggles. - Interval int64 `json:"interval"` - - PlatformVersion string `json:"platformVersion"` - - PlatformName string `json:"platformName"` - - YggdrasilVersion *string `json:"yggdrasilVersion"` - - // Which version of the Unleash-Client-Spec is this SDK validated against - SpecVersion string `json:"specVersion"` -} - -type metric struct { - // Name is the name of the feature toggle. - Name string - - // Enabled indicates whether the feature was enabled or not. - Enabled bool -} - -type metrics struct { - metricsChannels - options metricsOptions - started time.Time - bucketMu sync.Mutex - bucket api.Bucket - ticker *time.Ticker - close chan struct{} - closed chan struct{} - ctx context.Context - cancel func() - maxSkips float64 - errors float64 - skips float64 -} - -func newMetrics(options metricsOptions, channels metricsChannels) *metrics { - m := &metrics{ - metricsChannels: channels, - options: options, - started: time.Now(), - close: make(chan struct{}), - closed: make(chan struct{}), - maxSkips: 10, - errors: 0, - skips: 0, - } - ctx, cancel := context.WithCancel(context.Background()) - m.ctx = ctx - m.cancel = cancel - - if m.options.httpClient == nil { - m.options.httpClient = http.DefaultClient - } - - m.resetBucket() - if m.options.metricsInterval <= 0 { - m.options.disableMetrics = true - } - if !m.options.disableMetrics { - m.ticker = time.NewTicker(m.options.metricsInterval) - m.registerInstance() - go m.sync() - } - - return m -} - -func (m *metrics) Close() error { - if !m.options.disableMetrics { - m.ticker.Stop() - m.cancel() - close(m.close) - <-m.closed - } - return nil -} - -func (m *metrics) sync() { - for { - select { - case <-m.ticker.C: - if m.skips == 0 { - m.sendMetrics() - } else { - m.decrementSkip() - } - case <-m.close: - close(m.closed) - return - } - } -} - -func (m *metrics) registerInstance() { - u, _ := m.options.url.Parse("./client/register") - payload := m.getClientData() - resp, err := m.doPost(u, payload) - - if err != nil { - m.err(err) - return - } - defer resp.Body.Close() - - if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusMultipleChoices { - m.warn(fmt.Errorf("%s return %d", u.String(), resp.StatusCode)) - } - - m.registered <- payload -} -func (m *metrics) backoff() { - m.errors = math.Min(m.maxSkips, m.errors+1) - m.skips = m.errors -} - -func (m *metrics) configurationError() { - m.errors = m.maxSkips - m.skips = m.errors -} - -func (m *metrics) successfulPost() { - m.errors = math.Max(0, m.errors-1) - m.skips = m.errors -} - -func (m *metrics) decrementSkip() { - m.skips = math.Max(0, m.skips-1) -} -func (m *metrics) sendMetrics() { - m.bucketMu.Lock() - bucket := m.resetBucket() - m.bucketMu.Unlock() - if bucket.IsEmpty() { - return - } - bucket.Stop = time.Now() - payload := MetricsData{ - AppName: m.options.appName, - InstanceID: m.options.instanceId, - Bucket: bucket, - SDKVersion: fmt.Sprintf("%s:%s", clientName, clientVersion), - PlatformName: "go", - PlatformVersion: runtime.Version(), - YggdrasilVersion: nil, - SpecVersion: specVersion, - } - - u, _ := m.options.url.Parse("./client/metrics") - resp, err := m.doPost(u, payload) - if err != nil { - m.err(err) - return - } - defer resp.Body.Close() - - if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusMultipleChoices { - if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusNotFound { - m.configurationError() - } else if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= http.StatusInternalServerError { - m.backoff() - } - m.warn(fmt.Errorf("%s return %d", u.String(), resp.StatusCode)) - // The post failed, re-add the metrics we attempted to send so - // they are included in the next post. - for name, tc := range bucket.Toggles { - m.add(name, true, tc.Yes) - m.add(name, false, tc.No) - } - - m.bucketMu.Lock() - // Set the start time of the current bucket to the one we - // attempted to send. - m.bucket.Start = bucket.Start - m.bucketMu.Unlock() - } else { - m.successfulPost() - m.sent <- payload - } -} - -func (m *metrics) doPost(url *url.URL, payload interface{}) (*http.Response, error) { - var body bytes.Buffer - enc := json.NewEncoder(&body) - if err := enc.Encode(payload); err != nil { - return nil, err - } - - req, err := http.NewRequest("POST", url.String(), &body) - if err != nil { - return nil, err - } - req = req.WithContext(m.ctx) - req.Header.Set("Content-Type", "application/json") - req.Header.Add("UNLEASH-APPNAME", m.options.appName) - req.Header.Add("UNLEASH-INSTANCEID", m.options.instanceId) - req.Header.Add("User-Agent", m.options.appName) - - for k, v := range m.options.customHeaders { - req.Header[k] = v - } - - return m.options.httpClient.Do(req) -} - -func (m *metrics) add(name string, enabled bool, num int32) { - if m.options.disableMetrics || num == 0 { - return - } - m.bucketMu.Lock() - defer m.bucketMu.Unlock() - t, exists := m.bucket.Toggles[name] - if !exists { - t = api.ToggleCount{ - Variants: map[string]int32{}, - } - } - if enabled { - t.Yes += num - } else { - t.No += num - } - m.bucket.Toggles[name] = t -} - -func (m *metrics) count(name string, enabled bool) { - if m.options.disableMetrics { - return - } - m.add(name, enabled, 1) - m.metricsChannels.count <- metric{Name: name, Enabled: enabled} -} - -func (m *metrics) countVariants(name string, enabled bool, variantName string) { - if m.options.disableMetrics { - return - } - - m.add(name, enabled, 1) - m.metricsChannels.count <- metric{Name: name, Enabled: enabled} - - m.bucketMu.Lock() - defer m.bucketMu.Unlock() - - t, _ := m.bucket.Toggles[name] - if len(t.Variants) == 0 { - t.Variants = make(map[string]int32) - } - - if _, ok := t.Variants[variantName]; !ok { - t.Variants[variantName] = 1 - } else { - t.Variants[variantName] += 1 - } - m.bucket.Toggles[name] = t -} - -func (m *metrics) resetBucket() api.Bucket { - prev := m.bucket - m.bucket = api.Bucket{ - Start: time.Now(), - Toggles: map[string]api.ToggleCount{}, - } - return prev -} - -func (m *metrics) getClientData() ClientData { - return ClientData{ - m.options.appName, - m.options.instanceId, - fmt.Sprintf("%s:%s", clientName, clientVersion), - m.options.strategies, - m.started, - int64(m.options.metricsInterval.Seconds()), - runtime.Version(), - "go", - nil, - specVersion, - } -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/nooplistener.go b/vendor/github.com/Unleash/unleash-client-go/v4/nooplistener.go deleted file mode 100644 index 64cf43273..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/nooplistener.go +++ /dev/null @@ -1,28 +0,0 @@ -package unleash - -// NoopListener is an implementation of all of the listener interfaces that discards -// all messages. It's added if no other listener is added to drain the channels and as -// an example of implementing the listener interfaces. -type NoopListener struct{} - -func (l NoopListener) OnError(err error) { -} - -func (l NoopListener) OnWarning(warning error) { -} - -// The repository is ready. -func (l NoopListener) OnReady() { -} - -// The feature is queried. -func (l NoopListener) OnCount(name string, enabled bool) { -} - -// The server has uploaded metrics. -func (l NoopListener) OnSent(payload MetricsData) { -} - -// The client has registered. -func (l NoopListener) OnRegistered(payload ClientData) { -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/repository.go b/vendor/github.com/Unleash/unleash-client-go/v4/repository.go deleted file mode 100644 index 7921f380c..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/repository.go +++ /dev/null @@ -1,228 +0,0 @@ -package unleash - -import ( - "context" - "encoding/json" - "fmt" - "math" - "net/http" - "net/url" - "sync" - "time" - - "github.com/Unleash/unleash-client-go/v4/api" -) - -var SEGMENT_CLIENT_SPEC_VERSION = "4.3.1" - -type repository struct { - repositoryChannels - sync.RWMutex - options repositoryOptions - etag string - close chan struct{} - closed chan struct{} - ctx context.Context - cancel func() - isReady bool - refreshTicker *time.Ticker - segments map[int][]api.Constraint - errors float64 - maxSkips float64 - skips float64 -} - -func newRepository(options repositoryOptions, channels repositoryChannels) *repository { - repo := &repository{ - options: options, - repositoryChannels: channels, - close: make(chan struct{}), - closed: make(chan struct{}), - refreshTicker: time.NewTicker(options.refreshInterval), - segments: map[int][]api.Constraint{}, - errors: 0, - maxSkips: 10, - skips: 0, - } - ctx, cancel := context.WithCancel(context.Background()) - repo.ctx = ctx - repo.cancel = cancel - - if options.httpClient == nil { - repo.options.httpClient = http.DefaultClient - } - - if options.storage == nil { - repo.options.storage = &DefaultStorage{} - } - - repo.options.storage.Init(options.backupPath, options.appName) - - go repo.sync() - - return repo -} - -func (r *repository) fetchAndReportError() { - err := r.fetch() - if err != nil { - if urlErr, ok := err.(*url.Error); !(ok && urlErr.Err == context.Canceled) { - r.err(err) - } - } - if !r.isReady && err == nil { - r.isReady = true - r.ready <- true - } -} - -func (r *repository) sync() { - r.fetchAndReportError() - for { - select { - case <-r.close: - if err := r.options.storage.Persist(); err != nil { - r.err(err) - } - close(r.closed) - return - case <-r.refreshTicker.C: - if r.skips == 0 { - r.fetchAndReportError() - } else { - r.decrementSkips() - } - } - } -} - -func (r *repository) backoff() { - r.errors = math.Min(r.maxSkips, r.errors+1) - r.skips = r.errors -} - -func (r *repository) successfulFetch() { - r.errors = math.Max(0, r.errors-1) - r.skips = r.errors -} - -func (r *repository) decrementSkips() { - r.skips = math.Max(0, r.skips-1) -} -func (r *repository) configurationError() { - r.errors = r.maxSkips - r.skips = r.errors -} - -func (r *repository) fetch() error { - u, _ := r.options.url.Parse(getFetchURLPath(r.options.projectName)) - - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - return err - } - req = req.WithContext(r.ctx) - - req.Header.Add("UNLEASH-APPNAME", r.options.appName) - req.Header.Add("UNLEASH-INSTANCEID", r.options.instanceId) - req.Header.Add("User-Agent", r.options.appName) - // Needs to reference a version of the client specifications that include - // global segments - req.Header.Add("Unleash-Client-Spec", SEGMENT_CLIENT_SPEC_VERSION) - - for k, v := range r.options.customHeaders { - req.Header[k] = v - } - - if r.etag != "" { - req.Header.Add("If-None-Match", r.etag) - } - - resp, err := r.options.httpClient.Do(req) - if err != nil { - return err - } - - defer resp.Body.Close() - - if resp.StatusCode == http.StatusNotModified { - return nil - } - if err := r.statusIsOK(resp); err != nil { - return err - } - - var featureResp api.FeatureResponse - dec := json.NewDecoder(resp.Body) - if err := dec.Decode(&featureResp); err != nil { - return err - } - - r.Lock() - r.etag = resp.Header.Get("Etag") - r.segments = featureResp.SegmentsMap() - r.options.storage.Reset(featureResp.FeatureMap(), true) - r.successfulFetch() - r.Unlock() - return nil -} - -func (r *repository) statusIsOK(resp *http.Response) error { - s := resp.StatusCode - if http.StatusOK <= s && s < http.StatusMultipleChoices { - return nil - } else if s == http.StatusUnauthorized || s == http.StatusForbidden || s == http.StatusNotFound { - r.configurationError() - return fmt.Errorf("%s %s returned status code %d your SDK is most likely misconfigured, backing off to maximum (%f times our interval)", resp.Request.Method, resp.Request.URL, s, r.maxSkips) - } else if s == http.StatusTooManyRequests || s >= http.StatusInternalServerError { - r.backoff() - return fmt.Errorf("%s %s returned status code %d, backing off (%f times our interval)", resp.Request.Method, resp.Request.URL, s, r.errors) - } - - return fmt.Errorf("%s %s returned status code %d", resp.Request.Method, resp.Request.URL, s) -} - -func (r *repository) getToggle(key string) *api.Feature { - r.RLock() - defer r.RUnlock() - - if toggle, found := r.options.storage.Get(key); found { - if feature, ok := toggle.(api.Feature); ok { - return &feature - } - } - return nil -} - -func (r *repository) resolveSegmentConstraints(strategy api.Strategy) ([]api.Constraint, error) { - segmentConstraints := []api.Constraint{} - - for _, segmentId := range strategy.Segments { - if resolvedConstraints, ok := r.segments[segmentId]; ok { - segmentConstraints = append(segmentConstraints, resolvedConstraints...) - } else { - return segmentConstraints, fmt.Errorf("segment does not exist") - } - } - - return segmentConstraints, nil -} - -func (r *repository) list() []api.Feature { - r.RLock() - defer r.RUnlock() - - var features []api.Feature - for _, feature := range r.options.storage.List() { - features = append(features, feature.(api.Feature)) - } - return features -} - -func (r *repository) Close() error { - close(r.close) - r.cancel() - <-r.closed - r.refreshTicker.Stop() - return nil -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/storage.go b/vendor/github.com/Unleash/unleash-client-go/v4/storage.go deleted file mode 100644 index 1d00401d5..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/storage.go +++ /dev/null @@ -1,102 +0,0 @@ -package unleash - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - - "github.com/Unleash/unleash-client-go/v4/api" -) - -// Storage is an interface that can be implemented in order to have control over how -// the repository of feature toggles is persisted. -type Storage interface { - // Init is called to initialize the storage implementation. The backupPath - // is used to specify the location the data should be stored and the appName - // can be used in naming. - Init(backupPath string, appName string) - - // Reset is called after the repository has fetched the feature toggles from the server. - // If persist is true the implementation of this function should call Persist(). The data - // passed in here should be owned by the implementer of this interface. - Reset(data map[string]interface{}, persist bool) error - - // Load is called to load the data from persistent storage and hold it in memory for fast - // querying. - Load() error - - // Persist is called when the data in the storage implementation should be persisted to disk. - Persist() error - - // Get returns the data for the specified feature toggle. - Get(string) (interface{}, bool) - - // List returns a list of all feature toggles. - List() []interface{} -} - -// DefaultStorage is a default Storage implementation. -type DefaultStorage struct { - appName string - path string - data map[string]interface{} -} - -func (ds *DefaultStorage) Init(backupPath, appName string) { - ds.appName = appName - ds.path = filepath.Join(backupPath, fmt.Sprintf("unleash-repo-schema-v1-%s.json", appName)) - ds.data = map[string]interface{}{} - ds.Load() -} - -func (ds *DefaultStorage) Reset(data map[string]interface{}, persist bool) error { - ds.data = data - if persist { - return ds.Persist() - } - return nil -} - -func (ds *DefaultStorage) Load() error { - if file, err := os.Open(ds.path); err != nil { - return err - } else { - dec := json.NewDecoder(file) - var featuresFromFile map[string]api.Feature - if err := dec.Decode(&featuresFromFile); err != nil { - return err - } - - for key, value := range featuresFromFile { - ds.data[key] = value - } - } - return nil -} - -func (ds *DefaultStorage) Persist() error { - if file, err := os.Create(ds.path); err != nil { - return err - } else { - defer file.Close() - enc := json.NewEncoder(file) - if err := enc.Encode(ds.data); err != nil { - return err - } - } - return nil -} - -func (ds DefaultStorage) Get(key string) (interface{}, bool) { - val, ok := ds.data[key] - return val, ok -} - -func (ds *DefaultStorage) List() []interface{} { - var features []interface{} - for _, val := range ds.data { - features = append(features, val) - } - return features -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/strategy/strategy.go b/vendor/github.com/Unleash/unleash-client-go/v4/strategy/strategy.go deleted file mode 100644 index dc99d8791..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/strategy/strategy.go +++ /dev/null @@ -1,37 +0,0 @@ -package strategy - -import "github.com/Unleash/unleash-client-go/v4/context" - -const ( - // ParamHostNames is a parameter indicating a comma separated list of hostnames. - ParamHostNames = "hostNames" - - // ParamPercentage is a property indicating a percentage. - ParamPercentage = "percentage" - - // ParamGroupId is a property indicating a group ID. - ParamGroupId = "groupId" - - // ParamIps is a property indicating a comma separated list of ip addresses. - ParamIps = "IPs" - - // ParamUserIds is a property indicating a comma separated list of user ids. - ParamUserIds = "userIds" - - // ParamStickiness indicates which context property is sticky. - ParamStickiness = "stickiness" - - // ParamRollout is a property indicating a rollout percentage. - ParamRollout = "rollout" -) - -// Strategy is an interface for defining new custom strategies. -type Strategy interface { - // Name should return name of the strategy. - Name() string - - // IsEnabled should look at the map of parameters and optionally - // the supplied context and return true if the feature should be - // enabled. - IsEnabled(map[string]interface{}, *context.Context) bool -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/unleash.go b/vendor/github.com/Unleash/unleash-client-go/v4/unleash.go deleted file mode 100644 index c4c36eb83..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/unleash.go +++ /dev/null @@ -1,74 +0,0 @@ -package unleash - -import "github.com/Unleash/unleash-client-go/v4/api" - -var defaultClient *Client - -// ErrorListener defines an interface that be implemented in order to receive -// errors and warnings from the client. -type ErrorListener interface { - // OnError is called whenever the client experiences an error. - OnError(error) - - // OnWarning is called whenever the client experiences a warning. - OnWarning(error) -} - -// MetricListener defines an interface that can be implemented in order to receive -// events that are relevant to sending metrics. -type MetricListener interface { - // OnCount is called whenever the specified feature is queried. - OnCount(string, bool) - - // OnSent is called whenever the server has successfully sent metrics to the server. - OnSent(MetricsData) - - // OnRegistered is called whenever the client has successfully registered with the metrics server. - OnRegistered(ClientData) -} - -// RepositoryListener defines an interface that can be implemented in order to receive events that are relevant to -// the feature toggle repository. -type RepositoryListener interface { - // OnReady is called when the client has loaded the feature toggles from - // the Unleash server. - OnReady() -} - -// IsEnabled queries the default client whether or not the specified feature is enabled or not. -func IsEnabled(feature string, options ...FeatureOption) bool { - if defaultClient == nil { - var opts featureOption - for _, o := range options { - o(&opts) - } - return handleFallback(opts, feature, opts.ctx).Enabled - } - return defaultClient.IsEnabled(feature, options...) -} - -// Initialize will specify the options to be used by the default client. -func Initialize(options ...ConfigOption) (err error) { - defaultClient, err = NewClient(options...) - return -} - -func GetVariant(feature string, options ...VariantOption) *api.Variant { - if defaultClient == nil { - return api.GetDefaultVariant() - } - return defaultClient.GetVariant(feature, options...) -} - -// Close will close the default client. -func Close() error { - if defaultClient == nil { - return nil - } - return defaultClient.Close() -} - -// WaitForReady will block until the default client is ready or return immediately. -func WaitForReady() { - defaultClient.WaitForReady() -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/unleash_mock.go b/vendor/github.com/Unleash/unleash-client-go/v4/unleash_mock.go deleted file mode 100644 index 76be4de4e..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/unleash_mock.go +++ /dev/null @@ -1,49 +0,0 @@ -package unleash - -import ( - "encoding/json" - "net/http" - - "github.com/stretchr/testify/mock" -) - -const ( - mockerServer = "http://foo.com" - mockAppName = "unleash-client-go-tests" - mockInstanceId = "1234" -) - -type MockedListener struct { - mock.Mock -} - -func (l *MockedListener) OnError(err error) { - l.Called(err) -} - -func (l *MockedListener) OnWarning(warning error) { - l.Called(warning) -} - -func (l *MockedListener) OnReady() { - l.Called() -} - -func (l *MockedListener) OnCount(name string, enabled bool) { - l.Called(name, enabled) -} - -func (l *MockedListener) OnSent(payload MetricsData) { - l.Called(payload) -} - -func (l *MockedListener) OnRegistered(payload ClientData) { - l.Called(payload) -} - -func writeJSON(rw http.ResponseWriter, x interface{}) { - enc := json.NewEncoder(rw) - if err := enc.Encode(x); err != nil { - panic(err) - } -} diff --git a/vendor/github.com/Unleash/unleash-client-go/v4/utils.go b/vendor/github.com/Unleash/unleash-client-go/v4/utils.go deleted file mode 100644 index 7021925f6..000000000 --- a/vendor/github.com/Unleash/unleash-client-go/v4/utils.go +++ /dev/null @@ -1,80 +0,0 @@ -package unleash - -import ( - "fmt" - "math/rand" - "os" - "os/user" - "reflect" - "sync" - "time" -) - -func getTmpDirPath() string { - return os.TempDir() -} - -func generateInstanceId() string { - prefix := "" - - if user, err := user.Current(); err == nil && user.Username != "" { - prefix = user.Username - } else { - rand.Seed(time.Now().Unix()) - prefix = fmt.Sprintf("generated-%d-%d", rand.Intn(1000000), os.Getpid()) - } - - if hostname, err := os.Hostname(); err == nil && hostname != "" { - return fmt.Sprintf("%s-%s", prefix, hostname) - } - return prefix -} - -func getFetchURLPath(projectName string) string { - if projectName != "" { - return fmt.Sprintf("./client/features?project=%s", projectName) - } - return "./client/features" -} - -func contains(arr []string, str string) bool { - for _, item := range arr { - if item == str { - return true - } - } - return false -} - -// WarnOnce is a type for handling warnings that should only be displayed once. -type WarnOnce struct { - once sync.Once -} - -// Warn logs the warning message once. -func (wo *WarnOnce) Warn(message string) { - wo.once.Do(func() { - fmt.Println("Warning:", message) - }) -} - -func every(slice interface{}, condition func(interface{}) bool) bool { - sliceValue := reflect.ValueOf(slice) - - if sliceValue.Kind() != reflect.Slice { - fmt.Println("Input is not a slice returning false") - return false - } - - if sliceValue.Len() == 0 { - return false - } - - for i := 0; i < sliceValue.Len(); i++ { - element := sliceValue.Index(i).Interface() - if !condition(element) { - return false - } - } - return true -} diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/.editorconfig b/vendor/github.com/apapsch/go-jsonmerge/v2/.editorconfig deleted file mode 100644 index fbb2c8f36..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/.editorconfig +++ /dev/null @@ -1,6 +0,0 @@ -[*] -end_of_line = lf -insert_final_newline = true - -[*.{cmd,bat}] -end_of_line = crlf diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/.gitattributes b/vendor/github.com/apapsch/go-jsonmerge/v2/.gitattributes deleted file mode 100644 index 9be55028c..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/.gitattributes +++ /dev/null @@ -1,175 +0,0 @@ -## AUTO-DETECT - Handle line endings automatically for files detected -## as text and leave all files detected as binary untouched. -## This will handle all files NOT defined below. -* text=auto - -# Custom for Visual Studio -*.sln text eol=crlf -*.csproj text eol=crlf -*.vbproj text eol=crlf -*.fsproj text eol=crlf -*.dbproj text eol=crlf - -*.vcxproj text eol=crlf -*.vcxitems text eol=crlf -*.props text eol=crlf -*.filters text eol=crlf - -# Documents -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain -*.csv text -*.sql text -*.ini text - -## SOURCE CODE -*.go text eol=lf -*.c text eol=lf -*.h text eol=lf -*.bat text eol=crlf -*.cmd text eol=crlf -*.coffee text eol=lf - -*.htm text diff=html -*.html text diff=html -*.xml text diff=html -*.xhtml text diff=html - -*.js text eol=lf -*.jsx text eol=lf -*.json text eol=lf -*.ts text eol=lf - -*.css text diff=css eol=lf -*.scss text diff=css eol=lf -*.less text diff=css eol=lf -*.sass text eol=lf - -*.sh text eol=lf - -## DOCUMENTATION -*.md text eol=lf -*.txt text -AUTHORS text eol=lf -CHANGELOG text eol=lf -CHANGES text eol=lf -CONTRIBUTING text eol=lf -COPYING text eol=lf -INSTALL text eol=lf -license text eol=lf -LICENSE text eol=lf -NEWS text eol=lf -readme text eol=lf -*README* text eol=lf -TODO text eol=lf - -## TEMPLATES -*.dot text -*.ejs text -*.haml text -*.handlebars text -*.hbs text -*.hbt text -*.jade text -*.latte text -*.mustache text -*.tmpl text - -## LINTERS -.csslintrc text eol=lf -.eslintrc text eol=lf -.jscsrc text eol=lf -.jshintrc text eol=lf -.jshintignore text eol=lf -.stylelintrc text eol=lf - -## CONFIGS -*.bowerrc text eol=lf -*.cnf text -*.conf text -*.config text -.editorconfig text eol=lf -.gitattributes text eol=lf -.gitconfig text eol=lf -.gitignore text eol=lf -*.npmignore text eol=lf -*.yaml text eol=lf -*.yml text eol=lf -Makefile text eol=lf -makefile text eol=lf - -## GRAPHICS -*.ai binary -*.bmp binary -*.eps binary -*.gif binary -*.ico binary -*.jng binary -*.jp2 binary -*.jpg binary -*.jpeg binary -*.jpx binary -*.jxr binary -*.pdf binary -*.png binary -*.psb binary -*.psd binary -*.svg text -*.svgz binary -*.tif binary -*.tiff binary -*.wbmp binary -*.webp binary - -## AUDIO -*.kar binary -*.m4a binary -*.mid binary -*.midi binary -*.mp3 binary -*.ogg binary -*.ra binary - -## VIDEO -*.3gpp binary -*.3gp binary -*.as binary -*.asf binary -*.asx binary -*.fla binary -*.flv binary -*.m4v binary -*.mng binary -*.mov binary -*.mp4 binary -*.mpeg binary -*.mpg binary -*.swc binary -*.swf binary -*.webm binary - -## ARCHIVES -*.7z binary -*.gz binary -*.rar binary -*.tar binary -*.zip binary - -## FONTS -*.ttf binary -*.eot binary -*.otf binary -*.woff binary -*.woff2 binary - -## EXECUTABLES -*.exe binary -*.dll binary diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/.gitignore b/vendor/github.com/apapsch/go-jsonmerge/v2/.gitignore deleted file mode 100644 index 5efe425bd..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -# GoLand -/.idea/ - -/vendor/ - -/cmd/cmd.exe -/cmd/cmd - -/artifacts/ -/test/ -/cmd/test/ diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/.gitlab-ci.yml b/vendor/github.com/apapsch/go-jsonmerge/v2/.gitlab-ci.yml deleted file mode 100644 index a0d178f93..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/.gitlab-ci.yml +++ /dev/null @@ -1,42 +0,0 @@ -variables: - GOPROJ: "github.com/RaveNoX/go-jsonmerge" - - -stages: -- test -- build - -test: - tags: - - docker - - linux - image: golang:latest - stage: test - script: - - mkdir -p artifacts - - go test -cover -v -coverprofile="./artifacts/cover.out" ./ - - go tool cover -html="./artifacts/cover.out" -o "./artifacts/cover.htm" - - go test -cover -v -coverprofile="./artifacts/cover_cmd.out" ./cmd/jsonmerge - - go tool cover -html="./artifacts/cover_cmd.out" -o "./artifacts/cover_cmd.htm" - artifacts: - paths: - - artifacts/* - -build: - stage: build - tags: - - docker - - linux - image: golang:latest - script: - - mkdir -p artifacts - - echo "Building for Linux" - - GOOS=linux GOARCH=amd64 go build -o artifacts/jsonmerge ./cmd/jsonmerge - - echo "Building for MacOS (darwin)" - - GOOS=darwin GOARCH=amd64 go build -o artifacts/jsonmerge_darwin ./cmd/jsonmerge - - echo "Building for Windows" - - GOOS=windows GOARCH=amd64 go build -o artifacts/jsonmerge.exe ./cmd/jsonmerge - artifacts: - paths: - - artifacts/* - diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/.travis.yml b/vendor/github.com/apapsch/go-jsonmerge/v2/.travis.yml deleted file mode 100644 index eae1a8a26..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go - -go: -- 1.x - -install: -- mkdir -p artifacts - -env: - - GO111MODULE=on - -script: -- go test -cover -v -coverprofile="./artifacts/cover.out" ./ -- go tool cover -html="./artifacts/cover.out" -o "./artifacts/cover.htm" -- go test -cover -v -coverprofile="./artifacts/cover_cmd.out" ./cmd/jsonmerge -- go tool cover -html="./artifacts/cover_cmd.out" -o "./artifacts/cover_cmd.htm" -- GOARCH=amd64 GOOS=linux go build -o artifacts/jsonmerge ./cmd/jsonmerge -- GOARCH=amd64 GOOS=windows go build -o artifacts/jsonmerge.exe ./cmd/jsonmerge -- GOARCH=amd64 GOOS=darwin go build -o artifacts/jsonmerge_darwin ./cmd/jsonmerge diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/LICENSE b/vendor/github.com/apapsch/go-jsonmerge/v2/LICENSE deleted file mode 100644 index f23057e46..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016-2019 Artur Kraev - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/README.md b/vendor/github.com/apapsch/go-jsonmerge/v2/README.md deleted file mode 100644 index e11bd4c48..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# go-jsonmerge -[![Build Status](https://travis-ci.org/RaveNoX/go-jsonmerge.svg?branch=master)](https://travis-ci.org/RaveNoX/go-jsonmerge) -[![GoDoc](https://godoc.org/github.com/RaveNoX/go-jsonmerge?status.svg)](https://godoc.org/github.com/RaveNoX/go-jsonmerge) - -GO library for merging JSON objects - -## Original document -```json -{ - "number": 1, - "string": "value", - "object": { - "number": 1, - "string": "value", - "nested object": { - "number": 2 - }, - "array": [1, 2, 3], - "partial_array": [1, 2, 3] - } -} -``` - -## Patch -```json -{ - "number": 2, - "string": "value1", - "nonexitent": "woot", - "object": { - "number": 3, - "string": "value2", - "nested object": { - "number": 4 - }, - "array": [3, 2, 1], - "partial_array": { - "1": 4 - } - } -} -``` - -## Result -```json -{ - "number": 2, - "string": "value1", - "object": { - "number": 3, - "string": "value2", - "nested object": { - "number": 4 - }, - "array": [3, 2, 1], - "partial_array": [1, 4, 3] - } -} -``` - -## Commandline Tool - -```bash -$ go get -u github.com/RaveNoX/go-jsonmerge/cmd/jsonmerge -$ jsonmerge [options] ... -# For help -$ jsonmerge -h -``` - -## Development -``` -# Install depencencies -./init.sh - -# Build -./build.sh -``` - - -## License -[MIT](./LICENSE.MD) diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/build.cmd b/vendor/github.com/apapsch/go-jsonmerge/v2/build.cmd deleted file mode 100644 index ebd987673..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/build.cmd +++ /dev/null @@ -1,25 +0,0 @@ -@ECHO OFF -setlocal - -set GOARCH=amd64 - -cd %~dp0 -md artifacts - -echo Windows -set GOOS=windows -call go build -o artifacts\jsonmerge.exe .\cmd || goto :error - -echo Linux -set GOOS=linux -call go build -o artifacts\jsonmerge .\cmd || goto :error - -echo Darwin -set GOOS=darwin -call go build -o artifacts\jsonmerge_darwin .\cmd || goto :error - -echo Build done -exit - -:error -exit /b %errorlevel% diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/build.sh b/vendor/github.com/apapsch/go-jsonmerge/v2/build.sh deleted file mode 100644 index 29be8924c..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/build.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh - -set -e - -MY_DIR=$(dirname "$0") - -cd "${MY_DIR}" -mkdir -p "artifacts" - -echo "Linux" -GOARCH=amd64 GOOS=linux go build -o "artifacts/jsonmerge" ./cmd - -echo "Windows" -GOARCH=amd64 GOOS=windows go build -o "artifacts/jsonmerge.exe" ./cmd - -echo "Mac(darwin)" -GOARCH=amd64 GOOS=darwin go build -o "artifacts/jsonmerge_darwin" ./cmd - -echo "Build done" diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/doc.go b/vendor/github.com/apapsch/go-jsonmerge/v2/doc.go deleted file mode 100644 index 5bd6e15eb..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/doc.go +++ /dev/null @@ -1,52 +0,0 @@ -// Package jsonmerge helps mergeing JSON objects -// -// For example you have this documents: -// -// original.json -// { -// "number": 1, -// "string": "value", -// "object": { -// "number": 1, -// "string": "value", -// "nested object": { -// "number": 2 -// }, -// "array": [1, 2, 3], -// "partial_array": [1, 2, 3] -// } -// } -// -// patch.json -// { -// "number": 2, -// "string": "value1", -// "nonexitent": "woot", -// "object": { -// "number": 3, -// "string": "value2", -// "nested object": { -// "number": 4 -// }, -// "array": [3, 2, 1], -// "partial_array": { -// "1": 4 -// } -// } -// } -// -// After merge you will have this result: -// { -// "number": 2, -// "string": "value1", -// "object": { -// "number": 3, -// "string": "value2", -// "nested object": { -// "number": 4 -// }, -// "array": [3, 2, 1], -// "partial_array": [1, 4, 3] -// } -// } -package jsonmerge diff --git a/vendor/github.com/apapsch/go-jsonmerge/v2/merge.go b/vendor/github.com/apapsch/go-jsonmerge/v2/merge.go deleted file mode 100644 index 8ba052f18..000000000 --- a/vendor/github.com/apapsch/go-jsonmerge/v2/merge.go +++ /dev/null @@ -1,167 +0,0 @@ -package jsonmerge - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strconv" - "strings" -) - -// Merger describes result of merge operation and provides -// configuration. -type Merger struct { - // Errors is slice of non-critical errors of merge operations - Errors []error - // Replaced is describe replacements - // Key is path in document like - // "prop1.prop2.prop3" for object properties or - // "arr1.1.prop" for arrays - // Value is value of replacemet - Replaced map[string]interface{} - // CopyNonexistent enables setting fields into the result - // which only exist in the patch. - CopyNonexistent bool -} - -func (m *Merger) mergeValue(path []string, patch map[string]interface{}, key string, value interface{}) interface{} { - patchValue, patchHasValue := patch[key] - - if !patchHasValue { - return value - } - - _, patchValueIsObject := patchValue.(map[string]interface{}) - - path = append(path, key) - pathStr := strings.Join(path, ".") - - if _, ok := value.(map[string]interface{}); ok { - if !patchValueIsObject { - err := fmt.Errorf("patch value must be object for key \"%v\"", pathStr) - m.Errors = append(m.Errors, err) - return value - } - - return m.mergeObjects(value, patchValue, path) - } - - if _, ok := value.([]interface{}); ok && patchValueIsObject { - return m.mergeObjects(value, patchValue, path) - } - - if !reflect.DeepEqual(value, patchValue) { - m.Replaced[pathStr] = patchValue - } - - return patchValue -} - -func (m *Merger) mergeObjects(data, patch interface{}, path []string) interface{} { - if patchObject, ok := patch.(map[string]interface{}); ok { - if dataArray, ok := data.([]interface{}); ok { - ret := make([]interface{}, len(dataArray)) - - for i, val := range dataArray { - ret[i] = m.mergeValue(path, patchObject, strconv.Itoa(i), val) - } - - return ret - } else if dataObject, ok := data.(map[string]interface{}); ok { - ret := make(map[string]interface{}) - - for k, v := range dataObject { - ret[k] = m.mergeValue(path, patchObject, k, v) - } - if m.CopyNonexistent { - for k, v := range patchObject { - if _, ok := dataObject[k]; !ok { - ret[k] = v - } - } - } - - return ret - } - } - - return data -} - -// Merge merges patch document to data document -// -// Returning merged document. Result of merge operation can be -// obtained from the Merger. Result information is discarded before -// merging. -func (m *Merger) Merge(data, patch interface{}) interface{} { - m.Replaced = make(map[string]interface{}) - m.Errors = make([]error, 0) - return m.mergeObjects(data, patch, nil) -} - -// MergeBytesIndent merges patch document buffer to data document buffer -// -// Use prefix and indent for set indentation like in json.MarshalIndent -// -// Returning merged document buffer and error if any. -func (m *Merger) MergeBytesIndent(dataBuff, patchBuff []byte, prefix, indent string) (mergedBuff []byte, err error) { - var data, patch, merged interface{} - - err = unmarshalJSON(dataBuff, &data) - if err != nil { - err = fmt.Errorf("error in data JSON: %v", err) - return - } - - err = unmarshalJSON(patchBuff, &patch) - if err != nil { - err = fmt.Errorf("error in patch JSON: %v", err) - return - } - - merged = m.Merge(data, patch) - - mergedBuff, err = json.MarshalIndent(merged, prefix, indent) - if err != nil { - err = fmt.Errorf("error writing merged JSON: %v", err) - } - - return -} - -// MergeBytes merges patch document buffer to data document buffer -// -// Returning merged document buffer, merge info and -// error if any -func (m *Merger) MergeBytes(dataBuff, patchBuff []byte) (mergedBuff []byte, err error) { - var data, patch, merged interface{} - - err = unmarshalJSON(dataBuff, &data) - if err != nil { - err = fmt.Errorf("error in data JSON: %v", err) - return - } - - err = unmarshalJSON(patchBuff, &patch) - if err != nil { - err = fmt.Errorf("error in patch JSON: %v", err) - return - } - - merged = m.Merge(data, patch) - - mergedBuff, err = json.Marshal(merged) - if err != nil { - err = fmt.Errorf("error writing merged JSON: %v", err) - } - - return -} - -func unmarshalJSON(buff []byte, data interface{}) error { - decoder := json.NewDecoder(bytes.NewReader(buff)) - decoder.UseNumber() - - return decoder.Decode(data) -} diff --git a/vendor/github.com/aws/aws-sdk-go/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go/LICENSE.txt +++ /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/vendor/github.com/aws/aws-sdk-go/NOTICE.txt b/vendor/github.com/aws/aws-sdk-go/NOTICE.txt deleted file mode 100644 index 899129ecc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/NOTICE.txt +++ /dev/null @@ -1,3 +0,0 @@ -AWS SDK for Go -Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. -Copyright 2014-2015 Stripe, Inc. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/auth/bearer/token.go b/vendor/github.com/aws/aws-sdk-go/aws/auth/bearer/token.go deleted file mode 100644 index dd950a286..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/auth/bearer/token.go +++ /dev/null @@ -1,50 +0,0 @@ -package bearer - -import ( - "github.com/aws/aws-sdk-go/aws" - "time" -) - -// Token provides a type wrapping a bearer token and expiration metadata. -type Token struct { - Value string - - CanExpire bool - Expires time.Time -} - -// Expired returns if the token's Expires time is before or equal to the time -// provided. If CanExpire is false, Expired will always return false. -func (t Token) Expired(now time.Time) bool { - if !t.CanExpire { - return false - } - now = now.Round(0) - return now.Equal(t.Expires) || now.After(t.Expires) -} - -// TokenProvider provides interface for retrieving bearer tokens. -type TokenProvider interface { - RetrieveBearerToken(aws.Context) (Token, error) -} - -// TokenProviderFunc provides a helper utility to wrap a function as a type -// that implements the TokenProvider interface. -type TokenProviderFunc func(aws.Context) (Token, error) - -// RetrieveBearerToken calls the wrapped function, returning the Token or -// error. -func (fn TokenProviderFunc) RetrieveBearerToken(ctx aws.Context) (Token, error) { - return fn(ctx) -} - -// StaticTokenProvider provides a utility for wrapping a static bearer token -// value within an implementation of a token provider. -type StaticTokenProvider struct { - Token Token -} - -// RetrieveBearerToken returns the static token specified. -func (s StaticTokenProvider) RetrieveBearerToken(aws.Context) (Token, error) { - return s.Token, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go b/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go deleted file mode 100644 index 99849c0e1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go +++ /dev/null @@ -1,164 +0,0 @@ -// Package awserr represents API error interface accessors for the SDK. -package awserr - -// An Error wraps lower level errors with code, message and an original error. -// The underlying concrete error type may also satisfy other interfaces which -// can be to used to obtain more specific information about the error. -// -// Calling Error() or String() will always include the full information about -// an error based on its underlying type. -// -// Example: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if awsErr, ok := err.(awserr.Error); ok { -// // Get error details -// log.Println("Error:", awsErr.Code(), awsErr.Message()) -// -// // Prints out full error message, including original error if there was one. -// log.Println("Error:", awsErr.Error()) -// -// // Get original error -// if origErr := awsErr.OrigErr(); origErr != nil { -// // operate on original error. -// } -// } else { -// fmt.Println(err.Error()) -// } -// } -// -type Error interface { - // Satisfy the generic error interface. - error - - // Returns the short phrase depicting the classification of the error. - Code() string - - // Returns the error details message. - Message() string - - // Returns the original error if one was set. Nil is returned if not set. - OrigErr() error -} - -// BatchError is a batch of errors which also wraps lower level errors with -// code, message, and original errors. Calling Error() will include all errors -// that occurred in the batch. -// -// Deprecated: Replaced with BatchedErrors. Only defined for backwards -// compatibility. -type BatchError interface { - // Satisfy the generic error interface. - error - - // Returns the short phrase depicting the classification of the error. - Code() string - - // Returns the error details message. - Message() string - - // Returns the original error if one was set. Nil is returned if not set. - OrigErrs() []error -} - -// BatchedErrors is a batch of errors which also wraps lower level errors with -// code, message, and original errors. Calling Error() will include all errors -// that occurred in the batch. -// -// Replaces BatchError -type BatchedErrors interface { - // Satisfy the base Error interface. - Error - - // Returns the original error if one was set. Nil is returned if not set. - OrigErrs() []error -} - -// New returns an Error object described by the code, message, and origErr. -// -// If origErr satisfies the Error interface it will not be wrapped within a new -// Error object and will instead be returned. -func New(code, message string, origErr error) Error { - var errs []error - if origErr != nil { - errs = append(errs, origErr) - } - return newBaseError(code, message, errs) -} - -// NewBatchError returns an BatchedErrors with a collection of errors as an -// array of errors. -func NewBatchError(code, message string, errs []error) BatchedErrors { - return newBaseError(code, message, errs) -} - -// A RequestFailure is an interface to extract request failure information from -// an Error such as the request ID of the failed request returned by a service. -// RequestFailures may not always have a requestID value if the request failed -// prior to reaching the service such as a connection error. -// -// Example: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if reqerr, ok := err.(RequestFailure); ok { -// log.Println("Request failed", reqerr.Code(), reqerr.Message(), reqerr.RequestID()) -// } else { -// log.Println("Error:", err.Error()) -// } -// } -// -// Combined with awserr.Error: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if awsErr, ok := err.(awserr.Error); ok { -// // Generic AWS Error with Code, Message, and original error (if any) -// fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) -// -// if reqErr, ok := err.(awserr.RequestFailure); ok { -// // A service error occurred -// fmt.Println(reqErr.StatusCode(), reqErr.RequestID()) -// } -// } else { -// fmt.Println(err.Error()) -// } -// } -// -type RequestFailure interface { - Error - - // The status code of the HTTP response. - StatusCode() int - - // The request ID returned by the service for a request failure. This will - // be empty if no request ID is available such as the request failed due - // to a connection error. - RequestID() string -} - -// NewRequestFailure returns a wrapped error with additional information for -// request status code, and service requestID. -// -// Should be used to wrap all request which involve service requests. Even if -// the request failed without a service response, but had an HTTP status code -// that may be meaningful. -func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure { - return newRequestError(err, statusCode, reqID) -} - -// UnmarshalError provides the interface for the SDK failing to unmarshal data. -type UnmarshalError interface { - awsError - Bytes() []byte -} - -// NewUnmarshalError returns an initialized UnmarshalError error wrapper adding -// the bytes that fail to unmarshal to the error. -func NewUnmarshalError(err error, msg string, bytes []byte) UnmarshalError { - return &unmarshalError{ - awsError: New("UnmarshalError", msg, err), - bytes: bytes, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go b/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go deleted file mode 100644 index 9cf7eaf40..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go +++ /dev/null @@ -1,221 +0,0 @@ -package awserr - -import ( - "encoding/hex" - "fmt" -) - -// SprintError returns a string of the formatted error code. -// -// Both extra and origErr are optional. If they are included their lines -// will be added, but if they are not included their lines will be ignored. -func SprintError(code, message, extra string, origErr error) string { - msg := fmt.Sprintf("%s: %s", code, message) - if extra != "" { - msg = fmt.Sprintf("%s\n\t%s", msg, extra) - } - if origErr != nil { - msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error()) - } - return msg -} - -// A baseError wraps the code and message which defines an error. It also -// can be used to wrap an original error object. -// -// Should be used as the root for errors satisfying the awserr.Error. Also -// for any error which does not fit into a specific error wrapper type. -type baseError struct { - // Classification of error - code string - - // Detailed information about error - message string - - // Optional original error this error is based off of. Allows building - // chained errors. - errs []error -} - -// newBaseError returns an error object for the code, message, and errors. -// -// code is a short no whitespace phrase depicting the classification of -// the error that is being created. -// -// message is the free flow string containing detailed information about the -// error. -// -// origErrs is the error objects which will be nested under the new errors to -// be returned. -func newBaseError(code, message string, origErrs []error) *baseError { - b := &baseError{ - code: code, - message: message, - errs: origErrs, - } - - return b -} - -// Error returns the string representation of the error. -// -// See ErrorWithExtra for formatting. -// -// Satisfies the error interface. -func (b baseError) Error() string { - size := len(b.errs) - if size > 0 { - return SprintError(b.code, b.message, "", errorList(b.errs)) - } - - return SprintError(b.code, b.message, "", nil) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (b baseError) String() string { - return b.Error() -} - -// Code returns the short phrase depicting the classification of the error. -func (b baseError) Code() string { - return b.code -} - -// Message returns the error details message. -func (b baseError) Message() string { - return b.message -} - -// OrigErr returns the original error if one was set. Nil is returned if no -// error was set. This only returns the first element in the list. If the full -// list is needed, use BatchedErrors. -func (b baseError) OrigErr() error { - switch len(b.errs) { - case 0: - return nil - case 1: - return b.errs[0] - default: - if err, ok := b.errs[0].(Error); ok { - return NewBatchError(err.Code(), err.Message(), b.errs[1:]) - } - return NewBatchError("BatchedErrors", - "multiple errors occurred", b.errs) - } -} - -// OrigErrs returns the original errors if one was set. An empty slice is -// returned if no error was set. -func (b baseError) OrigErrs() []error { - return b.errs -} - -// So that the Error interface type can be included as an anonymous field -// in the requestError struct and not conflict with the error.Error() method. -type awsError Error - -// A requestError wraps a request or service error. -// -// Composed of baseError for code, message, and original error. -type requestError struct { - awsError - statusCode int - requestID string - bytes []byte -} - -// newRequestError returns a wrapped error with additional information for -// request status code, and service requestID. -// -// Should be used to wrap all request which involve service requests. Even if -// the request failed without a service response, but had an HTTP status code -// that may be meaningful. -// -// Also wraps original errors via the baseError. -func newRequestError(err Error, statusCode int, requestID string) *requestError { - return &requestError{ - awsError: err, - statusCode: statusCode, - requestID: requestID, - } -} - -// Error returns the string representation of the error. -// Satisfies the error interface. -func (r requestError) Error() string { - extra := fmt.Sprintf("status code: %d, request id: %s", - r.statusCode, r.requestID) - return SprintError(r.Code(), r.Message(), extra, r.OrigErr()) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (r requestError) String() string { - return r.Error() -} - -// StatusCode returns the wrapped status code for the error -func (r requestError) StatusCode() int { - return r.statusCode -} - -// RequestID returns the wrapped requestID -func (r requestError) RequestID() string { - return r.requestID -} - -// OrigErrs returns the original errors if one was set. An empty slice is -// returned if no error was set. -func (r requestError) OrigErrs() []error { - if b, ok := r.awsError.(BatchedErrors); ok { - return b.OrigErrs() - } - return []error{r.OrigErr()} -} - -type unmarshalError struct { - awsError - bytes []byte -} - -// Error returns the string representation of the error. -// Satisfies the error interface. -func (e unmarshalError) Error() string { - extra := hex.Dump(e.bytes) - return SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (e unmarshalError) String() string { - return e.Error() -} - -// Bytes returns the bytes that failed to unmarshal. -func (e unmarshalError) Bytes() []byte { - return e.bytes -} - -// An error list that satisfies the golang interface -type errorList []error - -// Error returns the string representation of the error. -// -// Satisfies the error interface. -func (e errorList) Error() string { - msg := "" - // How do we want to handle the array size being zero - if size := len(e); size > 0 { - for i := 0; i < size; i++ { - msg += e[i].Error() - // We check the next index to see if it is within the slice. - // If it is, then we append a newline. We do this, because unit tests - // could be broken with the additional '\n' - if i+1 < size { - msg += "\n" - } - } - } - return msg -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go deleted file mode 100644 index 1a3d106d5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go +++ /dev/null @@ -1,108 +0,0 @@ -package awsutil - -import ( - "io" - "reflect" - "time" -) - -// Copy deeply copies a src structure to dst. Useful for copying request and -// response structures. -// -// Can copy between structs of different type, but will only copy fields which -// are assignable, and exist in both structs. Fields which are not assignable, -// or do not exist in both structs are ignored. -func Copy(dst, src interface{}) { - dstval := reflect.ValueOf(dst) - if !dstval.IsValid() { - panic("Copy dst cannot be nil") - } - - rcopy(dstval, reflect.ValueOf(src), true) -} - -// CopyOf returns a copy of src while also allocating the memory for dst. -// src must be a pointer type or this operation will fail. -func CopyOf(src interface{}) (dst interface{}) { - dsti := reflect.New(reflect.TypeOf(src).Elem()) - dst = dsti.Interface() - rcopy(dsti, reflect.ValueOf(src), true) - return -} - -// rcopy performs a recursive copy of values from the source to destination. -// -// root is used to skip certain aspects of the copy which are not valid -// for the root node of a object. -func rcopy(dst, src reflect.Value, root bool) { - if !src.IsValid() { - return - } - - switch src.Kind() { - case reflect.Ptr: - if _, ok := src.Interface().(io.Reader); ok { - if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() { - dst.Elem().Set(src) - } else if dst.CanSet() { - dst.Set(src) - } - } else { - e := src.Type().Elem() - if dst.CanSet() && !src.IsNil() { - if _, ok := src.Interface().(*time.Time); !ok { - dst.Set(reflect.New(e)) - } else { - tempValue := reflect.New(e) - tempValue.Elem().Set(src.Elem()) - // Sets time.Time's unexported values - dst.Set(tempValue) - } - } - if src.Elem().IsValid() { - // Keep the current root state since the depth hasn't changed - rcopy(dst.Elem(), src.Elem(), root) - } - } - case reflect.Struct: - t := dst.Type() - for i := 0; i < t.NumField(); i++ { - name := t.Field(i).Name - srcVal := src.FieldByName(name) - dstVal := dst.FieldByName(name) - if srcVal.IsValid() && dstVal.CanSet() { - rcopy(dstVal, srcVal, false) - } - } - case reflect.Slice: - if src.IsNil() { - break - } - - s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap()) - dst.Set(s) - for i := 0; i < src.Len(); i++ { - rcopy(dst.Index(i), src.Index(i), false) - } - case reflect.Map: - if src.IsNil() { - break - } - - s := reflect.MakeMap(src.Type()) - dst.Set(s) - for _, k := range src.MapKeys() { - v := src.MapIndex(k) - v2 := reflect.New(v.Type()).Elem() - rcopy(v2, v, false) - dst.SetMapIndex(k, v2) - } - default: - // Assign the value if possible. If its not assignable, the value would - // need to be converted and the impact of that may be unexpected, or is - // not compatible with the dst type. - if src.Type().AssignableTo(dst.Type()) { - dst.Set(src) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go deleted file mode 100644 index 142a7a01c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go +++ /dev/null @@ -1,27 +0,0 @@ -package awsutil - -import ( - "reflect" -) - -// DeepEqual returns if the two values are deeply equal like reflect.DeepEqual. -// In addition to this, this method will also dereference the input values if -// possible so the DeepEqual performed will not fail if one parameter is a -// pointer and the other is not. -// -// DeepEqual will not perform indirection of nested values of the input parameters. -func DeepEqual(a, b interface{}) bool { - ra := reflect.Indirect(reflect.ValueOf(a)) - rb := reflect.Indirect(reflect.ValueOf(b)) - - if raValid, rbValid := ra.IsValid(), rb.IsValid(); !raValid && !rbValid { - // If the elements are both nil, and of the same type they are equal - // If they are of different types they are not equal - return reflect.TypeOf(a) == reflect.TypeOf(b) - } else if raValid != rbValid { - // Both values must be valid to be equal - return false - } - - return reflect.DeepEqual(ra.Interface(), rb.Interface()) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go deleted file mode 100644 index a4eb6a7f4..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go +++ /dev/null @@ -1,221 +0,0 @@ -package awsutil - -import ( - "reflect" - "regexp" - "strconv" - "strings" - - "github.com/jmespath/go-jmespath" -) - -var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`) - -// rValuesAtPath returns a slice of values found in value v. The values -// in v are explored recursively so all nested values are collected. -func rValuesAtPath(v interface{}, path string, createPath, caseSensitive, nilTerm bool) []reflect.Value { - pathparts := strings.Split(path, "||") - if len(pathparts) > 1 { - for _, pathpart := range pathparts { - vals := rValuesAtPath(v, pathpart, createPath, caseSensitive, nilTerm) - if len(vals) > 0 { - return vals - } - } - return nil - } - - values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))} - components := strings.Split(path, ".") - for len(values) > 0 && len(components) > 0 { - var index *int64 - var indexStar bool - c := strings.TrimSpace(components[0]) - if c == "" { // no actual component, illegal syntax - return nil - } else if caseSensitive && c != "*" && strings.ToLower(c[0:1]) == c[0:1] { - // TODO normalize case for user - return nil // don't support unexported fields - } - - // parse this component - if m := indexRe.FindStringSubmatch(c); m != nil { - c = m[1] - if m[2] == "" { - index = nil - indexStar = true - } else { - i, _ := strconv.ParseInt(m[2], 10, 32) - index = &i - indexStar = false - } - } - - nextvals := []reflect.Value{} - for _, value := range values { - // pull component name out of struct member - if value.Kind() != reflect.Struct { - continue - } - - if c == "*" { // pull all members - for i := 0; i < value.NumField(); i++ { - if f := reflect.Indirect(value.Field(i)); f.IsValid() { - nextvals = append(nextvals, f) - } - } - continue - } - - value = value.FieldByNameFunc(func(name string) bool { - if c == name { - return true - } else if !caseSensitive && strings.EqualFold(name, c) { - return true - } - return false - }) - - if nilTerm && value.Kind() == reflect.Ptr && len(components[1:]) == 0 { - if !value.IsNil() { - value.Set(reflect.Zero(value.Type())) - } - return []reflect.Value{value} - } - - if createPath && value.Kind() == reflect.Ptr && value.IsNil() { - // TODO if the value is the terminus it should not be created - // if the value to be set to its position is nil. - value.Set(reflect.New(value.Type().Elem())) - value = value.Elem() - } else { - value = reflect.Indirect(value) - } - - if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { - if !createPath && value.IsNil() { - value = reflect.ValueOf(nil) - } - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - - if indexStar || index != nil { - nextvals = []reflect.Value{} - for _, valItem := range values { - value := reflect.Indirect(valItem) - if value.Kind() != reflect.Slice { - continue - } - - if indexStar { // grab all indices - for i := 0; i < value.Len(); i++ { - idx := reflect.Indirect(value.Index(i)) - if idx.IsValid() { - nextvals = append(nextvals, idx) - } - } - continue - } - - // pull out index - i := int(*index) - if i >= value.Len() { // check out of bounds - if createPath { - // TODO resize slice - } else { - continue - } - } else if i < 0 { // support negative indexing - i = value.Len() + i - } - value = reflect.Indirect(value.Index(i)) - - if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { - if !createPath && value.IsNil() { - value = reflect.ValueOf(nil) - } - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - } - - components = components[1:] - } - return values -} - -// ValuesAtPath returns a list of values at the case insensitive lexical -// path inside of a structure. -func ValuesAtPath(i interface{}, path string) ([]interface{}, error) { - result, err := jmespath.Search(path, i) - if err != nil { - return nil, err - } - - v := reflect.ValueOf(result) - if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) { - return nil, nil - } - if s, ok := result.([]interface{}); ok { - return s, err - } - if v.Kind() == reflect.Map && v.Len() == 0 { - return nil, nil - } - if v.Kind() == reflect.Slice { - out := make([]interface{}, v.Len()) - for i := 0; i < v.Len(); i++ { - out[i] = v.Index(i).Interface() - } - return out, nil - } - - return []interface{}{result}, nil -} - -// SetValueAtPath sets a value at the case insensitive lexical path inside -// of a structure. -func SetValueAtPath(i interface{}, path string, v interface{}) { - rvals := rValuesAtPath(i, path, true, false, v == nil) - for _, rval := range rvals { - if rval.Kind() == reflect.Ptr && rval.IsNil() { - continue - } - setValue(rval, v) - } -} - -func setValue(dstVal reflect.Value, src interface{}) { - if dstVal.Kind() == reflect.Ptr { - dstVal = reflect.Indirect(dstVal) - } - srcVal := reflect.ValueOf(src) - - if !srcVal.IsValid() { // src is literal nil - if dstVal.CanAddr() { - // Convert to pointer so that pointer's value can be nil'ed - // dstVal = dstVal.Addr() - } - dstVal.Set(reflect.Zero(dstVal.Type())) - - } else if srcVal.Kind() == reflect.Ptr { - if srcVal.IsNil() { - srcVal = reflect.Zero(dstVal.Type()) - } else { - srcVal = reflect.ValueOf(src).Elem() - } - dstVal.Set(srcVal) - } else { - dstVal.Set(srcVal) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go deleted file mode 100644 index 11d4240d6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go +++ /dev/null @@ -1,123 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" -) - -// Prettify returns the string representation of a value. -func Prettify(i interface{}) string { - var buf bytes.Buffer - prettify(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -// prettify will recursively walk value v to build a textual -// representation of the value. -func prettify(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - strtype := v.Type().String() - if strtype == "time.Time" { - fmt.Fprintf(buf, "%s", v.Interface()) - break - } else if strings.HasPrefix(strtype, "io.") { - buf.WriteString("") - break - } - - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - ft, ok := v.Type().FieldByName(n) - if !ok { - panic(fmt.Sprintf("expected to find field %v on type %v, but was not found", n, v.Type())) - } - - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - - if tag := ft.Tag.Get("sensitive"); tag == "true" { - buf.WriteString("") - } else { - prettify(val, indent+2, buf) - } - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - strtype := v.Type().String() - if strtype == "[]uint8" { - fmt.Fprintf(buf, " len %d", v.Len()) - break - } - - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - prettify(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - prettify(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - if !v.IsValid() { - fmt.Fprint(buf, "") - return - } - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - case io.ReadSeeker, io.Reader: - format = "buffer(%p)" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go deleted file mode 100644 index 3f7cffd95..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go +++ /dev/null @@ -1,90 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "reflect" - "strings" -) - -// StringValue returns the string representation of a value. -// -// Deprecated: Use Prettify instead. -func StringValue(i interface{}) string { - var buf bytes.Buffer - stringValue(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - buf.WriteString("{\n") - - for i := 0; i < v.Type().NumField(); i++ { - ft := v.Type().Field(i) - fv := v.Field(i) - - if ft.Name[0:1] == strings.ToLower(ft.Name[0:1]) { - continue // ignore unexported fields - } - if (fv.Kind() == reflect.Ptr || fv.Kind() == reflect.Slice) && fv.IsNil() { - continue // ignore unset fields - } - - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(ft.Name + ": ") - - if tag := ft.Tag.Get("sensitive"); tag == "true" { - buf.WriteString("") - } else { - stringValue(fv, indent+2, buf) - } - - buf.WriteString(",\n") - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - stringValue(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - stringValue(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go deleted file mode 100644 index b147f103c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go +++ /dev/null @@ -1,94 +0,0 @@ -package client - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Config provides configuration to a service client instance. -type Config struct { - Config *aws.Config - Handlers request.Handlers - PartitionID string - Endpoint string - SigningRegion string - SigningName string - ResolvedRegion string - - // States that the signing name did not come from a modeled source but - // was derived based on other data. Used by service client constructors - // to determine if the signin name can be overridden based on metadata the - // service has. - SigningNameDerived bool -} - -// ConfigProvider provides a generic way for a service client to receive -// the ClientConfig without circular dependencies. -type ConfigProvider interface { - ClientConfig(serviceName string, cfgs ...*aws.Config) Config -} - -// ConfigNoResolveEndpointProvider same as ConfigProvider except it will not -// resolve the endpoint automatically. The service client's endpoint must be -// provided via the aws.Config.Endpoint field. -type ConfigNoResolveEndpointProvider interface { - ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) Config -} - -// A Client implements the base client request and response handling -// used by all service clients. -type Client struct { - request.Retryer - metadata.ClientInfo - - Config aws.Config - Handlers request.Handlers -} - -// New will return a pointer to a new initialized service client. -func New(cfg aws.Config, info metadata.ClientInfo, handlers request.Handlers, options ...func(*Client)) *Client { - svc := &Client{ - Config: cfg, - ClientInfo: info, - Handlers: handlers.Copy(), - } - - switch retryer, ok := cfg.Retryer.(request.Retryer); { - case ok: - svc.Retryer = retryer - case cfg.Retryer != nil && cfg.Logger != nil: - s := fmt.Sprintf("WARNING: %T does not implement request.Retryer; using DefaultRetryer instead", cfg.Retryer) - cfg.Logger.Log(s) - fallthrough - default: - maxRetries := aws.IntValue(cfg.MaxRetries) - if cfg.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries { - maxRetries = DefaultRetryerMaxNumRetries - } - svc.Retryer = DefaultRetryer{NumMaxRetries: maxRetries} - } - - svc.AddDebugHandlers() - - for _, option := range options { - option(svc) - } - - return svc -} - -// NewRequest returns a new Request pointer for the service API -// operation and parameters. -func (c *Client) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request { - return request.New(c.Config, c.ClientInfo, c.Handlers, c.Retryer, operation, params, data) -} - -// AddDebugHandlers injects debug logging handlers into the service to log request -// debug information. -func (c *Client) AddDebugHandlers() { - c.Handlers.Send.PushFrontNamed(LogHTTPRequestHandler) - c.Handlers.Send.PushBackNamed(LogHTTPResponseHandler) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go deleted file mode 100644 index 9f6af19dd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go +++ /dev/null @@ -1,177 +0,0 @@ -package client - -import ( - "math" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkrand" -) - -// DefaultRetryer implements basic retry logic using exponential backoff for -// most services. If you want to implement custom retry logic, you can implement the -// request.Retryer interface. -// -type DefaultRetryer struct { - // Num max Retries is the number of max retries that will be performed. - // By default, this is zero. - NumMaxRetries int - - // MinRetryDelay is the minimum retry delay after which retry will be performed. - // If not set, the value is 0ns. - MinRetryDelay time.Duration - - // MinThrottleRetryDelay is the minimum retry delay when throttled. - // If not set, the value is 0ns. - MinThrottleDelay time.Duration - - // MaxRetryDelay is the maximum retry delay before which retry must be performed. - // If not set, the value is 0ns. - MaxRetryDelay time.Duration - - // MaxThrottleDelay is the maximum retry delay when throttled. - // If not set, the value is 0ns. - MaxThrottleDelay time.Duration -} - -const ( - // DefaultRetryerMaxNumRetries sets maximum number of retries - DefaultRetryerMaxNumRetries = 3 - - // DefaultRetryerMinRetryDelay sets minimum retry delay - DefaultRetryerMinRetryDelay = 30 * time.Millisecond - - // DefaultRetryerMinThrottleDelay sets minimum delay when throttled - DefaultRetryerMinThrottleDelay = 500 * time.Millisecond - - // DefaultRetryerMaxRetryDelay sets maximum retry delay - DefaultRetryerMaxRetryDelay = 300 * time.Second - - // DefaultRetryerMaxThrottleDelay sets maximum delay when throttled - DefaultRetryerMaxThrottleDelay = 300 * time.Second -) - -// MaxRetries returns the number of maximum returns the service will use to make -// an individual API request. -func (d DefaultRetryer) MaxRetries() int { - return d.NumMaxRetries -} - -// setRetryerDefaults sets the default values of the retryer if not set -func (d *DefaultRetryer) setRetryerDefaults() { - if d.MinRetryDelay == 0 { - d.MinRetryDelay = DefaultRetryerMinRetryDelay - } - if d.MaxRetryDelay == 0 { - d.MaxRetryDelay = DefaultRetryerMaxRetryDelay - } - if d.MinThrottleDelay == 0 { - d.MinThrottleDelay = DefaultRetryerMinThrottleDelay - } - if d.MaxThrottleDelay == 0 { - d.MaxThrottleDelay = DefaultRetryerMaxThrottleDelay - } -} - -// RetryRules returns the delay duration before retrying this request again -func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { - - // if number of max retries is zero, no retries will be performed. - if d.NumMaxRetries == 0 { - return 0 - } - - // Sets default value for retryer members - d.setRetryerDefaults() - - // minDelay is the minimum retryer delay - minDelay := d.MinRetryDelay - - var initialDelay time.Duration - - isThrottle := r.IsErrorThrottle() - if isThrottle { - if delay, ok := getRetryAfterDelay(r); ok { - initialDelay = delay - } - minDelay = d.MinThrottleDelay - } - - retryCount := r.RetryCount - - // maxDelay the maximum retryer delay - maxDelay := d.MaxRetryDelay - - if isThrottle { - maxDelay = d.MaxThrottleDelay - } - - var delay time.Duration - - // Logic to cap the retry count based on the minDelay provided - actualRetryCount := int(math.Log2(float64(minDelay))) + 1 - if actualRetryCount < 63-retryCount { - delay = time.Duration(1< maxDelay { - delay = getJitterDelay(maxDelay / 2) - } - } else { - delay = getJitterDelay(maxDelay / 2) - } - return delay + initialDelay -} - -// getJitterDelay returns a jittered delay for retry -func getJitterDelay(duration time.Duration) time.Duration { - return time.Duration(sdkrand.SeededRand.Int63n(int64(duration)) + int64(duration)) -} - -// ShouldRetry returns true if the request should be retried. -func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { - - // ShouldRetry returns false if number of max retries is 0. - if d.NumMaxRetries == 0 { - return false - } - - // If one of the other handlers already set the retry state - // we don't want to override it based on the service's state - if r.Retryable != nil { - return *r.Retryable - } - return r.IsErrorRetryable() || r.IsErrorThrottle() -} - -// This will look in the Retry-After header, RFC 7231, for how long -// it will wait before attempting another request -func getRetryAfterDelay(r *request.Request) (time.Duration, bool) { - if !canUseRetryAfterHeader(r) { - return 0, false - } - - delayStr := r.HTTPResponse.Header.Get("Retry-After") - if len(delayStr) == 0 { - return 0, false - } - - delay, err := strconv.Atoi(delayStr) - if err != nil { - return 0, false - } - - return time.Duration(delay) * time.Second, true -} - -// Will look at the status code to see if the retry header pertains to -// the status code. -func canUseRetryAfterHeader(r *request.Request) bool { - switch r.HTTPResponse.StatusCode { - case 429: - case 503: - default: - return false - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go deleted file mode 100644 index 5ac5c24a1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go +++ /dev/null @@ -1,206 +0,0 @@ -package client - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http/httputil" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -const logReqMsg = `DEBUG: Request %s/%s Details: ----[ REQUEST POST-SIGN ]----------------------------- -%s ------------------------------------------------------` - -const logReqErrMsg = `DEBUG ERROR: Request %s/%s: ----[ REQUEST DUMP ERROR ]----------------------------- -%s -------------------------------------------------------` - -type logWriter struct { - // Logger is what we will use to log the payload of a response. - Logger aws.Logger - // buf stores the contents of what has been read - buf *bytes.Buffer -} - -func (logger *logWriter) Write(b []byte) (int, error) { - return logger.buf.Write(b) -} - -type teeReaderCloser struct { - // io.Reader will be a tee reader that is used during logging. - // This structure will read from a body and write the contents to a logger. - io.Reader - // Source is used just to close when we are done reading. - Source io.ReadCloser -} - -func (reader *teeReaderCloser) Close() error { - return reader.Source.Close() -} - -// LogHTTPRequestHandler is a SDK request handler to log the HTTP request sent -// to a service. Will include the HTTP request body if the LogLevel of the -// request matches LogDebugWithHTTPBody. -var LogHTTPRequestHandler = request.NamedHandler{ - Name: "awssdk.client.LogRequest", - Fn: logRequest, -} - -func logRequest(r *request.Request) { - if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil { - return - } - - logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) - bodySeekable := aws.IsReaderSeekable(r.Body) - - b, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) - if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, - r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - - if logBody { - if !bodySeekable { - r.SetReaderBody(aws.ReadSeekCloser(r.HTTPRequest.Body)) - } - // Reset the request body because dumpRequest will re-wrap the - // r.HTTPRequest's Body as a NoOpCloser and will not be reset after - // read by the HTTP client reader. - if err := r.Error; err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, - r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - } - - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, - r.ClientInfo.ServiceName, r.Operation.Name, string(b))) -} - -// LogHTTPRequestHeaderHandler is a SDK request handler to log the HTTP request sent -// to a service. Will only log the HTTP request's headers. The request payload -// will not be read. -var LogHTTPRequestHeaderHandler = request.NamedHandler{ - Name: "awssdk.client.LogRequestHeader", - Fn: logRequestHeader, -} - -func logRequestHeader(r *request.Request) { - if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil { - return - } - - b, err := httputil.DumpRequestOut(r.HTTPRequest, false) - if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, - r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, - r.ClientInfo.ServiceName, r.Operation.Name, string(b))) -} - -const logRespMsg = `DEBUG: Response %s/%s Details: ----[ RESPONSE ]-------------------------------------- -%s ------------------------------------------------------` - -const logRespErrMsg = `DEBUG ERROR: Response %s/%s: ----[ RESPONSE DUMP ERROR ]----------------------------- -%s ------------------------------------------------------` - -// LogHTTPResponseHandler is a SDK request handler to log the HTTP response -// received from a service. Will include the HTTP response body if the LogLevel -// of the request matches LogDebugWithHTTPBody. -var LogHTTPResponseHandler = request.NamedHandler{ - Name: "awssdk.client.LogResponse", - Fn: logResponse, -} - -func logResponse(r *request.Request) { - if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil { - return - } - - lw := &logWriter{r.Config.Logger, bytes.NewBuffer(nil)} - - if r.HTTPResponse == nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, - r.ClientInfo.ServiceName, r.Operation.Name, "request's HTTPResponse is nil")) - return - } - - logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) - if logBody { - r.HTTPResponse.Body = &teeReaderCloser{ - Reader: io.TeeReader(r.HTTPResponse.Body, lw), - Source: r.HTTPResponse.Body, - } - } - - handlerFn := func(req *request.Request) { - b, err := httputil.DumpResponse(req.HTTPResponse, false) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, - req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - - lw.Logger.Log(fmt.Sprintf(logRespMsg, - req.ClientInfo.ServiceName, req.Operation.Name, string(b))) - - if logBody { - b, err := ioutil.ReadAll(lw.buf) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, - req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - - lw.Logger.Log(string(b)) - } - } - - const handlerName = "awsdk.client.LogResponse.ResponseBody" - - r.Handlers.Unmarshal.SetBackNamed(request.NamedHandler{ - Name: handlerName, Fn: handlerFn, - }) - r.Handlers.UnmarshalError.SetBackNamed(request.NamedHandler{ - Name: handlerName, Fn: handlerFn, - }) -} - -// LogHTTPResponseHeaderHandler is a SDK request handler to log the HTTP -// response received from a service. Will only log the HTTP response's headers. -// The response payload will not be read. -var LogHTTPResponseHeaderHandler = request.NamedHandler{ - Name: "awssdk.client.LogResponseHeader", - Fn: logResponseHeader, -} - -func logResponseHeader(r *request.Request) { - if !r.Config.LogLevel.AtLeast(aws.LogDebug) || r.Config.Logger == nil { - return - } - - b, err := httputil.DumpResponse(r.HTTPResponse, false) - if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logRespErrMsg, - r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - - r.Config.Logger.Log(fmt.Sprintf(logRespMsg, - r.ClientInfo.ServiceName, r.Operation.Name, string(b))) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go b/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go deleted file mode 100644 index a7530ebb3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go +++ /dev/null @@ -1,15 +0,0 @@ -package metadata - -// ClientInfo wraps immutable data from the client.Client structure. -type ClientInfo struct { - ServiceName string - ServiceID string - APIVersion string - PartitionID string - Endpoint string - SigningName string - SigningRegion string - JSONVersion string - TargetPrefix string - ResolvedRegion string -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/no_op_retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/client/no_op_retryer.go deleted file mode 100644 index 881d575f0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/no_op_retryer.go +++ /dev/null @@ -1,28 +0,0 @@ -package client - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws/request" -) - -// NoOpRetryer provides a retryer that performs no retries. -// It should be used when we do not want retries to be performed. -type NoOpRetryer struct{} - -// MaxRetries returns the number of maximum returns the service will use to make -// an individual API; For NoOpRetryer the MaxRetries will always be zero. -func (d NoOpRetryer) MaxRetries() int { - return 0 -} - -// ShouldRetry will always return false for NoOpRetryer, as it should never retry. -func (d NoOpRetryer) ShouldRetry(_ *request.Request) bool { - return false -} - -// RetryRules returns the delay duration before retrying this request again; -// since NoOpRetryer does not retry, RetryRules always returns 0. -func (d NoOpRetryer) RetryRules(_ *request.Request) time.Duration { - return 0 -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config.go b/vendor/github.com/aws/aws-sdk-go/aws/config.go deleted file mode 100644 index c483e0cb8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ /dev/null @@ -1,670 +0,0 @@ -package aws - -import ( - "net/http" - "time" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/endpoints" -) - -// UseServiceDefaultRetries instructs the config to use the service's own -// default number of retries. This will be the default action if -// Config.MaxRetries is nil also. -const UseServiceDefaultRetries = -1 - -// RequestRetryer is an alias for a type that implements the request.Retryer -// interface. -type RequestRetryer interface{} - -// A Config provides service configuration for service clients. By default, -// all clients will use the defaults.DefaultConfig structure. -// -// // Create Session with MaxRetries configuration to be shared by multiple -// // service clients. -// sess := session.Must(session.NewSession(&aws.Config{ -// MaxRetries: aws.Int(3), -// })) -// -// // Create S3 service client with a specific Region. -// svc := s3.New(sess, &aws.Config{ -// Region: aws.String("us-west-2"), -// }) -type Config struct { - // Enables verbose error printing of all credential chain errors. - // Should be used when wanting to see all errors while attempting to - // retrieve credentials. - CredentialsChainVerboseErrors *bool - - // The credentials object to use when signing requests. Defaults to a - // chain of credential providers to search for credentials in environment - // variables, shared credential file, and EC2 Instance Roles. - Credentials *credentials.Credentials - - // An optional endpoint URL (hostname only or fully qualified URI) - // that overrides the default generated endpoint for a client. Set this - // to `nil` or the value to `""` to use the default generated endpoint. - // - // Note: You must still provide a `Region` value when specifying an - // endpoint for a client. - Endpoint *string - - // The resolver to use for looking up endpoints for AWS service clients - // to use based on region. - EndpointResolver endpoints.Resolver - - // EnforceShouldRetryCheck is used in the AfterRetryHandler to always call - // ShouldRetry regardless of whether or not if request.Retryable is set. - // This will utilize ShouldRetry method of custom retryers. If EnforceShouldRetryCheck - // is not set, then ShouldRetry will only be called if request.Retryable is nil. - // Proper handling of the request.Retryable field is important when setting this field. - EnforceShouldRetryCheck *bool - - // The region to send requests to. This parameter is required and must - // be configured globally or on a per-client basis unless otherwise - // noted. A full list of regions is found in the "Regions and Endpoints" - // document. - // - // See http://docs.aws.amazon.com/general/latest/gr/rande.html for AWS - // Regions and Endpoints. - Region *string - - // Set this to `true` to disable SSL when sending requests. Defaults - // to `false`. - DisableSSL *bool - - // The HTTP client to use when sending requests. Defaults to - // `http.DefaultClient`. - HTTPClient *http.Client - - // An integer value representing the logging level. The default log level - // is zero (LogOff), which represents no logging. To enable logging set - // to a LogLevel Value. - LogLevel *LogLevelType - - // The logger writer interface to write logging messages to. Defaults to - // standard out. - Logger Logger - - // The maximum number of times that a request will be retried for failures. - // Defaults to -1, which defers the max retry setting to the service - // specific configuration. - MaxRetries *int - - // Retryer guides how HTTP requests should be retried in case of - // recoverable failures. - // - // When nil or the value does not implement the request.Retryer interface, - // the client.DefaultRetryer will be used. - // - // When both Retryer and MaxRetries are non-nil, the former is used and - // the latter ignored. - // - // To set the Retryer field in a type-safe manner and with chaining, use - // the request.WithRetryer helper function: - // - // cfg := request.WithRetryer(aws.NewConfig(), myRetryer) - // - Retryer RequestRetryer - - // Disables semantic parameter validation, which validates input for - // missing required fields and/or other semantic request input errors. - DisableParamValidation *bool - - // Disables the computation of request and response checksums, e.g., - // CRC32 checksums in Amazon DynamoDB. - DisableComputeChecksums *bool - - // Set this to `true` to force the request to use path-style addressing, - // i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client - // will use virtual hosted bucket addressing when possible - // (`http://BUCKET.s3.amazonaws.com/KEY`). - // - // Note: This configuration option is specific to the Amazon S3 service. - // - // See http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html - // for Amazon S3: Virtual Hosting of Buckets - S3ForcePathStyle *bool - - // Set this to `true` to disable the SDK adding the `Expect: 100-Continue` - // header to PUT requests over 2MB of content. 100-Continue instructs the - // HTTP client not to send the body until the service responds with a - // `continue` status. This is useful to prevent sending the request body - // until after the request is authenticated, and validated. - // - // http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html - // - // 100-Continue is only enabled for Go 1.6 and above. See `http.Transport`'s - // `ExpectContinueTimeout` for information on adjusting the continue wait - // timeout. https://golang.org/pkg/net/http/#Transport - // - // You should use this flag to disable 100-Continue if you experience issues - // with proxies or third party S3 compatible services. - S3Disable100Continue *bool - - // Set this to `true` to enable S3 Accelerate feature. For all operations - // compatible with S3 Accelerate will use the accelerate endpoint for - // requests. Requests not compatible will fall back to normal S3 requests. - // - // The bucket must be enable for accelerate to be used with S3 client with - // accelerate enabled. If the bucket is not enabled for accelerate an error - // will be returned. The bucket name must be DNS compatible to also work - // with accelerate. - S3UseAccelerate *bool - - // S3DisableContentMD5Validation config option is temporarily disabled, - // For S3 GetObject API calls, #1837. - // - // Set this to `true` to disable the S3 service client from automatically - // adding the ContentMD5 to S3 Object Put and Upload API calls. This option - // will also disable the SDK from performing object ContentMD5 validation - // on GetObject API calls. - S3DisableContentMD5Validation *bool - - // Set this to `true` to have the S3 service client to use the region specified - // in the ARN, when an ARN is provided as an argument to a bucket parameter. - S3UseARNRegion *bool - - // Set this to `true` to enable the SDK to unmarshal API response header maps to - // normalized lower case map keys. - // - // For example S3's X-Amz-Meta prefixed header will be unmarshaled to lower case - // Metadata member's map keys. The value of the header in the map is unaffected. - // - // The AWS SDK for Go v2, uses lower case header maps by default. The v1 - // SDK provides this opt-in for this option, for backwards compatibility. - LowerCaseHeaderMaps *bool - - // Set this to `true` to disable the EC2Metadata client from overriding the - // default http.Client's Timeout. This is helpful if you do not want the - // EC2Metadata client to create a new http.Client. This options is only - // meaningful if you're not already using a custom HTTP client with the - // SDK. Enabled by default. - // - // Must be set and provided to the session.NewSession() in order to disable - // the EC2Metadata overriding the timeout for default credentials chain. - // - // Example: - // sess := session.Must(session.NewSession(aws.NewConfig() - // .WithEC2MetadataDisableTimeoutOverride(true))) - // - // svc := s3.New(sess) - // - EC2MetadataDisableTimeoutOverride *bool - - // Set this to `false` to disable EC2Metadata client from falling back to IMDSv1. - // By default, EC2 role credentials will fall back to IMDSv1 as needed for backwards compatibility. - // You can disable this behavior by explicitly setting this flag to `false`. When false, the EC2Metadata - // client will return any errors encountered from attempting to fetch a token instead of silently - // using the insecure data flow of IMDSv1. - // - // Example: - // sess := session.Must(session.NewSession(aws.NewConfig() - // .WithEC2MetadataEnableFallback(false))) - // - // svc := s3.New(sess) - // - // See [configuring IMDS] for more information. - // - // [configuring IMDS]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html - EC2MetadataEnableFallback *bool - - // Instructs the endpoint to be generated for a service client to - // be the dual stack endpoint. The dual stack endpoint will support - // both IPv4 and IPv6 addressing. - // - // Setting this for a service which does not support dual stack will fail - // to make requests. It is not recommended to set this value on the session - // as it will apply to all service clients created with the session. Even - // services which don't support dual stack endpoints. - // - // If the Endpoint config value is also provided the UseDualStack flag - // will be ignored. - // - // Only supported with. - // - // sess := session.Must(session.NewSession()) - // - // svc := s3.New(sess, &aws.Config{ - // UseDualStack: aws.Bool(true), - // }) - // - // Deprecated: This option will continue to function for S3 and S3 Control for backwards compatibility. - // UseDualStackEndpoint should be used to enable usage of a service's dual-stack endpoint for all service clients - // moving forward. For S3 and S3 Control, when UseDualStackEndpoint is set to a non-zero value it takes higher - // precedence then this option. - UseDualStack *bool - - // Sets the resolver to resolve a dual-stack endpoint for the service. - UseDualStackEndpoint endpoints.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint endpoints.FIPSEndpointState - - // SleepDelay is an override for the func the SDK will call when sleeping - // during the lifecycle of a request. Specifically this will be used for - // request delays. This value should only be used for testing. To adjust - // the delay of a request see the aws/client.DefaultRetryer and - // aws/request.Retryer. - // - // SleepDelay will prevent any Context from being used for canceling retry - // delay of an API operation. It is recommended to not use SleepDelay at all - // and specify a Retryer instead. - SleepDelay func(time.Duration) - - // DisableRestProtocolURICleaning will not clean the URL path when making rest protocol requests. - // Will default to false. This would only be used for empty directory names in s3 requests. - // - // Example: - // sess := session.Must(session.NewSession(&aws.Config{ - // DisableRestProtocolURICleaning: aws.Bool(true), - // })) - // - // svc := s3.New(sess) - // out, err := svc.GetObject(&s3.GetObjectInput { - // Bucket: aws.String("bucketname"), - // Key: aws.String("//foo//bar//moo"), - // }) - DisableRestProtocolURICleaning *bool - - // EnableEndpointDiscovery will allow for endpoint discovery on operations that - // have the definition in its model. By default, endpoint discovery is off. - // To use EndpointDiscovery, Endpoint should be unset or set to an empty string. - // - // Example: - // sess := session.Must(session.NewSession(&aws.Config{ - // EnableEndpointDiscovery: aws.Bool(true), - // })) - // - // svc := s3.New(sess) - // out, err := svc.GetObject(&s3.GetObjectInput { - // Bucket: aws.String("bucketname"), - // Key: aws.String("/foo/bar/moo"), - // }) - EnableEndpointDiscovery *bool - - // DisableEndpointHostPrefix will disable the SDK's behavior of prefixing - // request endpoint hosts with modeled information. - // - // Disabling this feature is useful when you want to use local endpoints - // for testing that do not support the modeled host prefix pattern. - DisableEndpointHostPrefix *bool - - // STSRegionalEndpoint will enable regional or legacy endpoint resolving - STSRegionalEndpoint endpoints.STSRegionalEndpoint - - // S3UsEast1RegionalEndpoint will enable regional or legacy endpoint resolving - S3UsEast1RegionalEndpoint endpoints.S3UsEast1RegionalEndpoint -} - -// NewConfig returns a new Config pointer that can be chained with builder -// methods to set multiple configuration values inline without using pointers. -// -// // Create Session with MaxRetries configuration to be shared by multiple -// // service clients. -// sess := session.Must(session.NewSession(aws.NewConfig(). -// WithMaxRetries(3), -// )) -// -// // Create S3 service client with a specific Region. -// svc := s3.New(sess, aws.NewConfig(). -// WithRegion("us-west-2"), -// ) -func NewConfig() *Config { - return &Config{} -} - -// WithCredentialsChainVerboseErrors sets a config verbose errors boolean and returning -// a Config pointer. -func (c *Config) WithCredentialsChainVerboseErrors(verboseErrs bool) *Config { - c.CredentialsChainVerboseErrors = &verboseErrs - return c -} - -// WithCredentials sets a config Credentials value returning a Config pointer -// for chaining. -func (c *Config) WithCredentials(creds *credentials.Credentials) *Config { - c.Credentials = creds - return c -} - -// WithEndpoint sets a config Endpoint value returning a Config pointer for -// chaining. -func (c *Config) WithEndpoint(endpoint string) *Config { - c.Endpoint = &endpoint - return c -} - -// WithEndpointResolver sets a config EndpointResolver value returning a -// Config pointer for chaining. -func (c *Config) WithEndpointResolver(resolver endpoints.Resolver) *Config { - c.EndpointResolver = resolver - return c -} - -// WithRegion sets a config Region value returning a Config pointer for -// chaining. -func (c *Config) WithRegion(region string) *Config { - c.Region = ®ion - return c -} - -// WithDisableSSL sets a config DisableSSL value returning a Config pointer -// for chaining. -func (c *Config) WithDisableSSL(disable bool) *Config { - c.DisableSSL = &disable - return c -} - -// WithHTTPClient sets a config HTTPClient value returning a Config pointer -// for chaining. -func (c *Config) WithHTTPClient(client *http.Client) *Config { - c.HTTPClient = client - return c -} - -// WithMaxRetries sets a config MaxRetries value returning a Config pointer -// for chaining. -func (c *Config) WithMaxRetries(max int) *Config { - c.MaxRetries = &max - return c -} - -// WithDisableParamValidation sets a config DisableParamValidation value -// returning a Config pointer for chaining. -func (c *Config) WithDisableParamValidation(disable bool) *Config { - c.DisableParamValidation = &disable - return c -} - -// WithDisableComputeChecksums sets a config DisableComputeChecksums value -// returning a Config pointer for chaining. -func (c *Config) WithDisableComputeChecksums(disable bool) *Config { - c.DisableComputeChecksums = &disable - return c -} - -// WithLogLevel sets a config LogLevel value returning a Config pointer for -// chaining. -func (c *Config) WithLogLevel(level LogLevelType) *Config { - c.LogLevel = &level - return c -} - -// WithLogger sets a config Logger value returning a Config pointer for -// chaining. -func (c *Config) WithLogger(logger Logger) *Config { - c.Logger = logger - return c -} - -// WithS3ForcePathStyle sets a config S3ForcePathStyle value returning a Config -// pointer for chaining. -func (c *Config) WithS3ForcePathStyle(force bool) *Config { - c.S3ForcePathStyle = &force - return c -} - -// WithS3Disable100Continue sets a config S3Disable100Continue value returning -// a Config pointer for chaining. -func (c *Config) WithS3Disable100Continue(disable bool) *Config { - c.S3Disable100Continue = &disable - return c -} - -// WithS3UseAccelerate sets a config S3UseAccelerate value returning a Config -// pointer for chaining. -func (c *Config) WithS3UseAccelerate(enable bool) *Config { - c.S3UseAccelerate = &enable - return c - -} - -// WithS3DisableContentMD5Validation sets a config -// S3DisableContentMD5Validation value returning a Config pointer for chaining. -func (c *Config) WithS3DisableContentMD5Validation(enable bool) *Config { - c.S3DisableContentMD5Validation = &enable - return c - -} - -// WithS3UseARNRegion sets a config S3UseARNRegion value and -// returning a Config pointer for chaining -func (c *Config) WithS3UseARNRegion(enable bool) *Config { - c.S3UseARNRegion = &enable - return c -} - -// WithUseDualStack sets a config UseDualStack value returning a Config -// pointer for chaining. -func (c *Config) WithUseDualStack(enable bool) *Config { - c.UseDualStack = &enable - return c -} - -// WithUseFIPSEndpoint sets a config UseFIPSEndpoint value returning a Config -// pointer for chaining. -func (c *Config) WithUseFIPSEndpoint(enable bool) *Config { - if enable { - c.UseFIPSEndpoint = endpoints.FIPSEndpointStateEnabled - } else { - c.UseFIPSEndpoint = endpoints.FIPSEndpointStateDisabled - } - return c -} - -// WithEC2MetadataDisableTimeoutOverride sets a config EC2MetadataDisableTimeoutOverride value -// returning a Config pointer for chaining. -func (c *Config) WithEC2MetadataDisableTimeoutOverride(enable bool) *Config { - c.EC2MetadataDisableTimeoutOverride = &enable - return c -} - -// WithEC2MetadataEnableFallback sets a config EC2MetadataEnableFallback value -// returning a Config pointer for chaining. -func (c *Config) WithEC2MetadataEnableFallback(v bool) *Config { - c.EC2MetadataEnableFallback = &v - return c -} - -// WithSleepDelay overrides the function used to sleep while waiting for the -// next retry. Defaults to time.Sleep. -func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config { - c.SleepDelay = fn - return c -} - -// WithEndpointDiscovery will set whether or not to use endpoint discovery. -func (c *Config) WithEndpointDiscovery(t bool) *Config { - c.EnableEndpointDiscovery = &t - return c -} - -// WithDisableEndpointHostPrefix will set whether or not to use modeled host prefix -// when making requests. -func (c *Config) WithDisableEndpointHostPrefix(t bool) *Config { - c.DisableEndpointHostPrefix = &t - return c -} - -// WithSTSRegionalEndpoint will set whether or not to use regional endpoint flag -// when resolving the endpoint for a service -func (c *Config) WithSTSRegionalEndpoint(sre endpoints.STSRegionalEndpoint) *Config { - c.STSRegionalEndpoint = sre - return c -} - -// WithS3UsEast1RegionalEndpoint will set whether or not to use regional endpoint flag -// when resolving the endpoint for a service -func (c *Config) WithS3UsEast1RegionalEndpoint(sre endpoints.S3UsEast1RegionalEndpoint) *Config { - c.S3UsEast1RegionalEndpoint = sre - return c -} - -// WithLowerCaseHeaderMaps sets a config LowerCaseHeaderMaps value -// returning a Config pointer for chaining. -func (c *Config) WithLowerCaseHeaderMaps(t bool) *Config { - c.LowerCaseHeaderMaps = &t - return c -} - -// WithDisableRestProtocolURICleaning sets a config DisableRestProtocolURICleaning value -// returning a Config pointer for chaining. -func (c *Config) WithDisableRestProtocolURICleaning(t bool) *Config { - c.DisableRestProtocolURICleaning = &t - return c -} - -// MergeIn merges the passed in configs into the existing config object. -func (c *Config) MergeIn(cfgs ...*Config) { - for _, other := range cfgs { - mergeInConfig(c, other) - } -} - -func mergeInConfig(dst *Config, other *Config) { - if other == nil { - return - } - - if other.CredentialsChainVerboseErrors != nil { - dst.CredentialsChainVerboseErrors = other.CredentialsChainVerboseErrors - } - - if other.Credentials != nil { - dst.Credentials = other.Credentials - } - - if other.Endpoint != nil { - dst.Endpoint = other.Endpoint - } - - if other.EndpointResolver != nil { - dst.EndpointResolver = other.EndpointResolver - } - - if other.Region != nil { - dst.Region = other.Region - } - - if other.DisableSSL != nil { - dst.DisableSSL = other.DisableSSL - } - - if other.HTTPClient != nil { - dst.HTTPClient = other.HTTPClient - } - - if other.LogLevel != nil { - dst.LogLevel = other.LogLevel - } - - if other.Logger != nil { - dst.Logger = other.Logger - } - - if other.MaxRetries != nil { - dst.MaxRetries = other.MaxRetries - } - - if other.Retryer != nil { - dst.Retryer = other.Retryer - } - - if other.DisableParamValidation != nil { - dst.DisableParamValidation = other.DisableParamValidation - } - - if other.DisableComputeChecksums != nil { - dst.DisableComputeChecksums = other.DisableComputeChecksums - } - - if other.S3ForcePathStyle != nil { - dst.S3ForcePathStyle = other.S3ForcePathStyle - } - - if other.S3Disable100Continue != nil { - dst.S3Disable100Continue = other.S3Disable100Continue - } - - if other.S3UseAccelerate != nil { - dst.S3UseAccelerate = other.S3UseAccelerate - } - - if other.S3DisableContentMD5Validation != nil { - dst.S3DisableContentMD5Validation = other.S3DisableContentMD5Validation - } - - if other.S3UseARNRegion != nil { - dst.S3UseARNRegion = other.S3UseARNRegion - } - - if other.UseDualStack != nil { - dst.UseDualStack = other.UseDualStack - } - - if other.UseDualStackEndpoint != endpoints.DualStackEndpointStateUnset { - dst.UseDualStackEndpoint = other.UseDualStackEndpoint - } - - if other.EC2MetadataDisableTimeoutOverride != nil { - dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride - } - - if other.EC2MetadataEnableFallback != nil { - dst.EC2MetadataEnableFallback = other.EC2MetadataEnableFallback - } - - if other.SleepDelay != nil { - dst.SleepDelay = other.SleepDelay - } - - if other.DisableRestProtocolURICleaning != nil { - dst.DisableRestProtocolURICleaning = other.DisableRestProtocolURICleaning - } - - if other.EnforceShouldRetryCheck != nil { - dst.EnforceShouldRetryCheck = other.EnforceShouldRetryCheck - } - - if other.EnableEndpointDiscovery != nil { - dst.EnableEndpointDiscovery = other.EnableEndpointDiscovery - } - - if other.DisableEndpointHostPrefix != nil { - dst.DisableEndpointHostPrefix = other.DisableEndpointHostPrefix - } - - if other.STSRegionalEndpoint != endpoints.UnsetSTSEndpoint { - dst.STSRegionalEndpoint = other.STSRegionalEndpoint - } - - if other.S3UsEast1RegionalEndpoint != endpoints.UnsetS3UsEast1Endpoint { - dst.S3UsEast1RegionalEndpoint = other.S3UsEast1RegionalEndpoint - } - - if other.LowerCaseHeaderMaps != nil { - dst.LowerCaseHeaderMaps = other.LowerCaseHeaderMaps - } - - if other.UseDualStackEndpoint != endpoints.DualStackEndpointStateUnset { - dst.UseDualStackEndpoint = other.UseDualStackEndpoint - } - - if other.UseFIPSEndpoint != endpoints.FIPSEndpointStateUnset { - dst.UseFIPSEndpoint = other.UseFIPSEndpoint - } -} - -// Copy will return a shallow copy of the Config object. If any additional -// configurations are provided they will be merged into the new config returned. -func (c *Config) Copy(cfgs ...*Config) *Config { - dst := &Config{} - dst.MergeIn(c) - - for _, cfg := range cfgs { - dst.MergeIn(cfg) - } - - return dst -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_5.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_5.go deleted file mode 100644 index 89aad2c67..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_1_5.go +++ /dev/null @@ -1,38 +0,0 @@ -//go:build !go1.9 -// +build !go1.9 - -package aws - -import "time" - -// Context is an copy of the Go v1.7 stdlib's context.Context interface. -// It is represented as a SDK interface to enable you to use the "WithContext" -// API methods with Go v1.6 and a Context type such as golang.org/x/net/context. -// -// See https://golang.org/pkg/context on how to use contexts. -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. - 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. - Value(key interface{}) interface{} -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_9.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_9.go deleted file mode 100644 index 6ee9ddd18..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_1_9.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build go1.9 -// +build go1.9 - -package aws - -import "context" - -// Context is an alias of the Go stdlib's context.Context interface. -// It can be used within the SDK's API operation "WithContext" methods. -// -// See https://golang.org/pkg/context on how to use contexts. -type Context = context.Context diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_5.go b/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_5.go deleted file mode 100644 index 313218190..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_5.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build !go1.7 -// +build !go1.7 - -package aws - -import ( - "github.com/aws/aws-sdk-go/internal/context" -) - -// BackgroundContext returns a context that will never be canceled, has no -// values, and no deadline. This context is used by the SDK to provide -// backwards compatibility with non-context API operations and functionality. -// -// Go 1.6 and before: -// This context function is equivalent to context.Background in the Go stdlib. -// -// Go 1.7 and later: -// The context returned will be the value returned by context.Background() -// -// See https://golang.org/pkg/context for more information on Contexts. -func BackgroundContext() Context { - return context.BackgroundCtx -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go deleted file mode 100644 index 9975d561b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build go1.7 -// +build go1.7 - -package aws - -import "context" - -// BackgroundContext returns a context that will never be canceled, has no -// values, and no deadline. This context is used by the SDK to provide -// backwards compatibility with non-context API operations and functionality. -// -// Go 1.6 and before: -// This context function is equivalent to context.Background in the Go stdlib. -// -// Go 1.7 and later: -// The context returned will be the value returned by context.Background() -// -// See https://golang.org/pkg/context for more information on Contexts. -func BackgroundContext() Context { - return context.Background() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_sleep.go b/vendor/github.com/aws/aws-sdk-go/aws/context_sleep.go deleted file mode 100644 index 304fd1561..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_sleep.go +++ /dev/null @@ -1,24 +0,0 @@ -package aws - -import ( - "time" -) - -// SleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the Context's -// error will be returned. -// -// Expects Context to always return a non-nil error if the Done channel is closed. -func SleepWithContext(ctx Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go b/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go deleted file mode 100644 index 4e076c183..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go +++ /dev/null @@ -1,918 +0,0 @@ -package aws - -import "time" - -// String returns a pointer to the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint returns a pointer to the uint value passed in. -func Uint(v uint) *uint { - return &v -} - -// UintValue returns the value of the uint pointer passed in or -// 0 if the pointer is nil. -func UintValue(v *uint) uint { - if v != nil { - return *v - } - return 0 -} - -// UintSlice converts a slice of uint values uinto a slice of -// uint pointers -func UintSlice(src []uint) []*uint { - dst := make([]*uint, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// UintValueSlice converts a slice of uint pointers uinto a slice of -// uint values -func UintValueSlice(src []*uint) []uint { - dst := make([]uint, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// UintMap converts a string map of uint values uinto a string -// map of uint pointers -func UintMap(src map[string]uint) map[string]*uint { - dst := make(map[string]*uint) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// UintValueMap converts a string map of uint pointers uinto a string -// map of uint values -func UintValueMap(src map[string]*uint) map[string]uint { - dst := make(map[string]uint) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int8 returns a pointer to the int8 value passed in. -func Int8(v int8) *int8 { - return &v -} - -// Int8Value returns the value of the int8 pointer passed in or -// 0 if the pointer is nil. -func Int8Value(v *int8) int8 { - if v != nil { - return *v - } - return 0 -} - -// Int8Slice converts a slice of int8 values into a slice of -// int8 pointers -func Int8Slice(src []int8) []*int8 { - dst := make([]*int8, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int8ValueSlice converts a slice of int8 pointers into a slice of -// int8 values -func Int8ValueSlice(src []*int8) []int8 { - dst := make([]int8, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int8Map converts a string map of int8 values into a string -// map of int8 pointers -func Int8Map(src map[string]int8) map[string]*int8 { - dst := make(map[string]*int8) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int8ValueMap converts a string map of int8 pointers into a string -// map of int8 values -func Int8ValueMap(src map[string]*int8) map[string]int8 { - dst := make(map[string]int8) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int16 returns a pointer to the int16 value passed in. -func Int16(v int16) *int16 { - return &v -} - -// Int16Value returns the value of the int16 pointer passed in or -// 0 if the pointer is nil. -func Int16Value(v *int16) int16 { - if v != nil { - return *v - } - return 0 -} - -// Int16Slice converts a slice of int16 values into a slice of -// int16 pointers -func Int16Slice(src []int16) []*int16 { - dst := make([]*int16, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int16ValueSlice converts a slice of int16 pointers into a slice of -// int16 values -func Int16ValueSlice(src []*int16) []int16 { - dst := make([]int16, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int16Map converts a string map of int16 values into a string -// map of int16 pointers -func Int16Map(src map[string]int16) map[string]*int16 { - dst := make(map[string]*int16) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int16ValueMap converts a string map of int16 pointers into a string -// map of int16 values -func Int16ValueMap(src map[string]*int16) map[string]int16 { - dst := make(map[string]int16) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int32 returns a pointer to the int32 value passed in. -func Int32(v int32) *int32 { - return &v -} - -// Int32Value returns the value of the int32 pointer passed in or -// 0 if the pointer is nil. -func Int32Value(v *int32) int32 { - if v != nil { - return *v - } - return 0 -} - -// Int32Slice converts a slice of int32 values into a slice of -// int32 pointers -func Int32Slice(src []int32) []*int32 { - dst := make([]*int32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int32ValueSlice converts a slice of int32 pointers into a slice of -// int32 values -func Int32ValueSlice(src []*int32) []int32 { - dst := make([]int32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int32Map converts a string map of int32 values into a string -// map of int32 pointers -func Int32Map(src map[string]int32) map[string]*int32 { - dst := make(map[string]*int32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int32ValueMap converts a string map of int32 pointers into a string -// map of int32 values -func Int32ValueMap(src map[string]*int32) map[string]int32 { - dst := make(map[string]int32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint8 returns a pointer to the uint8 value passed in. -func Uint8(v uint8) *uint8 { - return &v -} - -// Uint8Value returns the value of the uint8 pointer passed in or -// 0 if the pointer is nil. -func Uint8Value(v *uint8) uint8 { - if v != nil { - return *v - } - return 0 -} - -// Uint8Slice converts a slice of uint8 values into a slice of -// uint8 pointers -func Uint8Slice(src []uint8) []*uint8 { - dst := make([]*uint8, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint8ValueSlice converts a slice of uint8 pointers into a slice of -// uint8 values -func Uint8ValueSlice(src []*uint8) []uint8 { - dst := make([]uint8, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint8Map converts a string map of uint8 values into a string -// map of uint8 pointers -func Uint8Map(src map[string]uint8) map[string]*uint8 { - dst := make(map[string]*uint8) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint8ValueMap converts a string map of uint8 pointers into a string -// map of uint8 values -func Uint8ValueMap(src map[string]*uint8) map[string]uint8 { - dst := make(map[string]uint8) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint16 returns a pointer to the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return &v -} - -// Uint16Value returns the value of the uint16 pointer passed in or -// 0 if the pointer is nil. -func Uint16Value(v *uint16) uint16 { - if v != nil { - return *v - } - return 0 -} - -// Uint16Slice converts a slice of uint16 values into a slice of -// uint16 pointers -func Uint16Slice(src []uint16) []*uint16 { - dst := make([]*uint16, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint16ValueSlice converts a slice of uint16 pointers into a slice of -// uint16 values -func Uint16ValueSlice(src []*uint16) []uint16 { - dst := make([]uint16, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint16Map converts a string map of uint16 values into a string -// map of uint16 pointers -func Uint16Map(src map[string]uint16) map[string]*uint16 { - dst := make(map[string]*uint16) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint16ValueMap converts a string map of uint16 pointers into a string -// map of uint16 values -func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { - dst := make(map[string]uint16) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint32 returns a pointer to the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint32Value returns the value of the uint32 pointer passed in or -// 0 if the pointer is nil. -func Uint32Value(v *uint32) uint32 { - if v != nil { - return *v - } - return 0 -} - -// Uint32Slice converts a slice of uint32 values into a slice of -// uint32 pointers -func Uint32Slice(src []uint32) []*uint32 { - dst := make([]*uint32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint32ValueSlice converts a slice of uint32 pointers into a slice of -// uint32 values -func Uint32ValueSlice(src []*uint32) []uint32 { - dst := make([]uint32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint32Map converts a string map of uint32 values into a string -// map of uint32 pointers -func Uint32Map(src map[string]uint32) map[string]*uint32 { - dst := make(map[string]*uint32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint32ValueMap converts a string map of uint32 pointers into a string -// map of uint32 values -func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { - dst := make(map[string]uint32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint64 returns a pointer to the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return &v -} - -// Uint64Value returns the value of the uint64 pointer passed in or -// 0 if the pointer is nil. -func Uint64Value(v *uint64) uint64 { - if v != nil { - return *v - } - return 0 -} - -// Uint64Slice converts a slice of uint64 values into a slice of -// uint64 pointers -func Uint64Slice(src []uint64) []*uint64 { - dst := make([]*uint64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint64ValueSlice converts a slice of uint64 pointers into a slice of -// uint64 values -func Uint64ValueSlice(src []*uint64) []uint64 { - dst := make([]uint64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint64Map converts a string map of uint64 values into a string -// map of uint64 pointers -func Uint64Map(src map[string]uint64) map[string]*uint64 { - dst := make(map[string]*uint64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint64ValueMap converts a string map of uint64 pointers into a string -// map of uint64 values -func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { - dst := make(map[string]uint64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float32 returns a pointer to the float32 value passed in. -func Float32(v float32) *float32 { - return &v -} - -// Float32Value returns the value of the float32 pointer passed in or -// 0 if the pointer is nil. -func Float32Value(v *float32) float32 { - if v != nil { - return *v - } - return 0 -} - -// Float32Slice converts a slice of float32 values into a slice of -// float32 pointers -func Float32Slice(src []float32) []*float32 { - dst := make([]*float32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float32ValueSlice converts a slice of float32 pointers into a slice of -// float32 values -func Float32ValueSlice(src []*float32) []float32 { - dst := make([]float32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float32Map converts a string map of float32 values into a string -// map of float32 pointers -func Float32Map(src map[string]float32) map[string]*float32 { - dst := make(map[string]*float32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float32ValueMap converts a string map of float32 pointers into a string -// map of float32 values -func Float32ValueMap(src map[string]*float32) map[string]float32 { - dst := make(map[string]float32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float64 returns a pointer to the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// SecondsTimeValue converts an int64 pointer to a time.Time value -// representing seconds since Epoch or time.Time{} if the pointer is nil. -func SecondsTimeValue(v *int64) time.Time { - if v != nil { - return time.Unix((*v / 1000), 0) - } - return time.Time{} -} - -// MillisecondsTimeValue converts an int64 pointer to a time.Time value -// representing milliseconds sinch Epoch or time.Time{} if the pointer is nil. -func MillisecondsTimeValue(v *int64) time.Time { - if v != nil { - return time.Unix(0, (*v * 1000000)) - } - return time.Time{} -} - -// TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC". -// The result is undefined if the Unix time cannot be represented by an int64. -// Which includes calling TimeUnixMilli on a zero Time is undefined. -// -// This utility is useful for service API's such as CloudWatch Logs which require -// their unix time values to be in milliseconds. -// -// See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information. -func TimeUnixMilli(t time.Time) int64 { - return t.UnixNano() / int64(time.Millisecond/time.Nanosecond) -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/awsinternal.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/awsinternal.go deleted file mode 100644 index 140242dd1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/awsinternal.go +++ /dev/null @@ -1,4 +0,0 @@ -// DO NOT EDIT -package corehandlers - -const isAwsInternal = "" \ No newline at end of file diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go deleted file mode 100644 index 36a915efe..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go +++ /dev/null @@ -1,232 +0,0 @@ -package corehandlers - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "regexp" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -// Interface for matching types which also have a Len method. -type lener interface { - Len() int -} - -// BuildContentLengthHandler builds the content length of a request based on the body, -// or will use the HTTPRequest.Header's "Content-Length" if defined. If unable -// to determine request body length and no "Content-Length" was specified it will panic. -// -// The Content-Length will only be added to the request if the length of the body -// is greater than 0. If the body is empty or the current `Content-Length` -// header is <= 0, the header will also be stripped. -var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLengthHandler", Fn: func(r *request.Request) { - var length int64 - - if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { - length, _ = strconv.ParseInt(slength, 10, 64) - } else { - if r.Body != nil { - var err error - length, err = aws.SeekerLen(r.Body) - if err != nil { - r.Error = awserr.New(request.ErrCodeSerialization, "failed to get request body's length", err) - return - } - } - } - - if length > 0 { - r.HTTPRequest.ContentLength = length - r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length)) - } else { - r.HTTPRequest.ContentLength = 0 - r.HTTPRequest.Header.Del("Content-Length") - } -}} - -var reStatusCode = regexp.MustCompile(`^(\d{3})`) - -// ValidateReqSigHandler is a request handler to ensure that the request's -// signature doesn't expire before it is sent. This can happen when a request -// is built and signed significantly before it is sent. Or significant delays -// occur when retrying requests that would cause the signature to expire. -var ValidateReqSigHandler = request.NamedHandler{ - Name: "core.ValidateReqSigHandler", - Fn: func(r *request.Request) { - // Unsigned requests are not signed - if r.Config.Credentials == credentials.AnonymousCredentials { - return - } - - signedTime := r.Time - if !r.LastSignedAt.IsZero() { - signedTime = r.LastSignedAt - } - - // 5 minutes to allow for some clock skew/delays in transmission. - // Would be improved with aws/aws-sdk-go#423 - if signedTime.Add(5 * time.Minute).After(time.Now()) { - return - } - - fmt.Println("request expired, resigning") - r.Sign() - }, -} - -// SendHandler is a request handler to send service request using HTTP client. -var SendHandler = request.NamedHandler{ - Name: "core.SendHandler", - Fn: func(r *request.Request) { - sender := sendFollowRedirects - if r.DisableFollowRedirects { - sender = sendWithoutFollowRedirects - } - - if request.NoBody == r.HTTPRequest.Body { - // Strip off the request body if the NoBody reader was used as a - // place holder for a request body. This prevents the SDK from - // making requests with a request body when it would be invalid - // to do so. - // - // Use a shallow copy of the http.Request to ensure the race condition - // of transport on Body will not trigger - reqOrig, reqCopy := r.HTTPRequest, *r.HTTPRequest - reqCopy.Body = nil - r.HTTPRequest = &reqCopy - defer func() { - r.HTTPRequest = reqOrig - }() - } - - var err error - r.HTTPResponse, err = sender(r) - if err != nil { - handleSendError(r, err) - } - }, -} - -func sendFollowRedirects(r *request.Request) (*http.Response, error) { - return r.Config.HTTPClient.Do(r.HTTPRequest) -} - -func sendWithoutFollowRedirects(r *request.Request) (*http.Response, error) { - transport := r.Config.HTTPClient.Transport - if transport == nil { - transport = http.DefaultTransport - } - - return transport.RoundTrip(r.HTTPRequest) -} - -func handleSendError(r *request.Request, err error) { - // Prevent leaking if an HTTPResponse was returned. Clean up - // the body. - if r.HTTPResponse != nil { - r.HTTPResponse.Body.Close() - } - // Capture the case where url.Error is returned for error processing - // response. e.g. 301 without location header comes back as string - // error and r.HTTPResponse is nil. Other URL redirect errors will - // comeback in a similar method. - if e, ok := err.(*url.Error); ok && e.Err != nil { - if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil { - code, _ := strconv.ParseInt(s[1], 10, 64) - r.HTTPResponse = &http.Response{ - StatusCode: int(code), - Status: http.StatusText(int(code)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - return - } - } - if r.HTTPResponse == nil { - // Add a dummy request response object to ensure the HTTPResponse - // value is consistent. - r.HTTPResponse = &http.Response{ - StatusCode: int(0), - Status: http.StatusText(int(0)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - } - // Catch all request errors, and let the default retrier determine - // if the error is retryable. - r.Error = awserr.New(request.ErrCodeRequestError, "send request failed", err) - - // Override the error with a context canceled error, if that was canceled. - ctx := r.Context() - select { - case <-ctx.Done(): - r.Error = awserr.New(request.CanceledErrorCode, - "request context canceled", ctx.Err()) - r.Retryable = aws.Bool(false) - default: - } -} - -// ValidateResponseHandler is a request handler to validate service response. -var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseHandler", Fn: func(r *request.Request) { - if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 { - // this may be replaced by an UnmarshalError handler - r.Error = awserr.New("UnknownError", "unknown error", r.Error) - } -}} - -// AfterRetryHandler performs final checks to determine if the request should -// be retried and how long to delay. -var AfterRetryHandler = request.NamedHandler{ - Name: "core.AfterRetryHandler", - Fn: func(r *request.Request) { - // If one of the other handlers already set the retry state - // we don't want to override it based on the service's state - if r.Retryable == nil || aws.BoolValue(r.Config.EnforceShouldRetryCheck) { - r.Retryable = aws.Bool(r.ShouldRetry(r)) - } - - if r.WillRetry() { - r.RetryDelay = r.RetryRules(r) - - if sleepFn := r.Config.SleepDelay; sleepFn != nil { - // Support SleepDelay for backwards compatibility and testing - sleepFn(r.RetryDelay) - } else if err := aws.SleepWithContext(r.Context(), r.RetryDelay); err != nil { - r.Error = awserr.New(request.CanceledErrorCode, - "request context canceled", err) - r.Retryable = aws.Bool(false) - return - } - - // when the expired token exception occurs the credentials - // need to be expired locally so that the next request to - // get credentials will trigger a credentials refresh. - if r.IsErrorExpired() { - r.Config.Credentials.Expire() - } - - r.RetryCount++ - r.Error = nil - } - }} - -// ValidateEndpointHandler is a request handler to validate a request had the -// appropriate Region and Endpoint set. Will set r.Error if the endpoint or -// region is not valid. -var ValidateEndpointHandler = request.NamedHandler{Name: "core.ValidateEndpointHandler", Fn: func(r *request.Request) { - if r.ClientInfo.SigningRegion == "" && aws.StringValue(r.Config.Region) == "" { - r.Error = aws.ErrMissingRegion - } else if r.ClientInfo.Endpoint == "" { - // Was any endpoint provided by the user, or one was derived by the - // SDK's endpoint resolver? - r.Error = aws.ErrMissingEndpoint - } -}} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go deleted file mode 100644 index 7d50b1557..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go +++ /dev/null @@ -1,17 +0,0 @@ -package corehandlers - -import "github.com/aws/aws-sdk-go/aws/request" - -// ValidateParametersHandler is a request handler to validate the input parameters. -// Validating parameters only has meaning if done prior to the request being sent. -var ValidateParametersHandler = request.NamedHandler{Name: "core.ValidateParametersHandler", Fn: func(r *request.Request) { - if !r.ParamsFilled() { - return - } - - if v, ok := r.Params.(request.Validator); ok { - if err := v.Validate(); err != nil { - r.Error = err - } - } -}} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go deleted file mode 100644 index ac842c55d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go +++ /dev/null @@ -1,47 +0,0 @@ -package corehandlers - -import ( - "os" - "runtime" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -// SDKVersionUserAgentHandler is a request handler for adding the SDK Version -// to the user agent. -var SDKVersionUserAgentHandler = request.NamedHandler{ - Name: "core.SDKVersionUserAgentHandler", - Fn: request.MakeAddToUserAgentHandler(aws.SDKName, aws.SDKVersion, - runtime.Version(), runtime.GOOS, runtime.GOARCH), -} - -const execEnvVar = `AWS_EXECUTION_ENV` -const execEnvUAKey = `exec-env` - -// AddHostExecEnvUserAgentHander is a request handler appending the SDK's -// execution environment to the user agent. -// -// If the environment variable AWS_EXECUTION_ENV is set, its value will be -// appended to the user agent string. -var AddHostExecEnvUserAgentHander = request.NamedHandler{ - Name: "core.AddHostExecEnvUserAgentHander", - Fn: func(r *request.Request) { - v := os.Getenv(execEnvVar) - if len(v) == 0 { - return - } - - request.AddToUserAgent(r, execEnvUAKey+"/"+v) - }, -} - -var AddAwsInternal = request.NamedHandler{ - Name: "core.AddAwsInternal", - Fn: func(r *request.Request) { - if len(isAwsInternal) == 0 { - return - } - request.AddToUserAgent(r, isAwsInternal) - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go deleted file mode 100644 index 3ad1e798d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go +++ /dev/null @@ -1,100 +0,0 @@ -package credentials - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var ( - // ErrNoValidProvidersFoundInChain Is returned when there are no valid - // providers in the ChainProvider. - // - // This has been deprecated. For verbose error messaging set - // aws.Config.CredentialsChainVerboseErrors to true. - ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", - `no valid providers in chain. Deprecated. - For verbose messaging see aws.Config.CredentialsChainVerboseErrors`, - nil) -) - -// A ChainProvider will search for a provider which returns credentials -// and cache that provider until Retrieve is called again. -// -// The ChainProvider provides a way of chaining multiple providers together -// which will pick the first available using priority order of the Providers -// in the list. -// -// If none of the Providers retrieve valid credentials Value, ChainProvider's -// Retrieve() will return the error ErrNoValidProvidersFoundInChain. -// -// If a Provider is found which returns valid credentials Value ChainProvider -// will cache that Provider for all calls to IsExpired(), until Retrieve is -// called again. -// -// Example of ChainProvider to be used with an EnvProvider and EC2RoleProvider. -// In this example EnvProvider will first check if any credentials are available -// via the environment variables. If there are none ChainProvider will check -// the next Provider in the list, EC2RoleProvider in this case. If EC2RoleProvider -// does not return any credentials ChainProvider will return the error -// ErrNoValidProvidersFoundInChain -// -// creds := credentials.NewChainCredentials( -// []credentials.Provider{ -// &credentials.EnvProvider{}, -// &ec2rolecreds.EC2RoleProvider{ -// Client: ec2metadata.New(sess), -// }, -// }) -// -// // Usage of ChainCredentials with aws.Config -// svc := ec2.New(session.Must(session.NewSession(&aws.Config{ -// Credentials: creds, -// }))) -// -type ChainProvider struct { - Providers []Provider - curr Provider - VerboseErrors bool -} - -// NewChainCredentials returns a pointer to a new Credentials object -// wrapping a chain of providers. -func NewChainCredentials(providers []Provider) *Credentials { - return NewCredentials(&ChainProvider{ - Providers: append([]Provider{}, providers...), - }) -} - -// Retrieve returns the credentials value or error if no provider returned -// without error. -// -// If a provider is found it will be cached and any calls to IsExpired() -// will return the expired state of the cached provider. -func (c *ChainProvider) Retrieve() (Value, error) { - var errs []error - for _, p := range c.Providers { - creds, err := p.Retrieve() - if err == nil { - c.curr = p - return creds, nil - } - errs = append(errs, err) - } - c.curr = nil - - var err error - err = ErrNoValidProvidersFoundInChain - if c.VerboseErrors { - err = awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs) - } - return Value{}, err -} - -// IsExpired will returned the expired state of the currently cached provider -// if there is one. If there is no current provider, true will be returned. -func (c *ChainProvider) IsExpired() bool { - if c.curr != nil { - return c.curr.IsExpired() - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_background_go1.5.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_background_go1.5.go deleted file mode 100644 index 6e3406b1f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_background_go1.5.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build !go1.7 -// +build !go1.7 - -package credentials - -import ( - "github.com/aws/aws-sdk-go/internal/context" -) - -// backgroundContext returns a context that will never be canceled, has no -// values, and no deadline. This context is used by the SDK to provide -// backwards compatibility with non-context API operations and functionality. -// -// Go 1.6 and before: -// This context function is equivalent to context.Background in the Go stdlib. -// -// Go 1.7 and later: -// The context returned will be the value returned by context.Background() -// -// See https://golang.org/pkg/context for more information on Contexts. -func backgroundContext() Context { - return context.BackgroundCtx -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_background_go1.7.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_background_go1.7.go deleted file mode 100644 index a68df0ee7..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_background_go1.7.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build go1.7 -// +build go1.7 - -package credentials - -import "context" - -// backgroundContext returns a context that will never be canceled, has no -// values, and no deadline. This context is used by the SDK to provide -// backwards compatibility with non-context API operations and functionality. -// -// Go 1.6 and before: -// This context function is equivalent to context.Background in the Go stdlib. -// -// Go 1.7 and later: -// The context returned will be the value returned by context.Background() -// -// See https://golang.org/pkg/context for more information on Contexts. -func backgroundContext() Context { - return context.Background() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_go1.5.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_go1.5.go deleted file mode 100644 index 0345fab2d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_go1.5.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build !go1.9 -// +build !go1.9 - -package credentials - -import "time" - -// Context is an copy of the Go v1.7 stdlib's context.Context interface. -// It is represented as a SDK interface to enable you to use the "WithContext" -// API methods with Go v1.6 and a Context type such as golang.org/x/net/context. -// -// This type, aws.Context, and context.Context are equivalent. -// -// See https://golang.org/pkg/context on how to use contexts. -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. - 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. - Value(key interface{}) interface{} -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_go1.9.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_go1.9.go deleted file mode 100644 index 79018aba7..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/context_go1.9.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build go1.9 -// +build go1.9 - -package credentials - -import "context" - -// Context is an alias of the Go stdlib's context.Context interface. -// It can be used within the SDK's API operation "WithContext" methods. -// -// This type, aws.Context, and context.Context are equivalent. -// -// See https://golang.org/pkg/context on how to use contexts. -type Context = context.Context diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go deleted file mode 100644 index a880a3de8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go +++ /dev/null @@ -1,383 +0,0 @@ -// Package credentials provides credential retrieval and management -// -// The Credentials is the primary method of getting access to and managing -// credentials Values. Using dependency injection retrieval of the credential -// values is handled by a object which satisfies the Provider interface. -// -// By default the Credentials.Get() will cache the successful result of a -// Provider's Retrieve() until Provider.IsExpired() returns true. At which -// point Credentials will call Provider's Retrieve() to get new credential Value. -// -// The Provider is responsible for determining when credentials Value have expired. -// It is also important to note that Credentials will always call Retrieve the -// first time Credentials.Get() is called. -// -// Example of using the environment variable credentials. -// -// creds := credentials.NewEnvCredentials() -// -// // Retrieve the credentials value -// credValue, err := creds.Get() -// if err != nil { -// // handle error -// } -// -// Example of forcing credentials to expire and be refreshed on the next Get(). -// This may be helpful to proactively expire credentials and refresh them sooner -// than they would naturally expire on their own. -// -// creds := credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{}) -// creds.Expire() -// credsValue, err := creds.Get() -// // New credentials will be retrieved instead of from cache. -// -// -// Custom Provider -// -// Each Provider built into this package also provides a helper method to generate -// a Credentials pointer setup with the provider. To use a custom Provider just -// create a type which satisfies the Provider interface and pass it to the -// NewCredentials method. -// -// type MyProvider struct{} -// func (m *MyProvider) Retrieve() (Value, error) {...} -// func (m *MyProvider) IsExpired() bool {...} -// -// creds := credentials.NewCredentials(&MyProvider{}) -// credValue, err := creds.Get() -// -package credentials - -import ( - "fmt" - "sync" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/internal/sync/singleflight" -) - -// AnonymousCredentials is an empty Credential object that can be used as -// dummy placeholder credentials for requests that do not need signed. -// -// This Credentials can be used to configure a service to not sign requests -// when making service API calls. For example, when accessing public -// s3 buckets. -// -// svc := s3.New(session.Must(session.NewSession(&aws.Config{ -// Credentials: credentials.AnonymousCredentials, -// }))) -// // Access public S3 buckets. -var AnonymousCredentials = NewStaticCredentials("", "", "") - -// A Value is the AWS credentials value for individual credential fields. -type Value struct { - // AWS Access key ID - AccessKeyID string - - // AWS Secret Access Key - SecretAccessKey string - - // AWS Session Token - SessionToken string - - // Provider used to get credentials - ProviderName string -} - -// HasKeys returns if the credentials Value has both AccessKeyID and -// SecretAccessKey value set. -func (v Value) HasKeys() bool { - return len(v.AccessKeyID) != 0 && len(v.SecretAccessKey) != 0 -} - -// A Provider is the interface for any component which will provide credentials -// Value. A provider is required to manage its own Expired state, and what to -// be expired means. -// -// The Provider should not need to implement its own mutexes, because -// that will be managed by Credentials. -type Provider interface { - // Retrieve returns nil if it successfully retrieved the value. - // Error is returned if the value were not obtainable, or empty. - Retrieve() (Value, error) - - // IsExpired returns if the credentials are no longer valid, and need - // to be retrieved. - IsExpired() bool -} - -// ProviderWithContext is a Provider that can retrieve credentials with a Context -type ProviderWithContext interface { - Provider - - RetrieveWithContext(Context) (Value, error) -} - -// An Expirer is an interface that Providers can implement to expose the expiration -// time, if known. If the Provider cannot accurately provide this info, -// it should not implement this interface. -type Expirer interface { - // The time at which the credentials are no longer valid - ExpiresAt() time.Time -} - -// An ErrorProvider is a stub credentials provider that always returns an error -// this is used by the SDK when construction a known provider is not possible -// due to an error. -type ErrorProvider struct { - // The error to be returned from Retrieve - Err error - - // The provider name to set on the Retrieved returned Value - ProviderName string -} - -// Retrieve will always return the error that the ErrorProvider was created with. -func (p ErrorProvider) Retrieve() (Value, error) { - return Value{ProviderName: p.ProviderName}, p.Err -} - -// IsExpired will always return not expired. -func (p ErrorProvider) IsExpired() bool { - return false -} - -// A Expiry provides shared expiration logic to be used by credentials -// providers to implement expiry functionality. -// -// The best method to use this struct is as an anonymous field within the -// provider's struct. -// -// Example: -// type EC2RoleProvider struct { -// Expiry -// ... -// } -type Expiry struct { - // The date/time when to expire on - expiration time.Time - - // If set will be used by IsExpired to determine the current time. - // Defaults to time.Now if CurrentTime is not set. Available for testing - // to be able to mock out the current time. - CurrentTime func() time.Time -} - -// SetExpiration sets the expiration IsExpired will check when called. -// -// If window is greater than 0 the expiration time will be reduced by the -// window value. -// -// Using a window is helpful to trigger credentials to expire sooner than -// the expiration time given to ensure no requests are made with expired -// tokens. -func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) { - // Passed in expirations should have the monotonic clock values stripped. - // This ensures time comparisons will be based on wall-time. - e.expiration = expiration.Round(0) - if window > 0 { - e.expiration = e.expiration.Add(-window) - } -} - -// IsExpired returns if the credentials are expired. -func (e *Expiry) IsExpired() bool { - curTime := e.CurrentTime - if curTime == nil { - curTime = time.Now - } - return e.expiration.Before(curTime()) -} - -// ExpiresAt returns the expiration time of the credential -func (e *Expiry) ExpiresAt() time.Time { - return e.expiration -} - -// A Credentials provides concurrency safe retrieval of AWS credentials Value. -// Credentials will cache the credentials value until they expire. Once the value -// expires the next Get will attempt to retrieve valid credentials. -// -// Credentials is safe to use across multiple goroutines and will manage the -// synchronous state so the Providers do not need to implement their own -// synchronization. -// -// The first Credentials.Get() will always call Provider.Retrieve() to get the -// first instance of the credentials Value. All calls to Get() after that -// will return the cached credentials Value until IsExpired() returns true. -type Credentials struct { - sf singleflight.Group - - m sync.RWMutex - creds Value - provider Provider -} - -// NewCredentials returns a pointer to a new Credentials with the provider set. -func NewCredentials(provider Provider) *Credentials { - c := &Credentials{ - provider: provider, - } - return c -} - -// GetWithContext returns the credentials value, or error if the credentials -// Value failed to be retrieved. Will return early if the passed in context is -// canceled. -// -// Will return the cached credentials Value if it has not expired. If the -// credentials Value has expired the Provider's Retrieve() will be called -// to refresh the credentials. -// -// If Credentials.Expire() was called the credentials Value will be force -// expired, and the next call to Get() will cause them to be refreshed. -// -// Passed in Context is equivalent to aws.Context, and context.Context. -func (c *Credentials) GetWithContext(ctx Context) (Value, error) { - // Check if credentials are cached, and not expired. - select { - case curCreds, ok := <-c.asyncIsExpired(): - // ok will only be true, of the credentials were not expired. ok will - // be false and have no value if the credentials are expired. - if ok { - return curCreds, nil - } - case <-ctx.Done(): - return Value{}, awserr.New("RequestCanceled", - "request context canceled", ctx.Err()) - } - - // Cannot pass context down to the actual retrieve, because the first - // context would cancel the whole group when there is not direct - // association of items in the group. - resCh := c.sf.DoChan("", func() (interface{}, error) { - return c.singleRetrieve(&suppressedContext{ctx}) - }) - select { - case res := <-resCh: - return res.Val.(Value), res.Err - case <-ctx.Done(): - return Value{}, awserr.New("RequestCanceled", - "request context canceled", ctx.Err()) - } -} - -func (c *Credentials) singleRetrieve(ctx Context) (interface{}, error) { - c.m.Lock() - defer c.m.Unlock() - - if curCreds := c.creds; !c.isExpiredLocked(curCreds) { - return curCreds, nil - } - - var creds Value - var err error - if p, ok := c.provider.(ProviderWithContext); ok { - creds, err = p.RetrieveWithContext(ctx) - } else { - creds, err = c.provider.Retrieve() - } - if err == nil { - c.creds = creds - } - - return creds, err -} - -// Get returns the credentials value, or error if the credentials Value failed -// to be retrieved. -// -// Will return the cached credentials Value if it has not expired. If the -// credentials Value has expired the Provider's Retrieve() will be called -// to refresh the credentials. -// -// If Credentials.Expire() was called the credentials Value will be force -// expired, and the next call to Get() will cause them to be refreshed. -func (c *Credentials) Get() (Value, error) { - return c.GetWithContext(backgroundContext()) -} - -// Expire expires the credentials and forces them to be retrieved on the -// next call to Get(). -// -// This will override the Provider's expired state, and force Credentials -// to call the Provider's Retrieve(). -func (c *Credentials) Expire() { - c.m.Lock() - defer c.m.Unlock() - - c.creds = Value{} -} - -// IsExpired returns if the credentials are no longer valid, and need -// to be retrieved. -// -// If the Credentials were forced to be expired with Expire() this will -// reflect that override. -func (c *Credentials) IsExpired() bool { - c.m.RLock() - defer c.m.RUnlock() - - return c.isExpiredLocked(c.creds) -} - -// asyncIsExpired returns a channel of credentials Value. If the channel is -// closed the credentials are expired and credentials value are not empty. -func (c *Credentials) asyncIsExpired() <-chan Value { - ch := make(chan Value, 1) - go func() { - c.m.RLock() - defer c.m.RUnlock() - - if curCreds := c.creds; !c.isExpiredLocked(curCreds) { - ch <- curCreds - } - - close(ch) - }() - - return ch -} - -// isExpiredLocked helper method wrapping the definition of expired credentials. -func (c *Credentials) isExpiredLocked(creds interface{}) bool { - return creds == nil || creds.(Value) == Value{} || c.provider.IsExpired() -} - -// ExpiresAt provides access to the functionality of the Expirer interface of -// the underlying Provider, if it supports that interface. Otherwise, it returns -// an error. -func (c *Credentials) ExpiresAt() (time.Time, error) { - c.m.RLock() - defer c.m.RUnlock() - - expirer, ok := c.provider.(Expirer) - if !ok { - return time.Time{}, awserr.New("ProviderNotExpirer", - fmt.Sprintf("provider %s does not support ExpiresAt()", - c.creds.ProviderName), - nil) - } - if c.creds == (Value{}) { - // set expiration time to the distant past - return time.Time{}, nil - } - return expirer.ExpiresAt(), nil -} - -type suppressedContext struct { - Context -} - -func (s *suppressedContext) Deadline() (deadline time.Time, ok bool) { - return time.Time{}, false -} - -func (s *suppressedContext) Done() <-chan struct{} { - return nil -} - -func (s *suppressedContext) Err() error { - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go deleted file mode 100644 index 92af5b725..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go +++ /dev/null @@ -1,188 +0,0 @@ -package ec2rolecreds - -import ( - "bufio" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkuri" -) - -// ProviderName provides a name of EC2Role provider -const ProviderName = "EC2RoleProvider" - -// A EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if -// those credentials are expired. -// -// Example how to configure the EC2RoleProvider with custom http Client, Endpoint -// or ExpiryWindow -// -// p := &ec2rolecreds.EC2RoleProvider{ -// // Pass in a custom timeout to be used when requesting -// // IAM EC2 Role credentials. -// Client: ec2metadata.New(sess, aws.Config{ -// HTTPClient: &http.Client{Timeout: 10 * time.Second}, -// }), -// -// // Do not use early expiry of credentials. If a non zero value is -// // specified the credentials will be expired early -// ExpiryWindow: 0, -// } -type EC2RoleProvider struct { - credentials.Expiry - - // Required EC2Metadata client to use when connecting to EC2 metadata service. - Client *ec2metadata.EC2Metadata - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewCredentials returns a pointer to a new Credentials object wrapping -// the EC2RoleProvider. Takes a ConfigProvider to create a EC2Metadata client. -// The ConfigProvider is satisfied by the session.Session type. -func NewCredentials(c client.ConfigProvider, options ...func(*EC2RoleProvider)) *credentials.Credentials { - p := &EC2RoleProvider{ - Client: ec2metadata.New(c), - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping -// the EC2RoleProvider. Takes a EC2Metadata client to use when connecting to EC2 -// metadata service. -func NewCredentialsWithClient(client *ec2metadata.EC2Metadata, options ...func(*EC2RoleProvider)) *credentials.Credentials { - p := &EC2RoleProvider{ - Client: client, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve retrieves credentials from the EC2 service. -// Error will be returned if the request fails, or unable to extract -// the desired credentials. -func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) { - return m.RetrieveWithContext(aws.BackgroundContext()) -} - -// RetrieveWithContext retrieves credentials from the EC2 service. -// Error will be returned if the request fails, or unable to extract -// the desired credentials. -func (m *EC2RoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) { - credsList, err := requestCredList(ctx, m.Client) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - if len(credsList) == 0 { - return credentials.Value{ProviderName: ProviderName}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil) - } - credsName := credsList[0] - - roleCreds, err := requestCred(ctx, m.Client, credsName) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow) - - return credentials.Value{ - AccessKeyID: roleCreds.AccessKeyID, - SecretAccessKey: roleCreds.SecretAccessKey, - SessionToken: roleCreds.Token, - ProviderName: ProviderName, - }, nil -} - -// A ec2RoleCredRespBody provides the shape for unmarshaling credential -// request responses. -type ec2RoleCredRespBody struct { - // Success State - Expiration time.Time - AccessKeyID string - SecretAccessKey string - Token string - - // Error state - Code string - Message string -} - -const iamSecurityCredsPath = "iam/security-credentials/" - -// requestCredList requests a list of credentials from the EC2 service. -// If there are no credentials, or there is an error making or receiving the request -func requestCredList(ctx aws.Context, client *ec2metadata.EC2Metadata) ([]string, error) { - resp, err := client.GetMetadataWithContext(ctx, iamSecurityCredsPath) - if err != nil { - return nil, awserr.New("EC2RoleRequestError", "no EC2 instance role found", err) - } - - credsList := []string{} - s := bufio.NewScanner(strings.NewReader(resp)) - for s.Scan() { - credsList = append(credsList, s.Text()) - } - - if err := s.Err(); err != nil { - return nil, awserr.New(request.ErrCodeSerialization, - "failed to read EC2 instance role from metadata service", err) - } - - return credsList, nil -} - -// requestCred requests the credentials for a specific credentials from the EC2 service. -// -// If the credentials cannot be found, or there is an error reading the response -// and error will be returned. -func requestCred(ctx aws.Context, client *ec2metadata.EC2Metadata, credsName string) (ec2RoleCredRespBody, error) { - resp, err := client.GetMetadataWithContext(ctx, sdkuri.PathJoin(iamSecurityCredsPath, credsName)) - if err != nil { - return ec2RoleCredRespBody{}, - awserr.New("EC2RoleRequestError", - fmt.Sprintf("failed to get %s EC2 instance role credentials", credsName), - err) - } - - respCreds := ec2RoleCredRespBody{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&respCreds); err != nil { - return ec2RoleCredRespBody{}, - awserr.New(request.ErrCodeSerialization, - fmt.Sprintf("failed to decode %s EC2 instance role credentials", credsName), - err) - } - - if respCreds.Code != "Success" { - // If an error code was returned something failed requesting the role. - return ec2RoleCredRespBody{}, awserr.New(respCreds.Code, respCreds.Message, nil) - } - - return respCreds, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go deleted file mode 100644 index 329f788a3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go +++ /dev/null @@ -1,255 +0,0 @@ -// Package endpointcreds provides support for retrieving credentials from an -// arbitrary HTTP endpoint. -// -// The credentials endpoint Provider can receive both static and refreshable -// credentials that will expire. Credentials are static when an "Expiration" -// value is not provided in the endpoint's response. -// -// Static credentials will never expire once they have been retrieved. The format -// of the static credentials response: -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// } -// -// Refreshable credentials will expire within the "ExpiryWindow" of the Expiration -// value in the response. The format of the refreshable credentials response: -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// "Token" : "AQoDY....=", -// "Expiration" : "2016-02-25T06:03:31Z" -// } -// -// Errors should be returned in the following format and only returned with 400 -// or 500 HTTP status codes. -// { -// "code": "ErrorCode", -// "message": "Helpful error message." -// } -package endpointcreds - -import ( - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" -) - -// ProviderName is the name of the credentials provider. -const ProviderName = `CredentialsEndpointProvider` - -// Provider satisfies the credentials.Provider interface, and is a client to -// retrieve credentials from an arbitrary endpoint. -type Provider struct { - staticCreds bool - credentials.Expiry - - // Requires a AWS Client to make HTTP requests to the endpoint with. - // the Endpoint the request will be made to is provided by the aws.Config's - // Endpoint value. - Client *client.Client - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration - - // Optional authorization token value if set will be used as the value of - // the Authorization header of the endpoint credential request. - // - // When constructed from environment, the provider will use the value of - // AWS_CONTAINER_AUTHORIZATION_TOKEN environment variable as the token - // - // Will be overridden if AuthorizationTokenProvider is configured - AuthorizationToken string - - // Optional auth provider func to dynamically load the auth token from a file - // everytime a credential is retrieved - // - // When constructed from environment, the provider will read and use the content - // of the file pointed to by AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE environment variable - // as the auth token everytime credentials are retrieved - // - // Will override AuthorizationToken if configured - AuthorizationTokenProvider AuthTokenProvider -} - -// AuthTokenProvider defines an interface to dynamically load a value to be passed -// for the Authorization header of a credentials request. -type AuthTokenProvider interface { - GetToken() (string, error) -} - -// TokenProviderFunc is a func type implementing AuthTokenProvider interface -// and enables customizing token provider behavior -type TokenProviderFunc func() (string, error) - -// GetToken func retrieves auth token according to TokenProviderFunc implementation -func (p TokenProviderFunc) GetToken() (string, error) { - return p() -} - -// NewProviderClient returns a credentials Provider for retrieving AWS credentials -// from arbitrary endpoint. -func NewProviderClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) credentials.Provider { - p := &Provider{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "CredentialsEndpoint", - Endpoint: endpoint, - }, - handlers, - ), - } - - p.Client.Handlers.Unmarshal.PushBack(unmarshalHandler) - p.Client.Handlers.UnmarshalError.PushBack(unmarshalError) - p.Client.Handlers.Validate.Clear() - p.Client.Handlers.Validate.PushBack(validateEndpointHandler) - - for _, option := range options { - option(p) - } - - return p -} - -// NewCredentialsClient returns a pointer to a new Credentials object -// wrapping the endpoint credentials Provider. -func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials { - return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...)) -} - -// IsExpired returns true if the credentials retrieved are expired, or not yet -// retrieved. -func (p *Provider) IsExpired() bool { - if p.staticCreds { - return false - } - return p.Expiry.IsExpired() -} - -// Retrieve will attempt to request the credentials from the endpoint the Provider -// was configured for. And error will be returned if the retrieval fails. -func (p *Provider) Retrieve() (credentials.Value, error) { - return p.RetrieveWithContext(aws.BackgroundContext()) -} - -// RetrieveWithContext will attempt to request the credentials from the endpoint the Provider -// was configured for. And error will be returned if the retrieval fails. -func (p *Provider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) { - resp, err := p.getCredentials(ctx) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, - awserr.New("CredentialsEndpointError", "failed to load credentials", err) - } - - if resp.Expiration != nil { - p.SetExpiration(*resp.Expiration, p.ExpiryWindow) - } else { - p.staticCreds = true - } - - return credentials.Value{ - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.Token, - ProviderName: ProviderName, - }, nil -} - -type getCredentialsOutput struct { - Expiration *time.Time - AccessKeyID string - SecretAccessKey string - Token string -} - -type errorOutput struct { - Code string `json:"code"` - Message string `json:"message"` -} - -func (p *Provider) getCredentials(ctx aws.Context) (*getCredentialsOutput, error) { - op := &request.Operation{ - Name: "GetCredentials", - HTTPMethod: "GET", - } - - out := &getCredentialsOutput{} - req := p.Client.NewRequest(op, nil, out) - req.SetContext(ctx) - req.HTTPRequest.Header.Set("Accept", "application/json") - - authToken := p.AuthorizationToken - var err error - if p.AuthorizationTokenProvider != nil { - authToken, err = p.AuthorizationTokenProvider.GetToken() - if err != nil { - return nil, fmt.Errorf("get authorization token: %v", err) - } - } - - if strings.ContainsAny(authToken, "\r\n") { - return nil, fmt.Errorf("authorization token contains invalid newline sequence") - } - if len(authToken) != 0 { - req.HTTPRequest.Header.Set("Authorization", authToken) - } - - return out, req.Send() -} - -func validateEndpointHandler(r *request.Request) { - if len(r.ClientInfo.Endpoint) == 0 { - r.Error = aws.ErrMissingEndpoint - } -} - -func unmarshalHandler(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - out := r.Data.(*getCredentialsOutput) - if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&out); err != nil { - r.Error = awserr.New(request.ErrCodeSerialization, - "failed to decode endpoint credentials", - err, - ) - } -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - var errOut errorOutput - err := jsonutil.UnmarshalJSONError(&errOut, r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, - "failed to decode error message", err), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - return - } - - // Response body format is not consistent between metadata endpoints. - // Grab the error message as a string and include that as the source error - r.Error = awserr.New(errOut.Code, errOut.Message, nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go deleted file mode 100644 index 54c5cf733..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go +++ /dev/null @@ -1,74 +0,0 @@ -package credentials - -import ( - "os" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// EnvProviderName provides a name of Env provider -const EnvProviderName = "EnvProvider" - -var ( - // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be - // found in the process's environment. - ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) - - // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key - // can't be found in the process's environment. - ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) -) - -// A EnvProvider retrieves credentials from the environment variables of the -// running process. Environment credentials never expire. -// -// Environment variables used: -// -// * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY -// -// * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY -type EnvProvider struct { - retrieved bool -} - -// NewEnvCredentials returns a pointer to a new Credentials object -// wrapping the environment variable provider. -func NewEnvCredentials() *Credentials { - return NewCredentials(&EnvProvider{}) -} - -// Retrieve retrieves the keys from the environment. -func (e *EnvProvider) Retrieve() (Value, error) { - e.retrieved = false - - id := os.Getenv("AWS_ACCESS_KEY_ID") - if id == "" { - id = os.Getenv("AWS_ACCESS_KEY") - } - - secret := os.Getenv("AWS_SECRET_ACCESS_KEY") - if secret == "" { - secret = os.Getenv("AWS_SECRET_KEY") - } - - if id == "" { - return Value{ProviderName: EnvProviderName}, ErrAccessKeyIDNotFound - } - - if secret == "" { - return Value{ProviderName: EnvProviderName}, ErrSecretAccessKeyNotFound - } - - e.retrieved = true - return Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: os.Getenv("AWS_SESSION_TOKEN"), - ProviderName: EnvProviderName, - }, nil -} - -// IsExpired returns if the credentials have been retrieved. -func (e *EnvProvider) IsExpired() bool { - return !e.retrieved -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini b/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini deleted file mode 100644 index 7fc91d9d2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini +++ /dev/null @@ -1,12 +0,0 @@ -[default] -aws_access_key_id = accessKey -aws_secret_access_key = secret -aws_session_token = token - -[no_token] -aws_access_key_id = accessKey -aws_secret_access_key = secret - -[with_colon] -aws_access_key_id: accessKey -aws_secret_access_key: secret diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/processcreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/processcreds/provider.go deleted file mode 100644 index 18694f07f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/processcreds/provider.go +++ /dev/null @@ -1,438 +0,0 @@ -/* -Package processcreds is a credential Provider to retrieve `credential_process` -credentials. - -WARNING: The following describes a method of sourcing credentials from an external -process. This can potentially be dangerous, so proceed with caution. Other -credential providers should be preferred if at all possible. If using this -option, you should make sure that the config file is as locked down as possible -using security best practices for your operating system. - -You can use credentials from a `credential_process` in a variety of ways. - -One way is to setup your shared config file, located in the default -location, with the `credential_process` key and the command you want to be -called. You also need to set the AWS_SDK_LOAD_CONFIG environment variable -(e.g., `export AWS_SDK_LOAD_CONFIG=1`) to use the shared config file. - - [default] - credential_process = /command/to/call - -Creating a new session will use the credential process to retrieve credentials. -NOTE: If there are credentials in the profile you are using, the credential -process will not be used. - - // Initialize a session to load credentials. - sess, _ := session.NewSession(&aws.Config{ - Region: aws.String("us-east-1")}, - ) - - // Create S3 service client to use the credentials. - svc := s3.New(sess) - -Another way to use the `credential_process` method is by using -`credentials.NewCredentials()` and providing a command to be executed to -retrieve credentials: - - // Create credentials using the ProcessProvider. - creds := processcreds.NewCredentials("/path/to/command") - - // Create service client value configured for credentials. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -You can set a non-default timeout for the `credential_process` with another -constructor, `credentials.NewCredentialsTimeout()`, providing the timeout. To -set a one minute timeout: - - // Create credentials using the ProcessProvider. - creds := processcreds.NewCredentialsTimeout( - "/path/to/command", - time.Duration(500) * time.Millisecond) - -If you need more control, you can set any configurable options in the -credentials using one or more option functions. For example, you can set a two -minute timeout, a credential duration of 60 minutes, and a maximum stdout -buffer size of 2k. - - creds := processcreds.NewCredentials( - "/path/to/command", - func(opt *ProcessProvider) { - opt.Timeout = time.Duration(2) * time.Minute - opt.Duration = time.Duration(60) * time.Minute - opt.MaxBufSize = 2048 - }) - -You can also use your own `exec.Cmd`: - - // Create an exec.Cmd - myCommand := exec.Command("/path/to/command") - - // Create credentials using your exec.Cmd and custom timeout - creds := processcreds.NewCredentialsCommand( - myCommand, - func(opt *processcreds.ProcessProvider) { - opt.Timeout = time.Duration(1) * time.Second - }) -*/ -package processcreds - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "runtime" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -const ( - // ProviderName is the name this credentials provider will label any - // returned credentials Value with. - ProviderName = `ProcessProvider` - - // ErrCodeProcessProviderParse error parsing process output - ErrCodeProcessProviderParse = "ProcessProviderParseError" - - // ErrCodeProcessProviderVersion version error in output - ErrCodeProcessProviderVersion = "ProcessProviderVersionError" - - // ErrCodeProcessProviderRequired required attribute missing in output - ErrCodeProcessProviderRequired = "ProcessProviderRequiredError" - - // ErrCodeProcessProviderExecution execution of command failed - ErrCodeProcessProviderExecution = "ProcessProviderExecutionError" - - // errMsgProcessProviderTimeout process took longer than allowed - errMsgProcessProviderTimeout = "credential process timed out" - - // errMsgProcessProviderProcess process error - errMsgProcessProviderProcess = "error in credential_process" - - // errMsgProcessProviderParse problem parsing output - errMsgProcessProviderParse = "parse failed of credential_process output" - - // errMsgProcessProviderVersion version error in output - errMsgProcessProviderVersion = "wrong version in process output (not 1)" - - // errMsgProcessProviderMissKey missing access key id in output - errMsgProcessProviderMissKey = "missing AccessKeyId in process output" - - // errMsgProcessProviderMissSecret missing secret acess key in output - errMsgProcessProviderMissSecret = "missing SecretAccessKey in process output" - - // errMsgProcessProviderPrepareCmd prepare of command failed - errMsgProcessProviderPrepareCmd = "failed to prepare command" - - // errMsgProcessProviderEmptyCmd command must not be empty - errMsgProcessProviderEmptyCmd = "command must not be empty" - - // errMsgProcessProviderPipe failed to initialize pipe - errMsgProcessProviderPipe = "failed to initialize pipe" - - // DefaultDuration is the default amount of time in minutes that the - // credentials will be valid for. - DefaultDuration = time.Duration(15) * time.Minute - - // DefaultBufSize limits buffer size from growing to an enormous - // amount due to a faulty process. - DefaultBufSize = int(8 * sdkio.KibiByte) - - // DefaultTimeout default limit on time a process can run. - DefaultTimeout = time.Duration(1) * time.Minute -) - -// ProcessProvider satisfies the credentials.Provider interface, and is a -// client to retrieve credentials from a process. -type ProcessProvider struct { - staticCreds bool - credentials.Expiry - originalCommand []string - - // Expiry duration of the credentials. Defaults to 15 minutes if not set. - Duration time.Duration - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration - - // A string representing an os command that should return a JSON with - // credential information. - command *exec.Cmd - - // MaxBufSize limits memory usage from growing to an enormous - // amount due to a faulty process. - MaxBufSize int - - // Timeout limits the time a process can run. - Timeout time.Duration -} - -// NewCredentials returns a pointer to a new Credentials object wrapping the -// ProcessProvider. The credentials will expire every 15 minutes by default. -func NewCredentials(command string, options ...func(*ProcessProvider)) *credentials.Credentials { - p := &ProcessProvider{ - command: exec.Command(command), - Duration: DefaultDuration, - Timeout: DefaultTimeout, - MaxBufSize: DefaultBufSize, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsTimeout returns a pointer to a new Credentials object with -// the specified command and timeout, and default duration and max buffer size. -func NewCredentialsTimeout(command string, timeout time.Duration) *credentials.Credentials { - p := NewCredentials(command, func(opt *ProcessProvider) { - opt.Timeout = timeout - }) - - return p -} - -// NewCredentialsCommand returns a pointer to a new Credentials object with -// the specified command, and default timeout, duration and max buffer size. -func NewCredentialsCommand(command *exec.Cmd, options ...func(*ProcessProvider)) *credentials.Credentials { - p := &ProcessProvider{ - command: command, - Duration: DefaultDuration, - Timeout: DefaultTimeout, - MaxBufSize: DefaultBufSize, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// A CredentialProcessResponse is the AWS credentials format that must be -// returned when executing an external credential_process. -type CredentialProcessResponse struct { - // As of this writing, the Version key must be set to 1. This might - // increment over time as the structure evolves. - Version int - - // The access key ID that identifies the temporary security credentials. - AccessKeyID string `json:"AccessKeyId"` - - // The secret access key that can be used to sign requests. - SecretAccessKey string - - // The token that users must pass to the service API to use the temporary credentials. - SessionToken string - - // The date on which the current credentials expire. - Expiration *time.Time -} - -// Retrieve executes the 'credential_process' and returns the credentials. -func (p *ProcessProvider) Retrieve() (credentials.Value, error) { - out, err := p.executeCredentialProcess() - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - // Serialize and validate response - resp := &CredentialProcessResponse{} - if err = json.Unmarshal(out, resp); err != nil { - return credentials.Value{ProviderName: ProviderName}, awserr.New( - ErrCodeProcessProviderParse, - fmt.Sprintf("%s: %s", errMsgProcessProviderParse, string(out)), - err) - } - - if resp.Version != 1 { - return credentials.Value{ProviderName: ProviderName}, awserr.New( - ErrCodeProcessProviderVersion, - errMsgProcessProviderVersion, - nil) - } - - if len(resp.AccessKeyID) == 0 { - return credentials.Value{ProviderName: ProviderName}, awserr.New( - ErrCodeProcessProviderRequired, - errMsgProcessProviderMissKey, - nil) - } - - if len(resp.SecretAccessKey) == 0 { - return credentials.Value{ProviderName: ProviderName}, awserr.New( - ErrCodeProcessProviderRequired, - errMsgProcessProviderMissSecret, - nil) - } - - // Handle expiration - p.staticCreds = resp.Expiration == nil - if resp.Expiration != nil { - p.SetExpiration(*resp.Expiration, p.ExpiryWindow) - } - - return credentials.Value{ - ProviderName: ProviderName, - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.SessionToken, - }, nil -} - -// IsExpired returns true if the credentials retrieved are expired, or not yet -// retrieved. -func (p *ProcessProvider) IsExpired() bool { - if p.staticCreds { - return false - } - return p.Expiry.IsExpired() -} - -// prepareCommand prepares the command to be executed. -func (p *ProcessProvider) prepareCommand() error { - - var cmdArgs []string - if runtime.GOOS == "windows" { - cmdArgs = []string{"cmd.exe", "/C"} - } else { - cmdArgs = []string{"sh", "-c"} - } - - if len(p.originalCommand) == 0 { - p.originalCommand = make([]string, len(p.command.Args)) - copy(p.originalCommand, p.command.Args) - - // check for empty command because it succeeds - if len(strings.TrimSpace(p.originalCommand[0])) < 1 { - return awserr.New( - ErrCodeProcessProviderExecution, - fmt.Sprintf( - "%s: %s", - errMsgProcessProviderPrepareCmd, - errMsgProcessProviderEmptyCmd), - nil) - } - } - - cmdArgs = append(cmdArgs, p.originalCommand...) - p.command = exec.Command(cmdArgs[0], cmdArgs[1:]...) - p.command.Env = os.Environ() - - return nil -} - -// executeCredentialProcess starts the credential process on the OS and -// returns the results or an error. -func (p *ProcessProvider) executeCredentialProcess() ([]byte, error) { - - if err := p.prepareCommand(); err != nil { - return nil, err - } - - // Setup the pipes - outReadPipe, outWritePipe, err := os.Pipe() - if err != nil { - return nil, awserr.New( - ErrCodeProcessProviderExecution, - errMsgProcessProviderPipe, - err) - } - - p.command.Stderr = os.Stderr // display stderr on console for MFA - p.command.Stdout = outWritePipe // get creds json on process's stdout - p.command.Stdin = os.Stdin // enable stdin for MFA - - output := bytes.NewBuffer(make([]byte, 0, p.MaxBufSize)) - - stdoutCh := make(chan error, 1) - go readInput( - io.LimitReader(outReadPipe, int64(p.MaxBufSize)), - output, - stdoutCh) - - execCh := make(chan error, 1) - go executeCommand(*p.command, execCh) - - finished := false - var errors []error - for !finished { - select { - case readError := <-stdoutCh: - errors = appendError(errors, readError) - finished = true - case execError := <-execCh: - err := outWritePipe.Close() - errors = appendError(errors, err) - errors = appendError(errors, execError) - if errors != nil { - return output.Bytes(), awserr.NewBatchError( - ErrCodeProcessProviderExecution, - errMsgProcessProviderProcess, - errors) - } - case <-time.After(p.Timeout): - finished = true - return output.Bytes(), awserr.NewBatchError( - ErrCodeProcessProviderExecution, - errMsgProcessProviderTimeout, - errors) // errors can be nil - } - } - - out := output.Bytes() - - if runtime.GOOS == "windows" { - // windows adds slashes to quotes - out = []byte(strings.Replace(string(out), `\"`, `"`, -1)) - } - - return out, nil -} - -// appendError conveniently checks for nil before appending slice -func appendError(errors []error, err error) []error { - if err != nil { - return append(errors, err) - } - return errors -} - -func executeCommand(cmd exec.Cmd, exec chan error) { - // Start the command - err := cmd.Start() - if err == nil { - err = cmd.Wait() - } - - exec <- err -} - -func readInput(r io.Reader, w io.Writer, read chan error) { - tee := io.TeeReader(r, w) - - _, err := ioutil.ReadAll(tee) - - if err == io.EOF { - err = nil - } - - read <- err // will only arrive here when write end of pipe is closed -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go deleted file mode 100644 index 22b5c5d9f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go +++ /dev/null @@ -1,151 +0,0 @@ -package credentials - -import ( - "fmt" - "os" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/internal/ini" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// SharedCredsProviderName provides a name of SharedCreds provider -const SharedCredsProviderName = "SharedCredentialsProvider" - -var ( - // ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found. - ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil) -) - -// A SharedCredentialsProvider retrieves access key pair (access key ID, -// secret access key, and session token if present) credentials from the current -// user's home directory, and keeps track if those credentials are expired. -// -// Profile ini file example: $HOME/.aws/credentials -type SharedCredentialsProvider struct { - // Path to the shared credentials file. - // - // If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the - // env value is empty will default to current user's home directory. - // Linux/OSX: "$HOME/.aws/credentials" - // Windows: "%USERPROFILE%\.aws\credentials" - Filename string - - // AWS Profile to extract credentials from the shared credentials file. If empty - // will default to environment variable "AWS_PROFILE" or "default" if - // environment variable is also not set. - Profile string - - // retrieved states if the credentials have been successfully retrieved. - retrieved bool -} - -// NewSharedCredentials returns a pointer to a new Credentials object -// wrapping the Profile file provider. -func NewSharedCredentials(filename, profile string) *Credentials { - return NewCredentials(&SharedCredentialsProvider{ - Filename: filename, - Profile: profile, - }) -} - -// Retrieve reads and extracts the shared credentials from the current -// users home directory. -func (p *SharedCredentialsProvider) Retrieve() (Value, error) { - p.retrieved = false - - filename, err := p.filename() - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, err - } - - creds, err := loadProfile(filename, p.profile()) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, err - } - - p.retrieved = true - return creds, nil -} - -// IsExpired returns if the shared credentials have expired. -func (p *SharedCredentialsProvider) IsExpired() bool { - return !p.retrieved -} - -// loadProfiles loads from the file pointed to by shared credentials filename for profile. -// The credentials retrieved from the profile will be returned or error. Error will be -// returned if it fails to read from the file, or the data is invalid. -func loadProfile(filename, profile string) (Value, error) { - config, err := ini.OpenFile(filename) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err) - } - - iniProfile, ok := config.GetSection(profile) - if !ok { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to get profile", nil) - } - - id := iniProfile.String("aws_access_key_id") - if len(id) == 0 { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsAccessKey", - fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename), - nil) - } - - secret := iniProfile.String("aws_secret_access_key") - if len(secret) == 0 { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsSecret", - fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename), - nil) - } - - // Default to empty string if not found - token := iniProfile.String("aws_session_token") - - return Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: token, - ProviderName: SharedCredsProviderName, - }, nil -} - -// filename returns the filename to use to read AWS shared credentials. -// -// Will return an error if the user's home directory path cannot be found. -func (p *SharedCredentialsProvider) filename() (string, error) { - if len(p.Filename) != 0 { - return p.Filename, nil - } - - if p.Filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); len(p.Filename) != 0 { - return p.Filename, nil - } - - if home := shareddefaults.UserHomeDir(); len(home) == 0 { - // Backwards compatibility of home directly not found error being returned. - // This error is too verbose, failure when opening the file would of been - // a better error to return. - return "", ErrSharedCredentialsHomeNotFound - } - - p.Filename = shareddefaults.SharedCredentialsFilename() - - return p.Filename, nil -} - -// profile returns the AWS shared credentials profile. If empty will read -// environment variable "AWS_PROFILE". If that is not set profile will -// return "default". -func (p *SharedCredentialsProvider) profile() string { - if p.Profile == "" { - p.Profile = os.Getenv("AWS_PROFILE") - } - if p.Profile == "" { - p.Profile = "default" - } - - return p.Profile -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/doc.go deleted file mode 100644 index 18c940ab3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/doc.go +++ /dev/null @@ -1,60 +0,0 @@ -// Package ssocreds provides a credential provider for retrieving temporary AWS credentials using an SSO access token. -// -// IMPORTANT: The provider in this package does not initiate or perform the AWS SSO login flow. The SDK provider -// expects that you have already performed the SSO login flow using AWS CLI using the "aws sso login" command, or by -// some other mechanism. The provider must find a valid non-expired access token for the AWS SSO user portal URL in -// ~/.aws/sso/cache. If a cached token is not found, it is expired, or the file is malformed an error will be returned. -// -// Loading AWS SSO credentials with the AWS shared configuration file -// -// You can use configure AWS SSO credentials from the AWS shared configuration file by -// providing the specifying the required keys in the profile: -// -// sso_account_id -// sso_region -// sso_role_name -// sso_start_url -// -// For example, the following defines a profile "devsso" and specifies the AWS SSO parameters that defines the target -// account, role, sign-on portal, and the region where the user portal is located. Note: all SSO arguments must be -// provided, or an error will be returned. -// -// [profile devsso] -// sso_start_url = https://my-sso-portal.awsapps.com/start -// sso_role_name = SSOReadOnlyRole -// sso_region = us-east-1 -// sso_account_id = 123456789012 -// -// Using the config module, you can load the AWS SDK shared configuration, and specify that this profile be used to -// retrieve credentials. For example: -// -// sess, err := session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// Profile: "devsso", -// }) -// if err != nil { -// return err -// } -// -// Programmatically loading AWS SSO credentials directly -// -// You can programmatically construct the AWS SSO Provider in your application, and provide the necessary information -// to load and retrieve temporary credentials using an access token from ~/.aws/sso/cache. -// -// svc := sso.New(sess, &aws.Config{ -// Region: aws.String("us-west-2"), // Client Region must correspond to the AWS SSO user portal region -// }) -// -// provider := ssocreds.NewCredentialsWithClient(svc, "123456789012", "SSOReadOnlyRole", "https://my-sso-portal.awsapps.com/start") -// -// credentials, err := provider.Get() -// if err != nil { -// return err -// } -// -// Additional Resources -// -// Configuring the AWS CLI to use AWS Single Sign-On: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -// -// AWS Single Sign-On User Guide: https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html -package ssocreds diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/os.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/os.go deleted file mode 100644 index d4df39a7a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/os.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build !windows -// +build !windows - -package ssocreds - -import "os" - -func getHomeDirectory() string { - return os.Getenv("HOME") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/os_windows.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/os_windows.go deleted file mode 100644 index eb48f61e5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/os_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package ssocreds - -import "os" - -func getHomeDirectory() string { - return os.Getenv("USERPROFILE") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/provider.go deleted file mode 100644 index 4138e725d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/provider.go +++ /dev/null @@ -1,187 +0,0 @@ -package ssocreds - -import ( - "crypto/sha1" - "encoding/hex" - "encoding/json" - "io/ioutil" - "path/filepath" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/auth/bearer" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/service/sso" - "github.com/aws/aws-sdk-go/service/sso/ssoiface" -) - -// ErrCodeSSOProviderInvalidToken is the code type that is returned if loaded token has expired or is otherwise invalid. -// To refresh the SSO session run aws sso login with the corresponding profile. -const ErrCodeSSOProviderInvalidToken = "SSOProviderInvalidToken" - -const invalidTokenMessage = "the SSO session has expired or is invalid" - -func init() { - nowTime = time.Now - defaultCacheLocation = defaultCacheLocationImpl -} - -var nowTime func() time.Time - -// ProviderName is the name of the provider used to specify the source of credentials. -const ProviderName = "SSOProvider" - -var defaultCacheLocation func() string - -func defaultCacheLocationImpl() string { - return filepath.Join(getHomeDirectory(), ".aws", "sso", "cache") -} - -// Provider is an AWS credential provider that retrieves temporary AWS credentials by exchanging an SSO login token. -type Provider struct { - credentials.Expiry - - // The Client which is configured for the AWS Region where the AWS SSO user portal is located. - Client ssoiface.SSOAPI - - // The AWS account that is assigned to the user. - AccountID string - - // The role name that is assigned to the user. - RoleName string - - // The URL that points to the organization's AWS Single Sign-On (AWS SSO) user portal. - StartURL string - - // The filepath the cached token will be retrieved from. If unset Provider will - // use the startURL to determine the filepath at. - // - // ~/.aws/sso/cache/.json - // - // If custom cached token filepath is used, the Provider's startUrl - // parameter will be ignored. - CachedTokenFilepath string - - // Used by the SSOCredentialProvider if a token configuration - // profile is used in the shared config - TokenProvider bearer.TokenProvider -} - -// NewCredentials returns a new AWS Single Sign-On (AWS SSO) credential provider. The ConfigProvider is expected to be configured -// for the AWS Region where the AWS SSO user portal is located. -func NewCredentials(configProvider client.ConfigProvider, accountID, roleName, startURL string, optFns ...func(provider *Provider)) *credentials.Credentials { - return NewCredentialsWithClient(sso.New(configProvider), accountID, roleName, startURL, optFns...) -} - -// NewCredentialsWithClient returns a new AWS Single Sign-On (AWS SSO) credential provider. The provided client is expected to be configured -// for the AWS Region where the AWS SSO user portal is located. -func NewCredentialsWithClient(client ssoiface.SSOAPI, accountID, roleName, startURL string, optFns ...func(provider *Provider)) *credentials.Credentials { - p := &Provider{ - Client: client, - AccountID: accountID, - RoleName: roleName, - StartURL: startURL, - } - - for _, fn := range optFns { - fn(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve retrieves temporary AWS credentials from the configured Amazon Single Sign-On (AWS SSO) user portal -// by exchanging the accessToken present in ~/.aws/sso/cache. -func (p *Provider) Retrieve() (credentials.Value, error) { - return p.RetrieveWithContext(aws.BackgroundContext()) -} - -// RetrieveWithContext retrieves temporary AWS credentials from the configured Amazon Single Sign-On (AWS SSO) user portal -// by exchanging the accessToken present in ~/.aws/sso/cache. -func (p *Provider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) { - var accessToken *string - if p.TokenProvider != nil { - token, err := p.TokenProvider.RetrieveBearerToken(ctx) - if err != nil { - return credentials.Value{}, err - } - accessToken = &token.Value - } else { - if p.CachedTokenFilepath == "" { - cachedTokenFilePath, err := getCachedFilePath(p.StartURL) - if err != nil { - return credentials.Value{}, err - } - p.CachedTokenFilepath = cachedTokenFilePath - } - - tokenFile, err := loadTokenFile(p.CachedTokenFilepath) - if err != nil { - return credentials.Value{}, err - } - accessToken = &tokenFile.AccessToken - } - - output, err := p.Client.GetRoleCredentialsWithContext(ctx, &sso.GetRoleCredentialsInput{ - AccessToken: accessToken, - AccountId: &p.AccountID, - RoleName: &p.RoleName, - }) - if err != nil { - return credentials.Value{}, err - } - - expireTime := time.Unix(0, aws.Int64Value(output.RoleCredentials.Expiration)*int64(time.Millisecond)).UTC() - p.SetExpiration(expireTime, 0) - - return credentials.Value{ - AccessKeyID: aws.StringValue(output.RoleCredentials.AccessKeyId), - SecretAccessKey: aws.StringValue(output.RoleCredentials.SecretAccessKey), - SessionToken: aws.StringValue(output.RoleCredentials.SessionToken), - ProviderName: ProviderName, - }, nil -} - -func getCachedFilePath(startUrl string) (string, error) { - hash := sha1.New() - _, err := hash.Write([]byte(startUrl)) - if err != nil { - return "", err - } - return filepath.Join(defaultCacheLocation(), strings.ToLower(hex.EncodeToString(hash.Sum(nil)))+".json"), nil -} - -type token struct { - AccessToken string `json:"accessToken"` - ExpiresAt rfc3339 `json:"expiresAt"` - Region string `json:"region,omitempty"` - StartURL string `json:"startUrl,omitempty"` -} - -func (t token) Expired() bool { - return nowTime().Round(0).After(time.Time(t.ExpiresAt)) -} - -func loadTokenFile(cachedTokenPath string) (t token, err error) { - fileBytes, err := ioutil.ReadFile(cachedTokenPath) - if err != nil { - return token{}, awserr.New(ErrCodeSSOProviderInvalidToken, invalidTokenMessage, err) - } - - if err := json.Unmarshal(fileBytes, &t); err != nil { - return token{}, awserr.New(ErrCodeSSOProviderInvalidToken, invalidTokenMessage, err) - } - - if len(t.AccessToken) == 0 { - return token{}, awserr.New(ErrCodeSSOProviderInvalidToken, invalidTokenMessage, nil) - } - - if t.Expired() { - return token{}, awserr.New(ErrCodeSSOProviderInvalidToken, invalidTokenMessage, nil) - } - - return t, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/sso_cached_token.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/sso_cached_token.go deleted file mode 100644 index f6fa88451..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/sso_cached_token.go +++ /dev/null @@ -1,237 +0,0 @@ -package ssocreds - -import ( - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "github.com/aws/aws-sdk-go/internal/shareddefaults" - "io/ioutil" - "os" - "path/filepath" - "strconv" - "strings" - "time" -) - -var resolvedOsUserHomeDir = shareddefaults.UserHomeDir - -// StandardCachedTokenFilepath returns the filepath for the cached SSO token file, or -// error if unable get derive the path. Key that will be used to compute a SHA1 -// value that is hex encoded. -// -// Derives the filepath using the Key as: -// -// ~/.aws/sso/cache/.json -func StandardCachedTokenFilepath(key string) (string, error) { - homeDir := resolvedOsUserHomeDir() - if len(homeDir) == 0 { - return "", fmt.Errorf("unable to get USER's home directory for cached token") - } - hash := sha1.New() - if _, err := hash.Write([]byte(key)); err != nil { - return "", fmt.Errorf("unable to compute cached token filepath key SHA1 hash, %v", err) - } - - cacheFilename := strings.ToLower(hex.EncodeToString(hash.Sum(nil))) + ".json" - - return filepath.Join(homeDir, ".aws", "sso", "cache", cacheFilename), nil -} - -type tokenKnownFields struct { - AccessToken string `json:"accessToken,omitempty"` - ExpiresAt *rfc3339 `json:"expiresAt,omitempty"` - - RefreshToken string `json:"refreshToken,omitempty"` - ClientID string `json:"clientId,omitempty"` - ClientSecret string `json:"clientSecret,omitempty"` -} - -type cachedToken struct { - tokenKnownFields - UnknownFields map[string]interface{} `json:"-"` -} - -// MarshalJSON provides custom marshalling because the standard library Go marshaller ignores unknown/unspecified fields -// when marshalling from a struct: https://pkg.go.dev/encoding/json#Marshal -// This function adds some extra validation to the known fields and captures unknown fields. -func (t cachedToken) MarshalJSON() ([]byte, error) { - fields := map[string]interface{}{} - - setTokenFieldString(fields, "accessToken", t.AccessToken) - setTokenFieldRFC3339(fields, "expiresAt", t.ExpiresAt) - - setTokenFieldString(fields, "refreshToken", t.RefreshToken) - setTokenFieldString(fields, "clientId", t.ClientID) - setTokenFieldString(fields, "clientSecret", t.ClientSecret) - - for k, v := range t.UnknownFields { - if _, ok := fields[k]; ok { - return nil, fmt.Errorf("unknown token field %v, duplicates known field", k) - } - fields[k] = v - } - - return json.Marshal(fields) -} - -func setTokenFieldString(fields map[string]interface{}, key, value string) { - if value == "" { - return - } - fields[key] = value -} -func setTokenFieldRFC3339(fields map[string]interface{}, key string, value *rfc3339) { - if value == nil { - return - } - fields[key] = value -} - -// UnmarshalJSON provides custom unmarshalling because the standard library Go unmarshaller ignores unknown/unspecified -// fields when unmarshalling from a struct: https://pkg.go.dev/encoding/json#Unmarshal -// This function adds some extra validation to the known fields and captures unknown fields. -func (t *cachedToken) UnmarshalJSON(b []byte) error { - var fields map[string]interface{} - if err := json.Unmarshal(b, &fields); err != nil { - return nil - } - - t.UnknownFields = map[string]interface{}{} - - for k, v := range fields { - var err error - switch k { - case "accessToken": - err = getTokenFieldString(v, &t.AccessToken) - case "expiresAt": - err = getTokenFieldRFC3339(v, &t.ExpiresAt) - case "refreshToken": - err = getTokenFieldString(v, &t.RefreshToken) - case "clientId": - err = getTokenFieldString(v, &t.ClientID) - case "clientSecret": - err = getTokenFieldString(v, &t.ClientSecret) - default: - t.UnknownFields[k] = v - } - - if err != nil { - return fmt.Errorf("field %q, %v", k, err) - } - } - - return nil -} - -func getTokenFieldString(v interface{}, value *string) error { - var ok bool - *value, ok = v.(string) - if !ok { - return fmt.Errorf("expect value to be string, got %T", v) - } - return nil -} - -func getTokenFieldRFC3339(v interface{}, value **rfc3339) error { - var stringValue string - if err := getTokenFieldString(v, &stringValue); err != nil { - return err - } - - timeValue, err := parseRFC3339(stringValue) - if err != nil { - return err - } - - *value = &timeValue - return nil -} - -func loadCachedToken(filename string) (cachedToken, error) { - fileBytes, err := ioutil.ReadFile(filename) - if err != nil { - return cachedToken{}, fmt.Errorf("failed to read cached SSO token file, %v", err) - } - - var t cachedToken - if err := json.Unmarshal(fileBytes, &t); err != nil { - return cachedToken{}, fmt.Errorf("failed to parse cached SSO token file, %v", err) - } - - if len(t.AccessToken) == 0 || t.ExpiresAt == nil || time.Time(*t.ExpiresAt).IsZero() { - return cachedToken{}, fmt.Errorf( - "cached SSO token must contain accessToken and expiresAt fields") - } - - return t, nil -} - -func storeCachedToken(filename string, t cachedToken, fileMode os.FileMode) (err error) { - tmpFilename := filename + ".tmp-" + strconv.FormatInt(nowTime().UnixNano(), 10) - if err := writeCacheFile(tmpFilename, fileMode, t); err != nil { - return err - } - - if err := os.Rename(tmpFilename, filename); err != nil { - return fmt.Errorf("failed to replace old cached SSO token file, %v", err) - } - - return nil -} - -func writeCacheFile(filename string, fileMode os.FileMode, t cachedToken) (err error) { - var f *os.File - f, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_RDWR, fileMode) - if err != nil { - return fmt.Errorf("failed to create cached SSO token file %v", err) - } - - defer func() { - closeErr := f.Close() - if err == nil && closeErr != nil { - err = fmt.Errorf("failed to close cached SSO token file, %v", closeErr) - } - }() - - encoder := json.NewEncoder(f) - - if err = encoder.Encode(t); err != nil { - return fmt.Errorf("failed to serialize cached SSO token, %v", err) - } - - return nil -} - -type rfc3339 time.Time - -// UnmarshalJSON decode rfc3339 from JSON format -func (r *rfc3339) UnmarshalJSON(bytes []byte) error { - var value string - var err error - - if err = json.Unmarshal(bytes, &value); err != nil { - return err - } - - *r, err = parseRFC3339(value) - return err -} - -func parseRFC3339(v string) (rfc3339, error) { - parsed, err := time.Parse(time.RFC3339, v) - if err != nil { - return rfc3339{}, fmt.Errorf("expected RFC3339 timestamp: %v", err) - } - - return rfc3339(parsed), nil -} - -// MarshalJSON encode rfc3339 to JSON format time -func (r *rfc3339) MarshalJSON() ([]byte, error) { - value := time.Time(*r).Format(time.RFC3339) - - // Use JSON unmarshal to unescape the quoted value making use of JSON's - // quoting rules. - return json.Marshal(value) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/token_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/token_provider.go deleted file mode 100644 index 3388b78b4..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ssocreds/token_provider.go +++ /dev/null @@ -1,148 +0,0 @@ -package ssocreds - -import ( - "fmt" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/auth/bearer" - "github.com/aws/aws-sdk-go/service/ssooidc" -) - -// CreateTokenAPIClient provides the interface for the SSOTokenProvider's API -// client for calling CreateToken operation to refresh the SSO token. -type CreateTokenAPIClient interface { - CreateToken(input *ssooidc.CreateTokenInput) (*ssooidc.CreateTokenOutput, error) -} - -// SSOTokenProviderOptions provides the options for configuring the -// SSOTokenProvider. -type SSOTokenProviderOptions struct { - // Client that can be overridden - Client CreateTokenAPIClient - - // The path the file containing the cached SSO token will be read from. - // Initialized the NewSSOTokenProvider's cachedTokenFilepath parameter. - CachedTokenFilepath string -} - -// SSOTokenProvider provides a utility for refreshing SSO AccessTokens for -// Bearer Authentication. The SSOTokenProvider can only be used to refresh -// already cached SSO Tokens. This utility cannot perform the initial SSO -// create token. -// -// The initial SSO create token should be preformed with the AWS CLI before the -// Go application using the SSOTokenProvider will need to retrieve the SSO -// token. If the AWS CLI has not created the token cache file, this provider -// will return an error when attempting to retrieve the cached token. -// -// This provider will attempt to refresh the cached SSO token periodically if -// needed when RetrieveBearerToken is called. -// -// A utility such as the AWS CLI must be used to initially create the SSO -// session and cached token file. -// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -type SSOTokenProvider struct { - options SSOTokenProviderOptions -} - -// NewSSOTokenProvider returns an initialized SSOTokenProvider that will -// periodically refresh the SSO token cached stored in the cachedTokenFilepath. -// The cachedTokenFilepath file's content will be rewritten by the token -// provider when the token is refreshed. -// -// The client must be configured for the AWS region the SSO token was created for. -func NewSSOTokenProvider(client CreateTokenAPIClient, cachedTokenFilepath string, optFns ...func(o *SSOTokenProviderOptions)) *SSOTokenProvider { - options := SSOTokenProviderOptions{ - Client: client, - CachedTokenFilepath: cachedTokenFilepath, - } - for _, fn := range optFns { - fn(&options) - } - - provider := &SSOTokenProvider{ - options: options, - } - - return provider -} - -// RetrieveBearerToken returns the SSO token stored in the cachedTokenFilepath -// the SSOTokenProvider was created with. If the token has expired -// RetrieveBearerToken will attempt to refresh it. If the token cannot be -// refreshed or is not present an error will be returned. -// -// A utility such as the AWS CLI must be used to initially create the SSO -// session and cached token file. https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -func (p *SSOTokenProvider) RetrieveBearerToken(ctx aws.Context) (bearer.Token, error) { - cachedToken, err := loadCachedToken(p.options.CachedTokenFilepath) - if err != nil { - return bearer.Token{}, err - } - - if cachedToken.ExpiresAt != nil && nowTime().After(time.Time(*cachedToken.ExpiresAt)) { - cachedToken, err = p.refreshToken(cachedToken) - if err != nil { - return bearer.Token{}, fmt.Errorf("refresh cached SSO token failed, %v", err) - } - } - - expiresAt := toTime((*time.Time)(cachedToken.ExpiresAt)) - return bearer.Token{ - Value: cachedToken.AccessToken, - CanExpire: !expiresAt.IsZero(), - Expires: expiresAt, - }, nil -} - -func (p *SSOTokenProvider) refreshToken(token cachedToken) (cachedToken, error) { - if token.ClientSecret == "" || token.ClientID == "" || token.RefreshToken == "" { - return cachedToken{}, fmt.Errorf("cached SSO token is expired, or not present, and cannot be refreshed") - } - - createResult, err := p.options.Client.CreateToken(&ssooidc.CreateTokenInput{ - ClientId: &token.ClientID, - ClientSecret: &token.ClientSecret, - RefreshToken: &token.RefreshToken, - GrantType: aws.String("refresh_token"), - }) - if err != nil { - return cachedToken{}, fmt.Errorf("unable to refresh SSO token, %v", err) - } - if createResult.ExpiresIn == nil { - return cachedToken{}, fmt.Errorf("missing required field ExpiresIn") - } - if createResult.AccessToken == nil { - return cachedToken{}, fmt.Errorf("missing required field AccessToken") - } - if createResult.RefreshToken == nil { - return cachedToken{}, fmt.Errorf("missing required field RefreshToken") - } - - expiresAt := nowTime().Add(time.Duration(*createResult.ExpiresIn) * time.Second) - - token.AccessToken = *createResult.AccessToken - token.ExpiresAt = (*rfc3339)(&expiresAt) - token.RefreshToken = *createResult.RefreshToken - - fileInfo, err := os.Stat(p.options.CachedTokenFilepath) - if err != nil { - return cachedToken{}, fmt.Errorf("failed to stat cached SSO token file %v", err) - } - - if err = storeCachedToken(p.options.CachedTokenFilepath, token, fileInfo.Mode()); err != nil { - return cachedToken{}, fmt.Errorf("unable to cache refreshed SSO token, %v", err) - } - - return token, nil -} - -func toTime(p *time.Time) (v time.Time) { - if p == nil { - return v - } - - return *p -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go deleted file mode 100644 index cbba1e3d5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go +++ /dev/null @@ -1,57 +0,0 @@ -package credentials - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// StaticProviderName provides a name of Static provider -const StaticProviderName = "StaticProvider" - -var ( - // ErrStaticCredentialsEmpty is emitted when static credentials are empty. - ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil) -) - -// A StaticProvider is a set of credentials which are set programmatically, -// and will never expire. -type StaticProvider struct { - Value -} - -// NewStaticCredentials returns a pointer to a new Credentials object -// wrapping a static credentials value provider. Token is only required -// for temporary security credentials retrieved via STS, otherwise an empty -// string can be passed for this parameter. -func NewStaticCredentials(id, secret, token string) *Credentials { - return NewCredentials(&StaticProvider{Value: Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: token, - }}) -} - -// NewStaticCredentialsFromCreds returns a pointer to a new Credentials object -// wrapping the static credentials value provide. Same as NewStaticCredentials -// but takes the creds Value instead of individual fields -func NewStaticCredentialsFromCreds(creds Value) *Credentials { - return NewCredentials(&StaticProvider{Value: creds}) -} - -// Retrieve returns the credentials or error if the credentials are invalid. -func (s *StaticProvider) Retrieve() (Value, error) { - if s.AccessKeyID == "" || s.SecretAccessKey == "" { - return Value{ProviderName: StaticProviderName}, ErrStaticCredentialsEmpty - } - - if len(s.Value.ProviderName) == 0 { - s.Value.ProviderName = StaticProviderName - } - return s.Value, nil -} - -// IsExpired returns if the credentials are expired. -// -// For StaticProvider, the credentials never expired. -func (s *StaticProvider) IsExpired() bool { - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go deleted file mode 100644 index 86db488de..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go +++ /dev/null @@ -1,371 +0,0 @@ -/* -Package stscreds are credential Providers to retrieve STS AWS credentials. - -STS provides multiple ways to retrieve credentials which can be used when making -future AWS service API operation calls. - -The SDK will ensure that per instance of credentials.Credentials all requests -to refresh the credentials will be synchronized. But, the SDK is unable to -ensure synchronous usage of the AssumeRoleProvider if the value is shared -between multiple Credentials, Sessions or service clients. - -# Assume Role - -To assume an IAM role using STS with the SDK you can create a new Credentials -with the SDKs's stscreds package. - - // Initial credentials loaded from SDK's default credential chain. Such as - // the environment, shared credentials (~/.aws/credentials), or EC2 Instance - // Role. These credentials will be used to to make the STS Assume Role API. - sess := session.Must(session.NewSession()) - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. - creds := stscreds.NewCredentials(sess, "myRoleArn") - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -# Assume Role with static MFA Token - -To assume an IAM role with a MFA token you can either specify a MFA token code -directly or provide a function to prompt the user each time the credentials -need to refresh the role's credentials. Specifying the TokenCode should be used -for short lived operations that will not need to be refreshed, and when you do -not want to have direct control over the user provides their MFA token. - -With TokenCode the AssumeRoleProvider will be not be able to refresh the role's -credentials. - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN using the MFA token code provided. - creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { - p.SerialNumber = aws.String("myTokenSerialNumber") - p.TokenCode = aws.String("00000000") - }) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -# Assume Role with MFA Token Provider - -To assume an IAM role with MFA for longer running tasks where the credentials -may need to be refreshed setting the TokenProvider field of AssumeRoleProvider -will allow the credential provider to prompt for new MFA token code when the -role's credentials need to be refreshed. - -The StdinTokenProvider function is available to prompt on stdin to retrieve -the MFA token code from the user. You can also implement custom prompts by -satisfing the TokenProvider function signature. - -Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -have undesirable results as the StdinTokenProvider will not be synchronized. A -single Credentials with an AssumeRoleProvider can be shared safely. - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. Prompting for MFA token from stdin. - creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { - p.SerialNumber = aws.String("myTokenSerialNumber") - p.TokenProvider = stscreds.StdinTokenProvider - }) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) -*/ -package stscreds - -import ( - "fmt" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkrand" - "github.com/aws/aws-sdk-go/service/sts" -) - -// StdinTokenProvider will prompt on stderr and read from stdin for a string value. -// An error is returned if reading from stdin fails. -// -// Use this function to read MFA tokens from stdin. The function makes no attempt -// to make atomic prompts from stdin across multiple gorouties. -// -// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -// have undesirable results as the StdinTokenProvider will not be synchronized. A -// single Credentials with an AssumeRoleProvider can be shared safely -// -// Will wait forever until something is provided on the stdin. -func StdinTokenProvider() (string, error) { - var v string - fmt.Fprintf(os.Stderr, "Assume Role MFA token code: ") - _, err := fmt.Scanln(&v) - - return v, err -} - -// ProviderName provides a name of AssumeRole provider -const ProviderName = "AssumeRoleProvider" - -// AssumeRoler represents the minimal subset of the STS client API used by this provider. -type AssumeRoler interface { - AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) -} - -type assumeRolerWithContext interface { - AssumeRoleWithContext(aws.Context, *sts.AssumeRoleInput, ...request.Option) (*sts.AssumeRoleOutput, error) -} - -// DefaultDuration is the default amount of time in minutes that the credentials -// will be valid for. -var DefaultDuration = time.Duration(15) * time.Minute - -// AssumeRoleProvider retrieves temporary credentials from the STS service, and -// keeps track of their expiration time. -// -// This credential provider will be used by the SDKs default credential change -// when shared configuration is enabled, and the shared config or shared credentials -// file configure assume role. See Session docs for how to do this. -// -// AssumeRoleProvider does not provide any synchronization and it is not safe -// to share this value across multiple Credentials, Sessions, or service clients -// without also sharing the same Credentials instance. -type AssumeRoleProvider struct { - credentials.Expiry - - // STS client to make assume role request with. - Client AssumeRoler - - // Role to be assumed. - RoleARN string - - // Session name, if you wish to reuse the credentials elsewhere. - RoleSessionName string - - // Optional, you can pass tag key-value pairs to your session. These tags are called session tags. - Tags []*sts.Tag - - // A list of keys for session tags that you want to set as transitive. - // If you set a tag key as transitive, the corresponding key and value passes to subsequent sessions in a role chain. - TransitiveTagKeys []*string - - // Expiry duration of the STS credentials. Defaults to 15 minutes if not set. - Duration time.Duration - - // Optional ExternalID to pass along, defaults to nil if not set. - ExternalID *string - - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string - - // The ARNs of IAM managed policies you want to use as managed session policies. - // The policies must exist in the same account as the role. - // - // This parameter is optional. You can provide up to 10 managed policy ARNs. - // However, the plain text that you use for both inline and managed session - // policies can't exceed 2,048 characters. - // - // An AWS conversion compresses the passed session policies and session tags - // into a packed binary format that has a separate limit. Your request can fail - // for this limit even if your plain text meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. - // - // Passing policies to this operation returns new temporary credentials. The - // resulting session's permissions are the intersection of the role's identity-based - // policy and the session policies. You can use the role's temporary credentials - // in subsequent AWS API calls to access resources in the account that owns - // the role. You cannot use session policies to grant more permissions than - // those allowed by the identity-based policy of the role that is being assumed. - // For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []*sts.PolicyDescriptorType - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy - // of the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as GAHT12345678) - // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - SerialNumber *string - - // The SourceIdentity which is used to identity a persistent identity through the whole session. - // For more details see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html - SourceIdentity *string - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA (that is, if the policy includes a condition that tests - // for MFA). If the role being assumed requires MFA and if the TokenCode value - // is missing or expired, the AssumeRole call returns an "access denied" error. - // - // If SerialNumber is set and neither TokenCode nor TokenProvider are also - // set an error will be returned. - TokenCode *string - - // Async method of providing MFA token code for assuming an IAM role with MFA. - // The value returned by the function will be used as the TokenCode in the Retrieve - // call. See StdinTokenProvider for a provider that prompts and reads from stdin. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed when SerialNumber is also set and - // TokenCode is not set. - // - // If both TokenCode and TokenProvider is set, TokenProvider will be used and - // TokenCode is ignored. - TokenProvider func() (string, error) - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration - - // MaxJitterFrac reduces the effective Duration of each credential requested - // by a random percentage between 0 and MaxJitterFraction. MaxJitterFrac must - // have a value between 0 and 1. Any other value may lead to expected behavior. - // With a MaxJitterFrac value of 0, default) will no jitter will be used. - // - // For example, with a Duration of 30m and a MaxJitterFrac of 0.1, the - // AssumeRole call will be made with an arbitrary Duration between 27m and - // 30m. - // - // MaxJitterFrac should not be negative. - MaxJitterFrac float64 -} - -// NewCredentials returns a pointer to a new Credentials value wrapping the -// AssumeRoleProvider. The credentials will expire every 15 minutes and the -// role will be named after a nanosecond timestamp of this operation. The -// Credentials value will attempt to refresh the credentials using the provider -// when Credentials.Get is called, if the cached credentials are expiring. -// -// Takes a Config provider to create the STS client. The ConfigProvider is -// satisfied by the session.Session type. -// -// It is safe to share the returned Credentials with multiple Sessions and -// service clients. All access to the credentials and refreshing them -// will be synchronized. -func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { - p := &AssumeRoleProvider{ - Client: sts.New(c), - RoleARN: roleARN, - Duration: DefaultDuration, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsWithClient returns a pointer to a new Credentials value wrapping the -// AssumeRoleProvider. The credentials will expire every 15 minutes and the -// role will be named after a nanosecond timestamp of this operation. The -// Credentials value will attempt to refresh the credentials using the provider -// when Credentials.Get is called, if the cached credentials are expiring. -// -// Takes an AssumeRoler which can be satisfied by the STS client. -// -// It is safe to share the returned Credentials with multiple Sessions and -// service clients. All access to the credentials and refreshing them -// will be synchronized. -func NewCredentialsWithClient(svc AssumeRoler, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { - p := &AssumeRoleProvider{ - Client: svc, - RoleARN: roleARN, - Duration: DefaultDuration, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve generates a new set of temporary credentials using STS. -func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) { - return p.RetrieveWithContext(aws.BackgroundContext()) -} - -// RetrieveWithContext generates a new set of temporary credentials using STS. -func (p *AssumeRoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) { - // Apply defaults where parameters are not set. - if p.RoleSessionName == "" { - // Try to work out a role name that will hopefully end up unique. - p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano()) - } - if p.Duration == 0 { - // Expire as often as AWS permits. - p.Duration = DefaultDuration - } - jitter := time.Duration(sdkrand.SeededRand.Float64() * p.MaxJitterFrac * float64(p.Duration)) - input := &sts.AssumeRoleInput{ - DurationSeconds: aws.Int64(int64((p.Duration - jitter) / time.Second)), - RoleArn: aws.String(p.RoleARN), - RoleSessionName: aws.String(p.RoleSessionName), - ExternalId: p.ExternalID, - Tags: p.Tags, - PolicyArns: p.PolicyArns, - TransitiveTagKeys: p.TransitiveTagKeys, - SourceIdentity: p.SourceIdentity, - } - if p.Policy != nil { - input.Policy = p.Policy - } - if p.SerialNumber != nil { - if p.TokenCode != nil { - input.SerialNumber = p.SerialNumber - input.TokenCode = p.TokenCode - } else if p.TokenProvider != nil { - input.SerialNumber = p.SerialNumber - code, err := p.TokenProvider() - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - input.TokenCode = aws.String(code) - } else { - return credentials.Value{ProviderName: ProviderName}, - awserr.New("AssumeRoleTokenNotAvailable", - "assume role with MFA enabled, but neither TokenCode nor TokenProvider are set", nil) - } - } - - var roleOutput *sts.AssumeRoleOutput - var err error - - if c, ok := p.Client.(assumeRolerWithContext); ok { - roleOutput, err = c.AssumeRoleWithContext(ctx, input) - } else { - roleOutput, err = p.Client.AssumeRole(input) - } - - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - // We will proactively generate new credentials before they expire. - p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow) - - return credentials.Value{ - AccessKeyID: *roleOutput.Credentials.AccessKeyId, - SecretAccessKey: *roleOutput.Credentials.SecretAccessKey, - SessionToken: *roleOutput.Credentials.SessionToken, - ProviderName: ProviderName, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go deleted file mode 100644 index 19ad619aa..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go +++ /dev/null @@ -1,182 +0,0 @@ -package stscreds - -import ( - "fmt" - "io/ioutil" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/service/sts" - "github.com/aws/aws-sdk-go/service/sts/stsiface" -) - -const ( - // ErrCodeWebIdentity will be used as an error code when constructing - // a new error to be returned during session creation or retrieval. - ErrCodeWebIdentity = "WebIdentityErr" - - // WebIdentityProviderName is the web identity provider name - WebIdentityProviderName = "WebIdentityCredentials" -) - -// now is used to return a time.Time object representing -// the current time. This can be used to easily test and -// compare test values. -var now = time.Now - -// TokenFetcher should return WebIdentity token bytes or an error -type TokenFetcher interface { - FetchToken(credentials.Context) ([]byte, error) -} - -// FetchTokenPath is a path to a WebIdentity token file -type FetchTokenPath string - -// FetchToken returns a token by reading from the filesystem -func (f FetchTokenPath) FetchToken(ctx credentials.Context) ([]byte, error) { - data, err := ioutil.ReadFile(string(f)) - if err != nil { - errMsg := fmt.Sprintf("unable to read file at %s", f) - return nil, awserr.New(ErrCodeWebIdentity, errMsg, err) - } - return data, nil -} - -// WebIdentityRoleProvider is used to retrieve credentials using -// an OIDC token. -type WebIdentityRoleProvider struct { - credentials.Expiry - - // The policy ARNs to use with the web identity assumed role. - PolicyArns []*sts.PolicyDescriptorType - - // Duration the STS credentials will be valid for. Truncated to seconds. - // If unset, the assumed role will use AssumeRoleWithWebIdentity's default - // expiry duration. See - // https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#STS.AssumeRoleWithWebIdentity - // for more information. - Duration time.Duration - - // The amount of time the credentials will be refreshed before they expire. - // This is useful refresh credentials before they expire to reduce risk of - // using credentials as they expire. If unset, will default to no expiry - // window. - ExpiryWindow time.Duration - - client stsiface.STSAPI - - tokenFetcher TokenFetcher - roleARN string - roleSessionName string -} - -// NewWebIdentityCredentials will return a new set of credentials with a given -// configuration, role arn, and token file path. -// -// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible -// functional options, and wrap with credentials.NewCredentials helper. -func NewWebIdentityCredentials(c client.ConfigProvider, roleARN, roleSessionName, path string) *credentials.Credentials { - svc := sts.New(c) - p := NewWebIdentityRoleProvider(svc, roleARN, roleSessionName, path) - return credentials.NewCredentials(p) -} - -// NewWebIdentityRoleProvider will return a new WebIdentityRoleProvider with the -// provided stsiface.STSAPI -// -// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible -// functional options. -func NewWebIdentityRoleProvider(svc stsiface.STSAPI, roleARN, roleSessionName, path string) *WebIdentityRoleProvider { - return NewWebIdentityRoleProviderWithOptions(svc, roleARN, roleSessionName, FetchTokenPath(path)) -} - -// NewWebIdentityRoleProviderWithToken will return a new WebIdentityRoleProvider with the -// provided stsiface.STSAPI and a TokenFetcher -// -// Deprecated: Use NewWebIdentityRoleProviderWithOptions for flexible -// functional options. -func NewWebIdentityRoleProviderWithToken(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher) *WebIdentityRoleProvider { - return NewWebIdentityRoleProviderWithOptions(svc, roleARN, roleSessionName, tokenFetcher) -} - -// NewWebIdentityRoleProviderWithOptions will return an initialize -// WebIdentityRoleProvider with the provided stsiface.STSAPI, role ARN, and a -// TokenFetcher. Additional options can be provided as functional options. -// -// TokenFetcher is the implementation that will retrieve the JWT token from to -// assume the role with. Use the provided FetchTokenPath implementation to -// retrieve the JWT token using a file system path. -func NewWebIdentityRoleProviderWithOptions(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher, optFns ...func(*WebIdentityRoleProvider)) *WebIdentityRoleProvider { - p := WebIdentityRoleProvider{ - client: svc, - tokenFetcher: tokenFetcher, - roleARN: roleARN, - roleSessionName: roleSessionName, - } - - for _, fn := range optFns { - fn(&p) - } - - return &p -} - -// Retrieve will attempt to assume a role from a token which is located at -// 'WebIdentityTokenFilePath' specified destination and if that is empty an -// error will be returned. -func (p *WebIdentityRoleProvider) Retrieve() (credentials.Value, error) { - return p.RetrieveWithContext(aws.BackgroundContext()) -} - -// RetrieveWithContext will attempt to assume a role from a token which is -// located at 'WebIdentityTokenFilePath' specified destination and if that is -// empty an error will be returned. -func (p *WebIdentityRoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) { - b, err := p.tokenFetcher.FetchToken(ctx) - if err != nil { - return credentials.Value{}, awserr.New(ErrCodeWebIdentity, "failed fetching WebIdentity token: ", err) - } - - sessionName := p.roleSessionName - if len(sessionName) == 0 { - // session name is used to uniquely identify a session. This simply - // uses unix time in nanoseconds to uniquely identify sessions. - sessionName = strconv.FormatInt(now().UnixNano(), 10) - } - - var duration *int64 - if p.Duration != 0 { - duration = aws.Int64(int64(p.Duration / time.Second)) - } - - req, resp := p.client.AssumeRoleWithWebIdentityRequest(&sts.AssumeRoleWithWebIdentityInput{ - PolicyArns: p.PolicyArns, - RoleArn: &p.roleARN, - RoleSessionName: &sessionName, - WebIdentityToken: aws.String(string(b)), - DurationSeconds: duration, - }) - - req.SetContext(ctx) - - // InvalidIdentityToken error is a temporary error that can occur - // when assuming an Role with a JWT web identity token. - req.RetryErrorCodes = append(req.RetryErrorCodes, sts.ErrCodeInvalidIdentityTokenException) - if err := req.Send(); err != nil { - return credentials.Value{}, awserr.New(ErrCodeWebIdentity, "failed to retrieve credentials", err) - } - - p.SetExpiration(aws.TimeValue(resp.Credentials.Expiration), p.ExpiryWindow) - - value := credentials.Value{ - AccessKeyID: aws.StringValue(resp.Credentials.AccessKeyId), - SecretAccessKey: aws.StringValue(resp.Credentials.SecretAccessKey), - SessionToken: aws.StringValue(resp.Credentials.SessionToken), - ProviderName: WebIdentityProviderName, - } - return value, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go deleted file mode 100644 index 25a66d1dd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/doc.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package csm provides the Client Side Monitoring (CSM) client which enables -// sending metrics via UDP connection to the CSM agent. This package provides -// control options, and configuration for the CSM client. The client can be -// controlled manually, or automatically via the SDK's Session configuration. -// -// Enabling CSM client via SDK's Session configuration -// -// The CSM client can be enabled automatically via SDK's Session configuration. -// The SDK's session configuration enables the CSM client if the AWS_CSM_PORT -// environment variable is set to a non-empty value. -// -// The configuration options for the CSM client via the SDK's session -// configuration are: -// -// * AWS_CSM_PORT= -// The port number the CSM agent will receive metrics on. -// -// * AWS_CSM_HOST= -// The hostname, or IP address the CSM agent will receive metrics on. -// Without port number. -// -// Manually enabling the CSM client -// -// The CSM client can be started, paused, and resumed manually. The Start -// function will enable the CSM client to publish metrics to the CSM agent. It -// is safe to call Start concurrently, but if Start is called additional times -// with different ClientID or address it will panic. -// -// r, err := csm.Start("clientID", ":31000") -// if err != nil { -// panic(fmt.Errorf("failed starting CSM: %v", err)) -// } -// -// When controlling the CSM client manually, you must also inject its request -// handlers into the SDK's Session configuration for the SDK's API clients to -// publish metrics. -// -// sess, err := session.NewSession(&aws.Config{}) -// if err != nil { -// panic(fmt.Errorf("failed loading session: %v", err)) -// } -// -// // Add CSM client's metric publishing request handlers to the SDK's -// // Session Configuration. -// r.InjectHandlers(&sess.Handlers) -// -// Controlling CSM client -// -// Once the CSM client has been enabled the Get function will return a Reporter -// value that you can use to pause and resume the metrics published to the CSM -// agent. If Get function is called before the reporter is enabled with the -// Start function or via SDK's Session configuration nil will be returned. -// -// The Pause method can be called to stop the CSM client publishing metrics to -// the CSM agent. The Continue method will resume metric publishing. -// -// // Get the CSM client Reporter. -// r := csm.Get() -// -// // Will pause monitoring -// r.Pause() -// resp, err = client.GetObject(&s3.GetObjectInput{ -// Bucket: aws.String("bucket"), -// Key: aws.String("key"), -// }) -// -// // Resume monitoring -// r.Continue() -package csm diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go deleted file mode 100644 index 4b19e2800..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/enable.go +++ /dev/null @@ -1,89 +0,0 @@ -package csm - -import ( - "fmt" - "strings" - "sync" -) - -var ( - lock sync.Mutex -) - -const ( - // DefaultPort is used when no port is specified. - DefaultPort = "31000" - - // DefaultHost is the host that will be used when none is specified. - DefaultHost = "127.0.0.1" -) - -// AddressWithDefaults returns a CSM address built from the host and port -// values. If the host or port is not set, default values will be used -// instead. If host is "localhost" it will be replaced with "127.0.0.1". -func AddressWithDefaults(host, port string) string { - if len(host) == 0 || strings.EqualFold(host, "localhost") { - host = DefaultHost - } - - if len(port) == 0 { - port = DefaultPort - } - - // Only IP6 host can contain a colon - if strings.Contains(host, ":") { - return "[" + host + "]:" + port - } - - return host + ":" + port -} - -// Start will start a long running go routine to capture -// client side metrics. Calling start multiple time will only -// start the metric listener once and will panic if a different -// client ID or port is passed in. -// -// r, err := csm.Start("clientID", "127.0.0.1:31000") -// if err != nil { -// panic(fmt.Errorf("expected no error, but received %v", err)) -// } -// sess := session.NewSession() -// r.InjectHandlers(sess.Handlers) -// -// svc := s3.New(sess) -// out, err := svc.GetObject(&s3.GetObjectInput{ -// Bucket: aws.String("bucket"), -// Key: aws.String("key"), -// }) -func Start(clientID string, url string) (*Reporter, error) { - lock.Lock() - defer lock.Unlock() - - if sender == nil { - sender = newReporter(clientID, url) - } else { - if sender.clientID != clientID { - panic(fmt.Errorf("inconsistent client IDs. %q was expected, but received %q", sender.clientID, clientID)) - } - - if sender.url != url { - panic(fmt.Errorf("inconsistent URLs. %q was expected, but received %q", sender.url, url)) - } - } - - if err := connect(url); err != nil { - sender = nil - return nil, err - } - - return sender, nil -} - -// Get will return a reporter if one exists, if one does not exist, nil will -// be returned. -func Get() *Reporter { - lock.Lock() - defer lock.Unlock() - - return sender -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go deleted file mode 100644 index 5bacc791a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric.go +++ /dev/null @@ -1,109 +0,0 @@ -package csm - -import ( - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" -) - -type metricTime time.Time - -func (t metricTime) MarshalJSON() ([]byte, error) { - ns := time.Duration(time.Time(t).UnixNano()) - return []byte(strconv.FormatInt(int64(ns/time.Millisecond), 10)), nil -} - -type metric struct { - ClientID *string `json:"ClientId,omitempty"` - API *string `json:"Api,omitempty"` - Service *string `json:"Service,omitempty"` - Timestamp *metricTime `json:"Timestamp,omitempty"` - Type *string `json:"Type,omitempty"` - Version *int `json:"Version,omitempty"` - - AttemptCount *int `json:"AttemptCount,omitempty"` - Latency *int `json:"Latency,omitempty"` - - Fqdn *string `json:"Fqdn,omitempty"` - UserAgent *string `json:"UserAgent,omitempty"` - AttemptLatency *int `json:"AttemptLatency,omitempty"` - - SessionToken *string `json:"SessionToken,omitempty"` - Region *string `json:"Region,omitempty"` - AccessKey *string `json:"AccessKey,omitempty"` - HTTPStatusCode *int `json:"HttpStatusCode,omitempty"` - XAmzID2 *string `json:"XAmzId2,omitempty"` - XAmzRequestID *string `json:"XAmznRequestId,omitempty"` - - AWSException *string `json:"AwsException,omitempty"` - AWSExceptionMessage *string `json:"AwsExceptionMessage,omitempty"` - SDKException *string `json:"SdkException,omitempty"` - SDKExceptionMessage *string `json:"SdkExceptionMessage,omitempty"` - - FinalHTTPStatusCode *int `json:"FinalHttpStatusCode,omitempty"` - FinalAWSException *string `json:"FinalAwsException,omitempty"` - FinalAWSExceptionMessage *string `json:"FinalAwsExceptionMessage,omitempty"` - FinalSDKException *string `json:"FinalSdkException,omitempty"` - FinalSDKExceptionMessage *string `json:"FinalSdkExceptionMessage,omitempty"` - - DestinationIP *string `json:"DestinationIp,omitempty"` - ConnectionReused *int `json:"ConnectionReused,omitempty"` - - AcquireConnectionLatency *int `json:"AcquireConnectionLatency,omitempty"` - ConnectLatency *int `json:"ConnectLatency,omitempty"` - RequestLatency *int `json:"RequestLatency,omitempty"` - DNSLatency *int `json:"DnsLatency,omitempty"` - TCPLatency *int `json:"TcpLatency,omitempty"` - SSLLatency *int `json:"SslLatency,omitempty"` - - MaxRetriesExceeded *int `json:"MaxRetriesExceeded,omitempty"` -} - -func (m *metric) TruncateFields() { - m.ClientID = truncateString(m.ClientID, 255) - m.UserAgent = truncateString(m.UserAgent, 256) - - m.AWSException = truncateString(m.AWSException, 128) - m.AWSExceptionMessage = truncateString(m.AWSExceptionMessage, 512) - - m.SDKException = truncateString(m.SDKException, 128) - m.SDKExceptionMessage = truncateString(m.SDKExceptionMessage, 512) - - m.FinalAWSException = truncateString(m.FinalAWSException, 128) - m.FinalAWSExceptionMessage = truncateString(m.FinalAWSExceptionMessage, 512) - - m.FinalSDKException = truncateString(m.FinalSDKException, 128) - m.FinalSDKExceptionMessage = truncateString(m.FinalSDKExceptionMessage, 512) -} - -func truncateString(v *string, l int) *string { - if v != nil && len(*v) > l { - nv := (*v)[:l] - return &nv - } - - return v -} - -func (m *metric) SetException(e metricException) { - switch te := e.(type) { - case awsException: - m.AWSException = aws.String(te.exception) - m.AWSExceptionMessage = aws.String(te.message) - case sdkException: - m.SDKException = aws.String(te.exception) - m.SDKExceptionMessage = aws.String(te.message) - } -} - -func (m *metric) SetFinalException(e metricException) { - switch te := e.(type) { - case awsException: - m.FinalAWSException = aws.String(te.exception) - m.FinalAWSExceptionMessage = aws.String(te.message) - case sdkException: - m.FinalSDKException = aws.String(te.exception) - m.FinalSDKExceptionMessage = aws.String(te.message) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go deleted file mode 100644 index 82a3e345e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_chan.go +++ /dev/null @@ -1,55 +0,0 @@ -package csm - -import ( - "sync/atomic" -) - -const ( - runningEnum = iota - pausedEnum -) - -var ( - // MetricsChannelSize of metrics to hold in the channel - MetricsChannelSize = 100 -) - -type metricChan struct { - ch chan metric - paused *int64 -} - -func newMetricChan(size int) metricChan { - return metricChan{ - ch: make(chan metric, size), - paused: new(int64), - } -} - -func (ch *metricChan) Pause() { - atomic.StoreInt64(ch.paused, pausedEnum) -} - -func (ch *metricChan) Continue() { - atomic.StoreInt64(ch.paused, runningEnum) -} - -func (ch *metricChan) IsPaused() bool { - v := atomic.LoadInt64(ch.paused) - return v == pausedEnum -} - -// Push will push metrics to the metric channel if the channel -// is not paused -func (ch *metricChan) Push(m metric) bool { - if ch.IsPaused() { - return false - } - - select { - case ch.ch <- m: - return true - default: - return false - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_exception.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_exception.go deleted file mode 100644 index 54a99280c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/metric_exception.go +++ /dev/null @@ -1,26 +0,0 @@ -package csm - -type metricException interface { - Exception() string - Message() string -} - -type requestException struct { - exception string - message string -} - -func (e requestException) Exception() string { - return e.exception -} -func (e requestException) Message() string { - return e.message -} - -type awsException struct { - requestException -} - -type sdkException struct { - requestException -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go b/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go deleted file mode 100644 index 835bcd49c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/csm/reporter.go +++ /dev/null @@ -1,264 +0,0 @@ -package csm - -import ( - "encoding/json" - "net" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// Reporter will gather metrics of API requests made and -// send those metrics to the CSM endpoint. -type Reporter struct { - clientID string - url string - conn net.Conn - metricsCh metricChan - done chan struct{} -} - -var ( - sender *Reporter -) - -func connect(url string) error { - const network = "udp" - if err := sender.connect(network, url); err != nil { - return err - } - - if sender.done == nil { - sender.done = make(chan struct{}) - go sender.start() - } - - return nil -} - -func newReporter(clientID, url string) *Reporter { - return &Reporter{ - clientID: clientID, - url: url, - metricsCh: newMetricChan(MetricsChannelSize), - } -} - -func (rep *Reporter) sendAPICallAttemptMetric(r *request.Request) { - if rep == nil { - return - } - - now := time.Now() - creds, _ := r.Config.Credentials.Get() - - m := metric{ - ClientID: aws.String(rep.clientID), - API: aws.String(r.Operation.Name), - Service: aws.String(r.ClientInfo.ServiceID), - Timestamp: (*metricTime)(&now), - UserAgent: aws.String(r.HTTPRequest.Header.Get("User-Agent")), - Region: r.Config.Region, - Type: aws.String("ApiCallAttempt"), - Version: aws.Int(1), - - XAmzRequestID: aws.String(r.RequestID), - - AttemptLatency: aws.Int(int(now.Sub(r.AttemptTime).Nanoseconds() / int64(time.Millisecond))), - AccessKey: aws.String(creds.AccessKeyID), - } - - if r.HTTPResponse != nil { - m.HTTPStatusCode = aws.Int(r.HTTPResponse.StatusCode) - } - - if r.Error != nil { - if awserr, ok := r.Error.(awserr.Error); ok { - m.SetException(getMetricException(awserr)) - } - } - - m.TruncateFields() - rep.metricsCh.Push(m) -} - -func getMetricException(err awserr.Error) metricException { - msg := err.Error() - code := err.Code() - - switch code { - case request.ErrCodeRequestError, - request.ErrCodeSerialization, - request.CanceledErrorCode: - return sdkException{ - requestException{exception: code, message: msg}, - } - default: - return awsException{ - requestException{exception: code, message: msg}, - } - } -} - -func (rep *Reporter) sendAPICallMetric(r *request.Request) { - if rep == nil { - return - } - - now := time.Now() - m := metric{ - ClientID: aws.String(rep.clientID), - API: aws.String(r.Operation.Name), - Service: aws.String(r.ClientInfo.ServiceID), - Timestamp: (*metricTime)(&now), - UserAgent: aws.String(r.HTTPRequest.Header.Get("User-Agent")), - Type: aws.String("ApiCall"), - AttemptCount: aws.Int(r.RetryCount + 1), - Region: r.Config.Region, - Latency: aws.Int(int(time.Since(r.Time) / time.Millisecond)), - XAmzRequestID: aws.String(r.RequestID), - MaxRetriesExceeded: aws.Int(boolIntValue(r.RetryCount >= r.MaxRetries())), - } - - if r.HTTPResponse != nil { - m.FinalHTTPStatusCode = aws.Int(r.HTTPResponse.StatusCode) - } - - if r.Error != nil { - if awserr, ok := r.Error.(awserr.Error); ok { - m.SetFinalException(getMetricException(awserr)) - } - } - - m.TruncateFields() - - // TODO: Probably want to figure something out for logging dropped - // metrics - rep.metricsCh.Push(m) -} - -func (rep *Reporter) connect(network, url string) error { - if rep.conn != nil { - rep.conn.Close() - } - - conn, err := net.Dial(network, url) - if err != nil { - return awserr.New("UDPError", "Could not connect", err) - } - - rep.conn = conn - - return nil -} - -func (rep *Reporter) close() { - if rep.done != nil { - close(rep.done) - } - - rep.metricsCh.Pause() -} - -func (rep *Reporter) start() { - defer func() { - rep.metricsCh.Pause() - }() - - for { - select { - case <-rep.done: - rep.done = nil - return - case m := <-rep.metricsCh.ch: - // TODO: What to do with this error? Probably should just log - b, err := json.Marshal(m) - if err != nil { - continue - } - - rep.conn.Write(b) - } - } -} - -// Pause will pause the metric channel preventing any new metrics from being -// added. It is safe to call concurrently with other calls to Pause, but if -// called concurently with Continue can lead to unexpected state. -func (rep *Reporter) Pause() { - lock.Lock() - defer lock.Unlock() - - if rep == nil { - return - } - - rep.close() -} - -// Continue will reopen the metric channel and allow for monitoring to be -// resumed. It is safe to call concurrently with other calls to Continue, but -// if called concurently with Pause can lead to unexpected state. -func (rep *Reporter) Continue() { - lock.Lock() - defer lock.Unlock() - if rep == nil { - return - } - - if !rep.metricsCh.IsPaused() { - return - } - - rep.metricsCh.Continue() -} - -// Client side metric handler names -const ( - APICallMetricHandlerName = "awscsm.SendAPICallMetric" - APICallAttemptMetricHandlerName = "awscsm.SendAPICallAttemptMetric" -) - -// InjectHandlers will will enable client side metrics and inject the proper -// handlers to handle how metrics are sent. -// -// InjectHandlers is NOT safe to call concurrently. Calling InjectHandlers -// multiple times may lead to unexpected behavior, (e.g. duplicate metrics). -// -// // Start must be called in order to inject the correct handlers -// r, err := csm.Start("clientID", "127.0.0.1:8094") -// if err != nil { -// panic(fmt.Errorf("expected no error, but received %v", err)) -// } -// -// sess := session.NewSession() -// r.InjectHandlers(&sess.Handlers) -// -// // create a new service client with our client side metric session -// svc := s3.New(sess) -func (rep *Reporter) InjectHandlers(handlers *request.Handlers) { - if rep == nil { - return - } - - handlers.Complete.PushFrontNamed(request.NamedHandler{ - Name: APICallMetricHandlerName, - Fn: rep.sendAPICallMetric, - }) - - handlers.CompleteAttempt.PushFrontNamed(request.NamedHandler{ - Name: APICallAttemptMetricHandlerName, - Fn: rep.sendAPICallAttemptMetric, - }) -} - -// boolIntValue return 1 for true and 0 for false. -func boolIntValue(b bool) int { - if b { - return 1 - } - - return 0 -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go deleted file mode 100644 index 1ba80b576..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ /dev/null @@ -1,252 +0,0 @@ -// Package defaults is a collection of helpers to retrieve the SDK's default -// configuration and handlers. -// -// Generally this package shouldn't be used directly, but session.Session -// instead. This package is useful when you need to reset the defaults -// of a session or service client to the SDK defaults before setting -// additional parameters. -package defaults - -import ( - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// A Defaults provides a collection of default values for SDK clients. -type Defaults struct { - Config *aws.Config - Handlers request.Handlers -} - -// Get returns the SDK's default values with Config and handlers pre-configured. -func Get() Defaults { - cfg := Config() - handlers := Handlers() - cfg.Credentials = CredChain(cfg, handlers) - - return Defaults{ - Config: cfg, - Handlers: handlers, - } -} - -// Config returns the default configuration without credentials. -// To retrieve a config with credentials also included use -// `defaults.Get().Config` instead. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the configuration of an -// existing service client or session. -func Config() *aws.Config { - return aws.NewConfig(). - WithCredentials(credentials.AnonymousCredentials). - WithRegion(os.Getenv("AWS_REGION")). - WithHTTPClient(http.DefaultClient). - WithMaxRetries(aws.UseServiceDefaultRetries). - WithLogger(aws.NewDefaultLogger()). - WithLogLevel(aws.LogOff). - WithEndpointResolver(endpoints.DefaultResolver()) -} - -// Handlers returns the default request handlers. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the request handlers of an -// existing service client or session. -func Handlers() request.Handlers { - var handlers request.Handlers - - handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - handlers.Validate.AfterEachFn = request.HandlerListStopOnError - handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler) - handlers.Build.PushBackNamed(corehandlers.AddAwsInternal) - handlers.Build.PushBackNamed(corehandlers.AddHostExecEnvUserAgentHander) - handlers.Build.AfterEachFn = request.HandlerListStopOnError - handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler) - handlers.Send.PushBackNamed(corehandlers.ValidateReqSigHandler) - handlers.Send.PushBackNamed(corehandlers.SendHandler) - handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - handlers.ValidateResponse.PushBackNamed(corehandlers.ValidateResponseHandler) - - return handlers -} - -// CredChain returns the default credential chain. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the credentials of an -// existing service client or session's Config. -func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials { - return credentials.NewCredentials(&credentials.ChainProvider{ - VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: CredProviders(cfg, handlers), - }) -} - -// CredProviders returns the slice of providers used in -// the default credential chain. -// -// For applications that need to use some other provider (for example use -// different environment variables for legacy reasons) but still fall back -// on the default chain of providers. This allows that default chaint to be -// automatically updated -func CredProviders(cfg *aws.Config, handlers request.Handlers) []credentials.Provider { - return []credentials.Provider{ - &credentials.EnvProvider{}, - &credentials.SharedCredentialsProvider{Filename: "", Profile: ""}, - RemoteCredProvider(*cfg, handlers), - } -} - -const ( - httpProviderAuthorizationEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN" - httpProviderAuthFileEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE" - httpProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" -) - -// direct representation of the IPv4 address for the ECS container -// "169.254.170.2" -var ecsContainerIPv4 net.IP = []byte{ - 169, 254, 170, 2, -} - -// direct representation of the IPv4 address for the EKS container -// "169.254.170.23" -var eksContainerIPv4 net.IP = []byte{ - 169, 254, 170, 23, -} - -// direct representation of the IPv6 address for the EKS container -// "fd00:ec2::23" -var eksContainerIPv6 net.IP = []byte{ - 0xFD, 0, 0xE, 0xC2, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0x23, -} - -// RemoteCredProvider returns a credentials provider for the default remote -// endpoints such as EC2 or ECS Roles. -func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - if u := os.Getenv(httpProviderEnvVar); len(u) > 0 { - return localHTTPCredProvider(cfg, handlers, u) - } - - if uri := os.Getenv(shareddefaults.ECSCredsProviderEnvVar); len(uri) > 0 { - u := fmt.Sprintf("%s%s", shareddefaults.ECSContainerCredentialsURI, uri) - return httpCredProvider(cfg, handlers, u) - } - - return ec2RoleProvider(cfg, handlers) -} - -var lookupHostFn = net.LookupHost - -// isAllowedHost allows host to be loopback or known ECS/EKS container IPs -// -// host can either be an IP address OR an unresolved hostname - resolution will -// be automatically performed in the latter case -func isAllowedHost(host string) (bool, error) { - if ip := net.ParseIP(host); ip != nil { - return isIPAllowed(ip), nil - } - - addrs, err := lookupHostFn(host) - if err != nil { - return false, err - } - - for _, addr := range addrs { - if ip := net.ParseIP(addr); ip == nil || !isIPAllowed(ip) { - return false, nil - } - } - - return true, nil -} - -func isIPAllowed(ip net.IP) bool { - return ip.IsLoopback() || - ip.Equal(ecsContainerIPv4) || - ip.Equal(eksContainerIPv4) || - ip.Equal(eksContainerIPv6) -} - -func localHTTPCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { - var errMsg string - - parsed, err := url.Parse(u) - if err != nil { - errMsg = fmt.Sprintf("invalid URL, %v", err) - } else { - host := aws.URLHostname(parsed) - if len(host) == 0 { - errMsg = "unable to parse host from local HTTP cred provider URL" - } else if parsed.Scheme == "http" { - if isAllowedHost, allowHostErr := isAllowedHost(host); allowHostErr != nil { - errMsg = fmt.Sprintf("failed to resolve host %q, %v", host, allowHostErr) - } else if !isAllowedHost { - errMsg = fmt.Sprintf("invalid endpoint host, %q, only loopback/ecs/eks hosts are allowed.", host) - } - } - } - - if len(errMsg) > 0 { - if cfg.Logger != nil { - cfg.Logger.Log("Ignoring, HTTP credential provider", errMsg, err) - } - return credentials.ErrorProvider{ - Err: awserr.New("CredentialsEndpointError", errMsg, err), - ProviderName: endpointcreds.ProviderName, - } - } - - return httpCredProvider(cfg, handlers, u) -} - -func httpCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { - return endpointcreds.NewProviderClient(cfg, handlers, u, - func(p *endpointcreds.Provider) { - p.ExpiryWindow = 5 * time.Minute - p.AuthorizationToken = os.Getenv(httpProviderAuthorizationEnvVar) - if authFilePath := os.Getenv(httpProviderAuthFileEnvVar); authFilePath != "" { - p.AuthorizationTokenProvider = endpointcreds.TokenProviderFunc(func() (string, error) { - if contents, err := ioutil.ReadFile(authFilePath); err != nil { - return "", fmt.Errorf("failed to read authorization token from %v: %v", authFilePath, err) - } else { - return string(contents), nil - } - }) - } - }, - ) -} - -func ec2RoleProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - resolver := cfg.EndpointResolver - if resolver == nil { - resolver = endpoints.DefaultResolver() - } - - e, _ := resolver.EndpointFor(endpoints.Ec2metadataServiceID, "") - return &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.NewClient(cfg, handlers, e.URL, e.SigningRegion), - ExpiryWindow: 5 * time.Minute, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go deleted file mode 100644 index ca0ee1dcc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go +++ /dev/null @@ -1,27 +0,0 @@ -package defaults - -import ( - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// SharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func SharedCredentialsFilename() string { - return shareddefaults.SharedCredentialsFilename() -} - -// SharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func SharedConfigFilename() string { - return shareddefaults.SharedConfigFilename() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/doc.go deleted file mode 100644 index 4fcb61618..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/doc.go +++ /dev/null @@ -1,56 +0,0 @@ -// Package aws provides the core SDK's utilities and shared types. Use this package's -// utilities to simplify setting and reading API operations parameters. -// -// Value and Pointer Conversion Utilities -// -// This package includes a helper conversion utility for each scalar type the SDK's -// API use. These utilities make getting a pointer of the scalar, and dereferencing -// a pointer easier. -// -// Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. -// The Pointer to value will safely dereference the pointer and return its value. -// If the pointer was nil, the scalar's zero value will be returned. -// -// The value to pointer functions will be named after the scalar type. So get a -// *string from a string value use the "String" function. This makes it easy to -// to get pointer of a literal string value, because getting the address of a -// literal requires assigning the value to a variable first. -// -// var strPtr *string -// -// // Without the SDK's conversion functions -// str := "my string" -// strPtr = &str -// -// // With the SDK's conversion functions -// strPtr = aws.String("my string") -// -// // Convert *string to string value -// str = aws.StringValue(strPtr) -// -// In addition to scalars the aws package also includes conversion utilities for -// map and slice for commonly types used in API parameters. The map and slice -// conversion functions use similar naming pattern as the scalar conversion -// functions. -// -// var strPtrs []*string -// var strs []string = []string{"Go", "Gophers", "Go"} -// -// // Convert []string to []*string -// strPtrs = aws.StringSlice(strs) -// -// // Convert []*string to []string -// strs = aws.StringValueSlice(strPtrs) -// -// SDK Default HTTP Client -// -// The SDK will use the http.DefaultClient if a HTTP client is not provided to -// the SDK's Session, or service client constructor. This means that if the -// http.DefaultClient is modified by other components of your application the -// modifications will be picked up by the SDK as well. -// -// In some cases this might be intended, but it is a better practice to create -// a custom HTTP Client to share explicitly through your application. You can -// configure the SDK to use the custom HTTP Client by setting the HTTPClient -// value of the SDK's Config type when creating a Session or service client. -package aws diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go deleted file mode 100644 index 69fa63dc0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go +++ /dev/null @@ -1,250 +0,0 @@ -package ec2metadata - -import ( - "encoding/json" - "fmt" - "net/http" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkuri" -) - -// getToken uses the duration to return a token for EC2 metadata service, -// or an error if the request failed. -func (c *EC2Metadata) getToken(ctx aws.Context, duration time.Duration) (tokenOutput, error) { - op := &request.Operation{ - Name: "GetToken", - HTTPMethod: "PUT", - HTTPPath: "/latest/api/token", - } - - var output tokenOutput - req := c.NewRequest(op, nil, &output) - req.SetContext(ctx) - - // remove the fetch token handler from the request handlers to avoid infinite recursion - req.Handlers.Sign.RemoveByName(fetchTokenHandlerName) - - // Swap the unmarshalMetadataHandler with unmarshalTokenHandler on this request. - req.Handlers.Unmarshal.Swap(unmarshalMetadataHandlerName, unmarshalTokenHandler) - - ttl := strconv.FormatInt(int64(duration/time.Second), 10) - req.HTTPRequest.Header.Set(ttlHeader, ttl) - - err := req.Send() - - // Errors with bad request status should be returned. - if err != nil { - err = awserr.NewRequestFailure( - awserr.New(req.HTTPResponse.Status, http.StatusText(req.HTTPResponse.StatusCode), err), - req.HTTPResponse.StatusCode, req.RequestID) - } - - return output, err -} - -// GetMetadata uses the path provided to request information from the EC2 -// instance metadata service. The content will be returned as a string, or -// error if the request failed. -func (c *EC2Metadata) GetMetadata(p string) (string, error) { - return c.GetMetadataWithContext(aws.BackgroundContext(), p) -} - -// GetMetadataWithContext uses the path provided to request information from the EC2 -// instance metadata service. The content will be returned as a string, or -// error if the request failed. -func (c *EC2Metadata) GetMetadataWithContext(ctx aws.Context, p string) (string, error) { - op := &request.Operation{ - Name: "GetMetadata", - HTTPMethod: "GET", - HTTPPath: sdkuri.PathJoin("/latest/meta-data", p), - } - output := &metadataOutput{} - - req := c.NewRequest(op, nil, output) - - req.SetContext(ctx) - - err := req.Send() - return output.Content, err -} - -// GetUserData returns the userdata that was configured for the service. If -// there is no user-data setup for the EC2 instance a "NotFoundError" error -// code will be returned. -func (c *EC2Metadata) GetUserData() (string, error) { - return c.GetUserDataWithContext(aws.BackgroundContext()) -} - -// GetUserDataWithContext returns the userdata that was configured for the service. If -// there is no user-data setup for the EC2 instance a "NotFoundError" error -// code will be returned. -func (c *EC2Metadata) GetUserDataWithContext(ctx aws.Context) (string, error) { - op := &request.Operation{ - Name: "GetUserData", - HTTPMethod: "GET", - HTTPPath: "/latest/user-data", - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - req.SetContext(ctx) - - err := req.Send() - return output.Content, err -} - -// GetDynamicData uses the path provided to request information from the EC2 -// instance metadata service for dynamic data. The content will be returned -// as a string, or error if the request failed. -func (c *EC2Metadata) GetDynamicData(p string) (string, error) { - return c.GetDynamicDataWithContext(aws.BackgroundContext(), p) -} - -// GetDynamicDataWithContext uses the path provided to request information from the EC2 -// instance metadata service for dynamic data. The content will be returned -// as a string, or error if the request failed. -func (c *EC2Metadata) GetDynamicDataWithContext(ctx aws.Context, p string) (string, error) { - op := &request.Operation{ - Name: "GetDynamicData", - HTTPMethod: "GET", - HTTPPath: sdkuri.PathJoin("/latest/dynamic", p), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - req.SetContext(ctx) - - err := req.Send() - return output.Content, err -} - -// GetInstanceIdentityDocument retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *EC2Metadata) GetInstanceIdentityDocument() (EC2InstanceIdentityDocument, error) { - return c.GetInstanceIdentityDocumentWithContext(aws.BackgroundContext()) -} - -// GetInstanceIdentityDocumentWithContext retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *EC2Metadata) GetInstanceIdentityDocumentWithContext(ctx aws.Context) (EC2InstanceIdentityDocument, error) { - resp, err := c.GetDynamicDataWithContext(ctx, "instance-identity/document") - if err != nil { - return EC2InstanceIdentityDocument{}, - awserr.New("EC2MetadataRequestError", - "failed to get EC2 instance identity document", err) - } - - doc := EC2InstanceIdentityDocument{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&doc); err != nil { - return EC2InstanceIdentityDocument{}, - awserr.New(request.ErrCodeSerialization, - "failed to decode EC2 instance identity document", err) - } - - return doc, nil -} - -// IAMInfo retrieves IAM info from the metadata API -func (c *EC2Metadata) IAMInfo() (EC2IAMInfo, error) { - return c.IAMInfoWithContext(aws.BackgroundContext()) -} - -// IAMInfoWithContext retrieves IAM info from the metadata API -func (c *EC2Metadata) IAMInfoWithContext(ctx aws.Context) (EC2IAMInfo, error) { - resp, err := c.GetMetadataWithContext(ctx, "iam/info") - if err != nil { - return EC2IAMInfo{}, - awserr.New("EC2MetadataRequestError", - "failed to get EC2 IAM info", err) - } - - info := EC2IAMInfo{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&info); err != nil { - return EC2IAMInfo{}, - awserr.New(request.ErrCodeSerialization, - "failed to decode EC2 IAM info", err) - } - - if info.Code != "Success" { - errMsg := fmt.Sprintf("failed to get EC2 IAM Info (%s)", info.Code) - return EC2IAMInfo{}, - awserr.New("EC2MetadataError", errMsg, nil) - } - - return info, nil -} - -// Region returns the region the instance is running in. -func (c *EC2Metadata) Region() (string, error) { - return c.RegionWithContext(aws.BackgroundContext()) -} - -// RegionWithContext returns the region the instance is running in. -func (c *EC2Metadata) RegionWithContext(ctx aws.Context) (string, error) { - ec2InstanceIdentityDocument, err := c.GetInstanceIdentityDocumentWithContext(ctx) - if err != nil { - return "", err - } - // extract region from the ec2InstanceIdentityDocument - region := ec2InstanceIdentityDocument.Region - if len(region) == 0 { - return "", awserr.New("EC2MetadataError", "invalid region received for ec2metadata instance", nil) - } - // returns region - return region, nil -} - -// Available returns if the application has access to the EC2 Metadata service. -// Can be used to determine if application is running within an EC2 Instance and -// the metadata service is available. -func (c *EC2Metadata) Available() bool { - return c.AvailableWithContext(aws.BackgroundContext()) -} - -// AvailableWithContext returns if the application has access to the EC2 Metadata service. -// Can be used to determine if application is running within an EC2 Instance and -// the metadata service is available. -func (c *EC2Metadata) AvailableWithContext(ctx aws.Context) bool { - if _, err := c.GetMetadataWithContext(ctx, "instance-id"); err != nil { - return false - } - - return true -} - -// An EC2IAMInfo provides the shape for unmarshaling -// an IAM info from the metadata API -type EC2IAMInfo struct { - Code string - LastUpdated time.Time - InstanceProfileArn string - InstanceProfileID string -} - -// An EC2InstanceIdentityDocument provides the shape for unmarshaling -// an instance identity document -type EC2InstanceIdentityDocument struct { - DevpayProductCodes []string `json:"devpayProductCodes"` - MarketplaceProductCodes []string `json:"marketplaceProductCodes"` - AvailabilityZone string `json:"availabilityZone"` - PrivateIP string `json:"privateIp"` - Version string `json:"version"` - Region string `json:"region"` - InstanceID string `json:"instanceId"` - BillingProducts []string `json:"billingProducts"` - InstanceType string `json:"instanceType"` - AccountID string `json:"accountId"` - PendingTime time.Time `json:"pendingTime"` - ImageID string `json:"imageId"` - KernelID string `json:"kernelId"` - RamdiskID string `json:"ramdiskId"` - Architecture string `json:"architecture"` -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go deleted file mode 100644 index f4cc8751d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go +++ /dev/null @@ -1,245 +0,0 @@ -// Package ec2metadata provides the client for making API calls to the -// EC2 Metadata service. -// -// This package's client can be disabled completely by setting the environment -// variable "AWS_EC2_METADATA_DISABLED=true". This environment variable set to -// true instructs the SDK to disable the EC2 Metadata client. The client cannot -// be used while the environment variable is set to true, (case insensitive). -// -// The endpoint of the EC2 IMDS client can be configured via the environment -// variable, AWS_EC2_METADATA_SERVICE_ENDPOINT when creating the client with a -// Session. See aws/session#Options.EC2IMDSEndpoint for more details. -package ec2metadata - -import ( - "bytes" - "io" - "net/http" - "net/url" - "os" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/request" -) - -const ( - // ServiceName is the name of the service. - ServiceName = "ec2metadata" - disableServiceEnvVar = "AWS_EC2_METADATA_DISABLED" - - // Headers for Token and TTL - ttlHeader = "x-aws-ec2-metadata-token-ttl-seconds" - tokenHeader = "x-aws-ec2-metadata-token" - - // Named Handler constants - fetchTokenHandlerName = "FetchTokenHandler" - unmarshalMetadataHandlerName = "unmarshalMetadataHandler" - unmarshalTokenHandlerName = "unmarshalTokenHandler" - enableTokenProviderHandlerName = "enableTokenProviderHandler" - - // TTL constants - defaultTTL = 21600 * time.Second - ttlExpirationWindow = 30 * time.Second -) - -// A EC2Metadata is an EC2 Metadata service Client. -type EC2Metadata struct { - *client.Client -} - -// New creates a new instance of the EC2Metadata client with a session. -// This client is safe to use across multiple goroutines. -// -// Example: -// -// // Create a EC2Metadata client from just a session. -// svc := ec2metadata.New(mySession) -// -// // Create a EC2Metadata client with additional configuration -// svc := ec2metadata.New(mySession, aws.NewConfig().WithLogLevel(aws.LogDebugHTTPBody)) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2Metadata { - c := p.ClientConfig(ServiceName, cfgs...) - return NewClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion) -} - -// NewClient returns a new EC2Metadata client. Should be used to create -// a client when not using a session. Generally using just New with a session -// is preferred. -// -// Will remove the URL path from the endpoint provided to ensure the EC2 IMDS -// client is able to communicate with the EC2 IMDS API. -// -// If an unmodified HTTP client is provided from the stdlib default, or no client -// the EC2RoleProvider's EC2Metadata HTTP client's timeout will be shortened. -// To disable this set Config.EC2MetadataDisableTimeoutOverride to false. Enabled by default. -func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string, opts ...func(*client.Client)) *EC2Metadata { - if !aws.BoolValue(cfg.EC2MetadataDisableTimeoutOverride) && httpClientZero(cfg.HTTPClient) { - // If the http client is unmodified and this feature is not disabled - // set custom timeouts for EC2Metadata requests. - cfg.HTTPClient = &http.Client{ - // use a shorter timeout than default because the metadata - // service is local if it is running, and to fail faster - // if not running on an ec2 instance. - Timeout: 1 * time.Second, - } - // max number of retries on the client operation - cfg.MaxRetries = aws.Int(2) - } - - if u, err := url.Parse(endpoint); err == nil { - // Remove path from the endpoint since it will be added by requests. - // This is an artifact of the SDK adding `/latest` to the endpoint for - // EC2 IMDS, but this is now moved to the operation definition. - u.Path = "" - u.RawPath = "" - endpoint = u.String() - } - - svc := &EC2Metadata{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - ServiceID: ServiceName, - Endpoint: endpoint, - APIVersion: "latest", - }, - handlers, - ), - } - - // token provider instance - tp := newTokenProvider(svc, defaultTTL) - - // NamedHandler for fetching token - svc.Handlers.Sign.PushBackNamed(request.NamedHandler{ - Name: fetchTokenHandlerName, - Fn: tp.fetchTokenHandler, - }) - // NamedHandler for enabling token provider - svc.Handlers.Complete.PushBackNamed(request.NamedHandler{ - Name: enableTokenProviderHandlerName, - Fn: tp.enableTokenProviderHandler, - }) - - svc.Handlers.Unmarshal.PushBackNamed(unmarshalHandler) - svc.Handlers.UnmarshalError.PushBack(unmarshalError) - svc.Handlers.Validate.Clear() - svc.Handlers.Validate.PushBack(validateEndpointHandler) - - // Disable the EC2 Metadata service if the environment variable is set. - // This short-circuits the service's functionality to always fail to send - // requests. - if strings.ToLower(os.Getenv(disableServiceEnvVar)) == "true" { - svc.Handlers.Send.SwapNamed(request.NamedHandler{ - Name: corehandlers.SendHandler.Name, - Fn: func(r *request.Request) { - r.HTTPResponse = &http.Response{ - Header: http.Header{}, - } - r.Error = awserr.New( - request.CanceledErrorCode, - "EC2 IMDS access disabled via "+disableServiceEnvVar+" env var", - nil) - }, - }) - } - - // Add additional options to the service config - for _, option := range opts { - option(svc.Client) - } - return svc -} - -func httpClientZero(c *http.Client) bool { - return c == nil || (c.Transport == nil && c.CheckRedirect == nil && c.Jar == nil && c.Timeout == 0) -} - -type metadataOutput struct { - Content string -} - -type tokenOutput struct { - Token string - TTL time.Duration -} - -// unmarshal token handler is used to parse the response of a getToken operation -var unmarshalTokenHandler = request.NamedHandler{ - Name: unmarshalTokenHandlerName, - Fn: func(r *request.Request) { - defer r.HTTPResponse.Body.Close() - var b bytes.Buffer - if _, err := io.Copy(&b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.NewRequestFailure(awserr.New(request.ErrCodeSerialization, - "unable to unmarshal EC2 metadata response", err), r.HTTPResponse.StatusCode, r.RequestID) - return - } - - v := r.HTTPResponse.Header.Get(ttlHeader) - data, ok := r.Data.(*tokenOutput) - if !ok { - return - } - - data.Token = b.String() - // TTL is in seconds - i, err := strconv.ParseInt(v, 10, 64) - if err != nil { - r.Error = awserr.NewRequestFailure(awserr.New(request.ParamFormatErrCode, - "unable to parse EC2 token TTL response", err), r.HTTPResponse.StatusCode, r.RequestID) - return - } - t := time.Duration(i) * time.Second - data.TTL = t - }, -} - -var unmarshalHandler = request.NamedHandler{ - Name: unmarshalMetadataHandlerName, - Fn: func(r *request.Request) { - defer r.HTTPResponse.Body.Close() - var b bytes.Buffer - if _, err := io.Copy(&b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.NewRequestFailure(awserr.New(request.ErrCodeSerialization, - "unable to unmarshal EC2 metadata response", err), r.HTTPResponse.StatusCode, r.RequestID) - return - } - - if data, ok := r.Data.(*metadataOutput); ok { - data.Content = b.String() - } - }, -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - var b bytes.Buffer - - if _, err := io.Copy(&b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, "unable to unmarshal EC2 metadata error response", err), - r.HTTPResponse.StatusCode, r.RequestID) - return - } - - // Response body format is not consistent between metadata endpoints. - // Grab the error message as a string and include that as the source error - r.Error = awserr.NewRequestFailure( - awserr.New("EC2MetadataError", "failed to make EC2Metadata request\n"+b.String(), nil), - r.HTTPResponse.StatusCode, r.RequestID) -} - -func validateEndpointHandler(r *request.Request) { - if r.ClientInfo.Endpoint == "" { - r.Error = aws.ErrMissingEndpoint - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/token_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/token_provider.go deleted file mode 100644 index f1f9ba4ec..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/token_provider.go +++ /dev/null @@ -1,99 +0,0 @@ -package ec2metadata - -import ( - "fmt" - "github.com/aws/aws-sdk-go/aws" - "net/http" - "sync/atomic" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A tokenProvider struct provides access to EC2Metadata client -// and atomic instance of a token, along with configuredTTL for it. -// tokenProvider also provides an atomic flag to disable the -// fetch token operation. -// The disabled member will use 0 as false, and 1 as true. -type tokenProvider struct { - client *EC2Metadata - token atomic.Value - configuredTTL time.Duration - disabled uint32 -} - -// A ec2Token struct helps use of token in EC2 Metadata service ops -type ec2Token struct { - token string - credentials.Expiry -} - -// newTokenProvider provides a pointer to a tokenProvider instance -func newTokenProvider(c *EC2Metadata, duration time.Duration) *tokenProvider { - return &tokenProvider{client: c, configuredTTL: duration} -} - -// check if fallback is enabled -func (t *tokenProvider) fallbackEnabled() bool { - return t.client.Config.EC2MetadataEnableFallback == nil || *t.client.Config.EC2MetadataEnableFallback -} - -// fetchTokenHandler fetches token for EC2Metadata service client by default. -func (t *tokenProvider) fetchTokenHandler(r *request.Request) { - // short-circuits to insecure data flow if tokenProvider is disabled. - if v := atomic.LoadUint32(&t.disabled); v == 1 && t.fallbackEnabled() { - return - } - - if ec2Token, ok := t.token.Load().(ec2Token); ok && !ec2Token.IsExpired() { - r.HTTPRequest.Header.Set(tokenHeader, ec2Token.token) - return - } - - output, err := t.client.getToken(r.Context(), t.configuredTTL) - - if err != nil { - // only attempt fallback to insecure data flow if IMDSv1 is enabled - if !t.fallbackEnabled() { - r.Error = awserr.New("EC2MetadataError", "failed to get IMDSv2 token and fallback to IMDSv1 is disabled", err) - return - } - - // change the disabled flag on token provider to true and fallback - if requestFailureError, ok := err.(awserr.RequestFailure); ok { - switch requestFailureError.StatusCode() { - case http.StatusForbidden, http.StatusNotFound, http.StatusMethodNotAllowed: - atomic.StoreUint32(&t.disabled, 1) - if t.client.Config.LogLevel.Matches(aws.LogDebugWithDeprecated) { - t.client.Config.Logger.Log(fmt.Sprintf("WARN: failed to get session token, falling back to IMDSv1: %v", requestFailureError)) - } - case http.StatusBadRequest: - r.Error = requestFailureError - } - } - return - } - - newToken := ec2Token{ - token: output.Token, - } - newToken.SetExpiration(time.Now().Add(output.TTL), ttlExpirationWindow) - t.token.Store(newToken) - - // Inject token header to the request. - if ec2Token, ok := t.token.Load().(ec2Token); ok { - r.HTTPRequest.Header.Set(tokenHeader, ec2Token.token) - } -} - -// enableTokenProviderHandler enables the token provider -func (t *tokenProvider) enableTokenProviderHandler(r *request.Request) { - // If the error code status is 401, we enable the token provider - if e, ok := r.Error.(awserr.RequestFailure); ok && e != nil && - e.StatusCode() == http.StatusUnauthorized { - t.token.Store(ec2Token{}) - atomic.StoreUint32(&t.disabled, 0) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go deleted file mode 100644 index cad3b9a48..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go +++ /dev/null @@ -1,193 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -type modelDefinition map[string]json.RawMessage - -// A DecodeModelOptions are the options for how the endpoints model definition -// are decoded. -type DecodeModelOptions struct { - SkipCustomizations bool -} - -// Set combines all of the option functions together. -func (d *DecodeModelOptions) Set(optFns ...func(*DecodeModelOptions)) { - for _, fn := range optFns { - fn(d) - } -} - -// DecodeModel unmarshals a Regions and Endpoint model definition file into -// a endpoint Resolver. If the file format is not supported, or an error occurs -// when unmarshaling the model an error will be returned. -// -// Casting the return value of this func to a EnumPartitions will -// allow you to get a list of the partitions in the order the endpoints -// will be resolved in. -// -// resolver, err := endpoints.DecodeModel(reader) -// -// partitions := resolver.(endpoints.EnumPartitions).Partitions() -// for _, p := range partitions { -// // ... inspect partitions -// } -func DecodeModel(r io.Reader, optFns ...func(*DecodeModelOptions)) (Resolver, error) { - var opts DecodeModelOptions - opts.Set(optFns...) - - // Get the version of the partition file to determine what - // unmarshaling model to use. - modelDef := modelDefinition{} - if err := json.NewDecoder(r).Decode(&modelDef); err != nil { - return nil, newDecodeModelError("failed to decode endpoints model", err) - } - - var version string - if b, ok := modelDef["version"]; ok { - version = string(b) - } else { - return nil, newDecodeModelError("endpoints version not found in model", nil) - } - - if version == "3" { - return decodeV3Endpoints(modelDef, opts) - } - - return nil, newDecodeModelError( - fmt.Sprintf("endpoints version %s, not supported", version), nil) -} - -func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resolver, error) { - b, ok := modelDef["partitions"] - if !ok { - return nil, newDecodeModelError("endpoints model missing partitions", nil) - } - - ps := partitions{} - if err := json.Unmarshal(b, &ps); err != nil { - return nil, newDecodeModelError("failed to decode endpoints model", err) - } - - if opts.SkipCustomizations { - return ps, nil - } - - // Customization - for i := 0; i < len(ps); i++ { - p := &ps[i] - custRegionalS3(p) - custRmIotDataService(p) - custFixAppAutoscalingChina(p) - custFixAppAutoscalingUsGov(p) - } - - return ps, nil -} - -func custRegionalS3(p *partition) { - if p.ID != "aws" { - return - } - - service, ok := p.Services["s3"] - if !ok { - return - } - - const awsGlobal = "aws-global" - const usEast1 = "us-east-1" - - // If global endpoint already exists no customization needed. - if _, ok := service.Endpoints[endpointKey{Region: awsGlobal}]; ok { - return - } - - service.PartitionEndpoint = awsGlobal - if _, ok := service.Endpoints[endpointKey{Region: usEast1}]; !ok { - service.Endpoints[endpointKey{Region: usEast1}] = endpoint{} - } - service.Endpoints[endpointKey{Region: awsGlobal}] = endpoint{ - Hostname: "s3.amazonaws.com", - CredentialScope: credentialScope{ - Region: usEast1, - }, - } - - p.Services["s3"] = service -} - -func custRmIotDataService(p *partition) { - delete(p.Services, "data.iot") -} - -func custFixAppAutoscalingChina(p *partition) { - if p.ID != "aws-cn" { - return - } - - const serviceName = "application-autoscaling" - s, ok := p.Services[serviceName] - if !ok { - return - } - - const expectHostname = `autoscaling.{region}.amazonaws.com` - serviceDefault := s.Defaults[defaultKey{}] - if e, a := expectHostname, serviceDefault.Hostname; e != a { - fmt.Printf("custFixAppAutoscalingChina: ignoring customization, expected %s, got %s\n", e, a) - return - } - serviceDefault.Hostname = expectHostname + ".cn" - s.Defaults[defaultKey{}] = serviceDefault - p.Services[serviceName] = s -} - -func custFixAppAutoscalingUsGov(p *partition) { - if p.ID != "aws-us-gov" { - return - } - - const serviceName = "application-autoscaling" - s, ok := p.Services[serviceName] - if !ok { - return - } - - serviceDefault := s.Defaults[defaultKey{}] - if a := serviceDefault.CredentialScope.Service; a != "" { - fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty credential scope service, got %s\n", a) - return - } - - if a := serviceDefault.Hostname; a != "" { - fmt.Printf("custFixAppAutoscalingUsGov: ignoring customization, expected empty hostname, got %s\n", a) - return - } - - serviceDefault.CredentialScope.Service = "application-autoscaling" - serviceDefault.Hostname = "autoscaling.{region}.amazonaws.com" - - if s.Defaults == nil { - s.Defaults = make(endpointDefaults) - } - - s.Defaults[defaultKey{}] = serviceDefault - - p.Services[serviceName] = s -} - -type decodeModelError struct { - awsError -} - -func newDecodeModelError(msg string, err error) decodeModelError { - return decodeModelError{ - awsError: awserr.New("DecodeEndpointsModelError", msg, err), - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go deleted file mode 100644 index c3516e018..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ /dev/null @@ -1,48609 +0,0 @@ -// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. - -package endpoints - -import ( - "regexp" -) - -// Partition identifiers -const ( - AwsPartitionID = "aws" // AWS Standard partition. - AwsCnPartitionID = "aws-cn" // AWS China partition. - AwsUsGovPartitionID = "aws-us-gov" // AWS GovCloud (US) partition. - AwsIsoPartitionID = "aws-iso" // AWS ISO (US) partition. - AwsIsoBPartitionID = "aws-iso-b" // AWS ISOB (US) partition. - AwsIsoEPartitionID = "aws-iso-e" // AWS ISOE (Europe) partition. - AwsIsoFPartitionID = "aws-iso-f" // AWS ISOF partition. -) - -// AWS Standard partition's regions. -const ( - AfSouth1RegionID = "af-south-1" // Africa (Cape Town). - ApEast1RegionID = "ap-east-1" // Asia Pacific (Hong Kong). - ApNortheast1RegionID = "ap-northeast-1" // Asia Pacific (Tokyo). - ApNortheast2RegionID = "ap-northeast-2" // Asia Pacific (Seoul). - ApNortheast3RegionID = "ap-northeast-3" // Asia Pacific (Osaka). - ApSouth1RegionID = "ap-south-1" // Asia Pacific (Mumbai). - ApSouth2RegionID = "ap-south-2" // Asia Pacific (Hyderabad). - ApSoutheast1RegionID = "ap-southeast-1" // Asia Pacific (Singapore). - ApSoutheast2RegionID = "ap-southeast-2" // Asia Pacific (Sydney). - ApSoutheast3RegionID = "ap-southeast-3" // Asia Pacific (Jakarta). - ApSoutheast4RegionID = "ap-southeast-4" // Asia Pacific (Melbourne). - CaCentral1RegionID = "ca-central-1" // Canada (Central). - CaWest1RegionID = "ca-west-1" // Canada West (Calgary). - EuCentral1RegionID = "eu-central-1" // Europe (Frankfurt). - EuCentral2RegionID = "eu-central-2" // Europe (Zurich). - EuNorth1RegionID = "eu-north-1" // Europe (Stockholm). - EuSouth1RegionID = "eu-south-1" // Europe (Milan). - EuSouth2RegionID = "eu-south-2" // Europe (Spain). - EuWest1RegionID = "eu-west-1" // Europe (Ireland). - EuWest2RegionID = "eu-west-2" // Europe (London). - EuWest3RegionID = "eu-west-3" // Europe (Paris). - IlCentral1RegionID = "il-central-1" // Israel (Tel Aviv). - MeCentral1RegionID = "me-central-1" // Middle East (UAE). - MeSouth1RegionID = "me-south-1" // Middle East (Bahrain). - SaEast1RegionID = "sa-east-1" // South America (Sao Paulo). - UsEast1RegionID = "us-east-1" // US East (N. Virginia). - UsEast2RegionID = "us-east-2" // US East (Ohio). - UsWest1RegionID = "us-west-1" // US West (N. California). - UsWest2RegionID = "us-west-2" // US West (Oregon). -) - -// AWS China partition's regions. -const ( - CnNorth1RegionID = "cn-north-1" // China (Beijing). - CnNorthwest1RegionID = "cn-northwest-1" // China (Ningxia). -) - -// AWS GovCloud (US) partition's regions. -const ( - UsGovEast1RegionID = "us-gov-east-1" // AWS GovCloud (US-East). - UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US-West). -) - -// AWS ISO (US) partition's regions. -const ( - UsIsoEast1RegionID = "us-iso-east-1" // US ISO East. - UsIsoWest1RegionID = "us-iso-west-1" // US ISO WEST. -) - -// AWS ISOB (US) partition's regions. -const ( - UsIsobEast1RegionID = "us-isob-east-1" // US ISOB East (Ohio). -) - -// AWS ISOE (Europe) partition's regions. -const ( - EuIsoeWest1RegionID = "eu-isoe-west-1" // EU ISOE West. -) - -// AWS ISOF partition's regions. -const () - -// DefaultResolver returns an Endpoint resolver that will be able -// to resolve endpoints for: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), AWS ISOB (US), AWS ISOE (Europe), and AWS ISOF. -// -// Use DefaultPartitions() to get the list of the default partitions. -func DefaultResolver() Resolver { - return defaultPartitions -} - -// DefaultPartitions returns a list of the partitions the SDK is bundled -// with. The available partitions are: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), AWS ISOB (US), AWS ISOE (Europe), and AWS ISOF. -// -// partitions := endpoints.DefaultPartitions -// for _, p := range partitions { -// // ... inspect partitions -// } -func DefaultPartitions() []Partition { - return defaultPartitions.Partitions() -} - -var defaultPartitions = partitions{ - awsPartition, - awscnPartition, - awsusgovPartition, - awsisoPartition, - awsisobPartition, - awsisoePartition, - awsisofPartition, -} - -// AwsPartition returns the Resolver for AWS Standard. -func AwsPartition() Partition { - return awsPartition.Partition() -} - -var awsPartition = partition{ - ID: "aws", - Name: "AWS Standard", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - Regions: regions{ - "af-south-1": region{ - Description: "Africa (Cape Town)", - }, - "ap-east-1": region{ - Description: "Asia Pacific (Hong Kong)", - }, - "ap-northeast-1": region{ - Description: "Asia Pacific (Tokyo)", - }, - "ap-northeast-2": region{ - Description: "Asia Pacific (Seoul)", - }, - "ap-northeast-3": region{ - Description: "Asia Pacific (Osaka)", - }, - "ap-south-1": region{ - Description: "Asia Pacific (Mumbai)", - }, - "ap-south-2": region{ - Description: "Asia Pacific (Hyderabad)", - }, - "ap-southeast-1": region{ - Description: "Asia Pacific (Singapore)", - }, - "ap-southeast-2": region{ - Description: "Asia Pacific (Sydney)", - }, - "ap-southeast-3": region{ - Description: "Asia Pacific (Jakarta)", - }, - "ap-southeast-4": region{ - Description: "Asia Pacific (Melbourne)", - }, - "ca-central-1": region{ - Description: "Canada (Central)", - }, - "ca-west-1": region{ - Description: "Canada West (Calgary)", - }, - "eu-central-1": region{ - Description: "Europe (Frankfurt)", - }, - "eu-central-2": region{ - Description: "Europe (Zurich)", - }, - "eu-north-1": region{ - Description: "Europe (Stockholm)", - }, - "eu-south-1": region{ - Description: "Europe (Milan)", - }, - "eu-south-2": region{ - Description: "Europe (Spain)", - }, - "eu-west-1": region{ - Description: "Europe (Ireland)", - }, - "eu-west-2": region{ - Description: "Europe (London)", - }, - "eu-west-3": region{ - Description: "Europe (Paris)", - }, - "il-central-1": region{ - Description: "Israel (Tel Aviv)", - }, - "me-central-1": region{ - Description: "Middle East (UAE)", - }, - "me-south-1": region{ - Description: "Middle East (Bahrain)", - }, - "sa-east-1": region{ - Description: "South America (Sao Paulo)", - }, - "us-east-1": region{ - Description: "US East (N. Virginia)", - }, - "us-east-2": region{ - Description: "US East (Ohio)", - }, - "us-west-1": region{ - Description: "US West (N. California)", - }, - "us-west-2": region{ - Description: "US West (Oregon)", - }, - }, - Services: services{ - "access-analyzer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "access-analyzer-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "access-analyzer-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "access-analyzer-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "access-analyzer-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "access-analyzer-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "access-analyzer-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "access-analyzer-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "access-analyzer-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "access-analyzer-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "access-analyzer-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "access-analyzer-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "access-analyzer-fips.us-west-2.amazonaws.com", - }, - }, - }, - "account": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "account.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "acm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "acm-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - Hostname: "acm-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "acm-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "acm-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "acm-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "acm-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "acm-pca": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "acm-pca-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "acm-pca-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "acm-pca-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "acm-pca-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "acm-pca-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "acm-pca-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca-fips.us-west-2.amazonaws.com", - }, - }, - }, - "agreement-marketplace": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "airflow": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "amplify": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "amplifybackend": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "amplifyuibuilder": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "aoss": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "api.detective": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.detective-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "api.detective-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.detective-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "api.detective-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.detective-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "api.detective-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.detective-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "api.detective-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.detective-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "api.detective-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "api.ecr": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "api.ecr.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "api.ecr.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "api.ecr.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "api.ecr.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "api.ecr.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "api.ecr.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "api.ecr.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "api.ecr.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "api.ecr.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "api.ecr.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "api.ecr.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "api.ecr.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "api.ecr.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "dkr-us-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-east-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-west-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "api.ecr.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "api.ecr.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "api.ecr.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "api.ecr.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "api.ecr.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "api.ecr.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "api.ecr.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "api.ecr.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "fips-dkr-us-east-1", - }: endpoint{ - Hostname: "ecr-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-dkr-us-east-2", - }: endpoint{ - Hostname: "ecr-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-dkr-us-west-1", - }: endpoint{ - Hostname: "ecr-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-dkr-us-west-2", - }: endpoint{ - Hostname: "ecr-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ecr-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ecr-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ecr-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ecr-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "api.ecr.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "api.ecr.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "api.ecr.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "api.ecr.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "api.ecr.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "api.ecr.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "api.ecr.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "api.ecr.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "api.ecr-public": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "api.ecr-public.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "api.ecr-public.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "api.elastic-inference": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "api.elastic-inference.ap-northeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "api.elastic-inference.ap-northeast-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "api.elastic-inference.eu-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "api.elastic-inference.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "api.elastic-inference.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "api.elastic-inference.us-west-2.amazonaws.com", - }, - }, - }, - "api.fleethub.iot": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.fleethub.iot-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "api.fleethub.iot-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "api.fleethub.iot-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "api.fleethub.iot-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "api.fleethub.iot-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.fleethub.iot-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.fleethub.iot-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.fleethub.iot-fips.us-west-2.amazonaws.com", - }, - }, - }, - "api.iotdeviceadvisor": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "api.iotdeviceadvisor.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "api.iotdeviceadvisor.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "api.iotdeviceadvisor.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "api.iotdeviceadvisor.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "api.iotwireless": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "api.iotwireless.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "api.iotwireless.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "api.iotwireless.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "api.iotwireless.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "api.iotwireless.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "api.iotwireless.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "api.iotwireless.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "api.mediatailor": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "api.pricing": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "pricing", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "api.sagemaker": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "api-fips.sagemaker.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api-fips.sagemaker.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "api-fips.sagemaker.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api-fips.sagemaker.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "api-fips.sagemaker.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api-fips.sagemaker.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "api-fips.sagemaker.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api-fips.sagemaker.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "api-fips.sagemaker.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "api.tunneling.iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-west-2.amazonaws.com", - }, - }, - }, - "apigateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apigateway-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apigateway-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "apigateway-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "apigateway-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "apigateway-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "apigateway-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "apigateway-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "apigateway-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apigateway-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apigateway-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apigateway-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apigateway-fips.us-west-2.amazonaws.com", - }, - }, - }, - "app-integrations": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "appconfig": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "appconfigdata": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "appflow": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "appflow-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "appflow-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "appflow-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "appflow-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appflow-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appflow-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appflow-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appflow-fips.us-west-2.amazonaws.com", - }, - }, - }, - "application-autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "applicationinsights": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "appmesh": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appmesh-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "appmesh-fips.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "appmesh-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.eu-west-3.api.aws", - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appmesh-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "appmesh-fips.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "appmesh-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appmesh-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "appmesh-fips.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "appmesh-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appmesh-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "appmesh-fips.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "appmesh-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appmesh-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "appmesh-fips.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "appmesh-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "apprunner": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "apprunner-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "apprunner-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "apprunner-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apprunner-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apprunner-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "apprunner-fips.us-west-2.amazonaws.com", - }, - }, - }, - "appstream2": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Service: "appstream", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "appstream2-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appstream2-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "appstream2-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appstream2-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "appstream2-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "appsync": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "aps": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "arc-zonal-shift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "athena": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.eu-west-3.api.aws", - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "athena-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "athena-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "athena-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "athena-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "athena-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "athena-fips.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "athena-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "athena-fips.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "athena-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "athena-fips.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "athena-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "athena-fips.us-west-2.api.aws", - }, - }, - }, - "auditmanager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "auditmanager-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "auditmanager-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "auditmanager-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "auditmanager-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "auditmanager-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "auditmanager-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "auditmanager-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "auditmanager-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "autoscaling-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "autoscaling-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "autoscaling-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "autoscaling-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "autoscaling-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "autoscaling-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling-fips.us-west-2.amazonaws.com", - }, - }, - }, - "autoscaling-plans": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "backup": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "backup-gateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "batch": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.batch.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "fips.batch.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "fips.batch.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "fips.batch.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "fips.batch.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.batch.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.batch.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.batch.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.batch.us-west-2.amazonaws.com", - }, - }, - }, - "bedrock": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "bedrock-ap-northeast-1", - }: endpoint{ - Hostname: "bedrock.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "bedrock-ap-south-1", - }: endpoint{ - Hostname: "bedrock.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "bedrock-ap-southeast-1", - }: endpoint{ - Hostname: "bedrock.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "bedrock-ap-southeast-2", - }: endpoint{ - Hostname: "bedrock.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "bedrock-ca-central-1", - }: endpoint{ - Hostname: "bedrock.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "bedrock-eu-central-1", - }: endpoint{ - Hostname: "bedrock.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "bedrock-eu-west-1", - }: endpoint{ - Hostname: "bedrock.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "bedrock-eu-west-2", - }: endpoint{ - Hostname: "bedrock.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "bedrock-eu-west-3", - }: endpoint{ - Hostname: "bedrock.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "bedrock-fips-ca-central-1", - }: endpoint{ - Hostname: "bedrock-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "bedrock-fips-us-east-1", - }: endpoint{ - Hostname: "bedrock-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "bedrock-fips-us-west-2", - }: endpoint{ - Hostname: "bedrock-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "bedrock-runtime-ap-northeast-1", - }: endpoint{ - Hostname: "bedrock-runtime.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-ap-south-1", - }: endpoint{ - Hostname: "bedrock-runtime.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-ap-southeast-1", - }: endpoint{ - Hostname: "bedrock-runtime.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-ap-southeast-2", - }: endpoint{ - Hostname: "bedrock-runtime.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "bedrock-runtime-ca-central-1", - }: endpoint{ - Hostname: "bedrock-runtime.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-eu-central-1", - }: endpoint{ - Hostname: "bedrock-runtime.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-eu-west-1", - }: endpoint{ - Hostname: "bedrock-runtime.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-eu-west-2", - }: endpoint{ - Hostname: "bedrock-runtime.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "bedrock-runtime-eu-west-3", - }: endpoint{ - Hostname: "bedrock-runtime.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "bedrock-runtime-fips-ca-central-1", - }: endpoint{ - Hostname: "bedrock-runtime-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-fips-us-east-1", - }: endpoint{ - Hostname: "bedrock-runtime-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-fips-us-west-2", - }: endpoint{ - Hostname: "bedrock-runtime-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "bedrock-runtime-sa-east-1", - }: endpoint{ - Hostname: "bedrock-runtime.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-us-east-1", - }: endpoint{ - Hostname: "bedrock-runtime.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-us-west-2", - }: endpoint{ - Hostname: "bedrock-runtime.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "bedrock-sa-east-1", - }: endpoint{ - Hostname: "bedrock.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "bedrock-us-east-1", - }: endpoint{ - Hostname: "bedrock.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "bedrock-us-west-2", - }: endpoint{ - Hostname: "bedrock.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "billingconductor": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "billingconductor.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "braket": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "budgets": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "budgets.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cases": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{}, - }, - }, - "cassandra": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "cassandra-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "cassandra-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cassandra-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cassandra-fips.us-west-2.amazonaws.com", - }, - }, - }, - "catalog.marketplace": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "ce": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "ce.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "chime": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "chime.us-east-1.amazonaws.com", - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cleanrooms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "cloud9": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloud9-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloud9-fips.ca-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "cloud9-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "cloud9-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "cloud9-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "cloud9-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "cloud9-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloud9-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloud9-fips.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloud9-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloud9-fips.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloud9-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloud9-fips.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloud9-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloud9-fips.us-west-2.api.aws", - }, - }, - }, - "cloudcontrolapi": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.ca-west-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.eu-west-3.api.aws", - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "cloudcontrolapi-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "cloudcontrolapi-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-west-2.api.aws", - }, - }, - }, - "clouddirectory": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "cloudformation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudformation-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "cloudformation-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudformation-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "cloudformation-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudformation-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "cloudformation-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudformation-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "cloudformation-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "cloudfront": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "cloudfront.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cloudhsm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "cloudhsmv2": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "cloudhsm", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "cloudsearch": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "cloudtrail": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "cloudtrail-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "cloudtrail-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "cloudtrail-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "cloudtrail-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudtrail-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudtrail-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudtrail-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudtrail-fips.us-west-2.amazonaws.com", - }, - }, - }, - "cloudtrail-data": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "codeartifact": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "codebuild": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codebuild-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "codebuild-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codebuild-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "codebuild-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codebuild-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "codebuild-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codebuild-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "codebuild-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "codecatalyst": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "codecatalyst.global.api.aws", - }, - }, - }, - "codecommit": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codecommit-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "codecommit-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "codecommit-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codecommit-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "codecommit-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codecommit-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "codecommit-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codecommit-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "codecommit-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codecommit-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "codecommit-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "codedeploy": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codedeploy-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "codedeploy-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codedeploy-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "codedeploy-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codedeploy-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "codedeploy-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codedeploy-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "codedeploy-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "codeguru-reviewer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "codepipeline": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codepipeline-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "codepipeline-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "codepipeline-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "codepipeline-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "codepipeline-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "codepipeline-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codepipeline-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codepipeline-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codepipeline-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codepipeline-fips.us-west-2.amazonaws.com", - }, - }, - }, - "codestar": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "codestar-connections": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "codestar-notifications": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "cognito-identity": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "cognito-identity-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "cognito-identity-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "cognito-identity-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "cognito-identity-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-identity-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-identity-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-identity-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-identity-fips.us-west-2.amazonaws.com", - }, - }, - }, - "cognito-idp": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "cognito-idp-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "cognito-idp-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "cognito-idp-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "cognito-idp-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-idp-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-idp-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-idp-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-idp-fips.us-west-2.amazonaws.com", - }, - }, - }, - "cognito-sync": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "comprehend": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "comprehend-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "comprehend-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "comprehend-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehend-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehend-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehend-fips.us-west-2.amazonaws.com", - }, - }, - }, - "comprehendmedical": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehendmedical-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "comprehendmedical-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "comprehendmedical-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "comprehendmedical-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "comprehendmedical-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehendmedical-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehendmedical-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehendmedical-fips.us-west-2.amazonaws.com", - }, - }, - }, - "compute-optimizer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "compute-optimizer.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "compute-optimizer.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "compute-optimizer.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "compute-optimizer.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "compute-optimizer.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "compute-optimizer.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "compute-optimizer.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "compute-optimizer.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "compute-optimizer.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "compute-optimizer.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "compute-optimizer.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "compute-optimizer.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "compute-optimizer.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "compute-optimizer.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "compute-optimizer.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "compute-optimizer.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "compute-optimizer.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "compute-optimizer.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "compute-optimizer.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "compute-optimizer.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "compute-optimizer.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "compute-optimizer.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "compute-optimizer.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "compute-optimizer.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "compute-optimizer.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "compute-optimizer.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "compute-optimizer.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "compute-optimizer.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "config": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "config-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "config-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "config-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "config-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "config-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "config-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "config-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "config-fips.us-west-2.amazonaws.com", - }, - }, - }, - "connect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "connect-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "connect-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "connect-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "connect-fips.us-west-2.amazonaws.com", - }, - }, - }, - "connect-campaigns": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "connect-campaigns-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "connect-campaigns-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "connect-campaigns-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "connect-campaigns-fips.us-west-2.amazonaws.com", - }, - }, - }, - "contact-lens": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "controltower": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "controltower-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "controltower-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "controltower-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - Hostname: "controltower-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "controltower-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "controltower-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "controltower-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "controltower-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "controltower-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "controltower-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "controltower-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "controltower-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "cost-optimization-hub": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "cost-optimization-hub.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cur": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "data-ats.iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Service: "iotdata", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iot-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "data.iot-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "iotdata", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "data.iot-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "iotdata", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "data.iot-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Service: "iotdata", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "data.iot-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "iotdata", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "data.iot-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Service: "iotdata", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iot-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iot-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iot-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iot-fips.us-west-2.amazonaws.com", - }, - }, - }, - "data.jobs.iot": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.jobs.iot-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "data.jobs.iot-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-west-2.amazonaws.com", - }, - }, - }, - "data.mediastore": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "databrew": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "databrew-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "databrew-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "databrew-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "databrew-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "databrew-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "databrew-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "databrew-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "databrew-fips.us-west-2.amazonaws.com", - }, - }, - }, - "dataexchange": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "datapipeline": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "datasync": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "datasync-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "datasync-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "datasync-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "datasync-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "datasync-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "datasync-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.us-west-2.amazonaws.com", - }, - }, - }, - "datazone": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "datazone.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "datazone.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "datazone.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "datazone.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "datazone.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "datazone.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "datazone.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "datazone.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "datazone.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "datazone.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "datazone.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "datazone.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datazone-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "datazone.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "datazone.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "datazone.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "datazone.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "datazone.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "datazone.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "datazone.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "datazone.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "datazone.eu-west-3.api.aws", - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "datazone.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "datazone.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "datazone.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "datazone.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "datazone.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datazone-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "datazone.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datazone-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "datazone.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "datazone.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datazone-fips.us-west-2.amazonaws.com", - }, - }, - }, - "dax": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "devicefarm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "devops-guru": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "devops-guru-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "devops-guru-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "devops-guru-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "devops-guru-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "devops-guru-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "devops-guru-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "devops-guru-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "devops-guru-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "devops-guru-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "devops-guru-fips.us-west-2.amazonaws.com", - }, - }, - }, - "directconnect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "directconnect-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "directconnect-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "directconnect-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "directconnect-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "directconnect-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "directconnect-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "directconnect-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "directconnect-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "directconnect-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "directconnect-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "directconnect-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "directconnect-fips.us-west-2.amazonaws.com", - }, - }, - }, - "discovery": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "dlm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "dms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "dms", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dms", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dms-fips", - }: endpoint{ - Hostname: "dms-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "dms-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "dms-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "dms-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "dms-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "docdb": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "rds.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "rds.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "rds.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "rds.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "rds.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "rds.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "rds.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "rds.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "rds.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "rds.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "rds.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "rds.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "rds.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "rds.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "drs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "drs-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "drs-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "drs-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "drs-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "drs-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "drs-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "drs-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "drs-fips.us-west-2.amazonaws.com", - }, - }, - }, - "ds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ds-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ds-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "ds-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "ds-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ds-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ds-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ds-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ds-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ds-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ds-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ds-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ds-fips.us-west-2.amazonaws.com", - }, - }, - }, - "dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "dynamodb-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - Hostname: "dynamodb-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "local", - }: endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "dynamodb-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "dynamodb-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "dynamodb-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "dynamodb-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "ebs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ebs-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ebs-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "ebs-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "ebs-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ebs-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ebs-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ebs-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ebs-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ebs-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ebs-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ebs-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ebs-fips.us-west-2.amazonaws.com", - }, - }, - }, - "ec2": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "ec2.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ec2-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ec2-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "ec2.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "ec2-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "ec2-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ec2-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ec2-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ec2-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ec2-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "ec2.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "ec2.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ec2-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "ec2.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ec2-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ec2-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "ec2.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ec2-fips.us-west-2.amazonaws.com", - }, - }, - }, - "ecs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ecs-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ecs-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ecs-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ecs-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecs-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecs-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecs-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecs-fips.us-west-2.amazonaws.com", - }, - }, - }, - "edge.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "eks": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.eks.{region}.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "fips.eks.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "fips.eks.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "fips.eks.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "fips.eks.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.eks.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.eks.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.eks.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.eks.us-west-2.amazonaws.com", - }, - }, - }, - "eks-auth": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "eks-auth.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "eks-auth.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "eks-auth.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "eks-auth.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "eks-auth.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "eks-auth.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "eks-auth.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "eks-auth.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "eks-auth.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "eks-auth.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "eks-auth.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "eks-auth.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "eks-auth.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "eks-auth.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "eks-auth.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "eks-auth.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "eks-auth.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "eks-auth.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "eks-auth.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "eks-auth.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "eks-auth.eu-west-3.api.aws", - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "eks-auth.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "eks-auth.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "eks-auth.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "eks-auth.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "eks-auth.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "eks-auth.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "eks-auth.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "eks-auth.us-west-2.api.aws", - }, - }, - }, - "elasticache": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "elasticache-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticache-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "elasticache-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticache-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "elasticache-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticache-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "elasticache-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticache-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "elasticache-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "elasticbeanstalk": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "elasticbeanstalk-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "elasticbeanstalk-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "elasticbeanstalk-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "elasticbeanstalk-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticbeanstalk-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticbeanstalk-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticbeanstalk-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticbeanstalk-fips.us-west-2.amazonaws.com", - }, - }, - }, - "elasticfilesystem": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.af-south-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-east-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-northeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-northeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-northeast-3.amazonaws.com", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-south-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-south-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-southeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-southeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-southeast-3.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-southeast-4.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-central-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-north-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-south-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-south-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-west-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-west-3.amazonaws.com", - }, - endpointKey{ - Region: "fips-af-south-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-east-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-2", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-3", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-south-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-south-2", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-2", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-3", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-4", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-central-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-central-2", - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-north-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-south-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-south-2", - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-2", - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-3", - }: endpoint{ - Hostname: "elasticfilesystem-fips.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-il-central-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-me-central-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-me-south-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-sa-east-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.il-central-1.amazonaws.com", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.me-central-1.amazonaws.com", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.me-south-1.amazonaws.com", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.sa-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-west-2.amazonaws.com", - }, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "elasticloadbalancing-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "elasticloadbalancing-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "elasticloadbalancing-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "elasticloadbalancing-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticloadbalancing-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticloadbalancing-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticloadbalancing-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticloadbalancing-fips.us-west-2.amazonaws.com", - }, - }, - }, - "elasticmapreduce": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SSLCommonName: "{region}.{service}.{dnsSuffix}", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "elasticmapreduce-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "elasticmapreduce-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "elasticmapreduce-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "elasticmapreduce-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "elasticmapreduce-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "elasticmapreduce-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce-fips.us-east-1.amazonaws.com", - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "elasticmapreduce.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce-fips.us-west-2.amazonaws.com", - }, - }, - }, - "elastictranscoder": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "email": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "email-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "email-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "email-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "email-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "email-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "email-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "email-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "email-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "email-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "email-fips.us-west-2.amazonaws.com", - }, - }, - }, - "emr-containers": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-containers-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "emr-containers-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "emr-containers-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "emr-containers-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "emr-containers-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "emr-containers-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-containers-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-containers-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-containers-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-containers-fips.us-west-2.amazonaws.com", - }, - }, - }, - "emr-serverless": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-serverless-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "emr-serverless-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "emr-serverless-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "emr-serverless-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "emr-serverless-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "emr-serverless-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-serverless-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-serverless-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-serverless-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-serverless-fips.us-west-2.amazonaws.com", - }, - }, - }, - "entitlement.marketplace": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "es": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.eu-west-3.api.aws", - }, - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "es-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "es-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "es-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "es-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "es-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "es-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "es-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "es-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "es-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "events": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "events-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "events-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "events-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "events-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "events-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "events-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "events-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "events-fips.us-west-2.amazonaws.com", - }, - }, - }, - "evidently": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "evidently.ap-northeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "evidently.ap-southeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "evidently.ap-southeast-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "evidently.eu-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "evidently.eu-north-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "evidently.eu-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "evidently.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "evidently.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "evidently.us-west-2.amazonaws.com", - }, - }, - }, - "finspace": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "finspace-api": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "firehose": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "firehose-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "firehose-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "firehose-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "firehose-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "firehose-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "firehose-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "firehose-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "firehose-fips.us-west-2.amazonaws.com", - }, - }, - }, - "fms": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.af-south-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.ap-east-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.ap-northeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.ap-northeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.ap-south-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.ap-southeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.ap-southeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.eu-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.eu-south-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.eu-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.eu-west-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.eu-west-3.amazonaws.com", - }, - endpointKey{ - Region: "fips-af-south-1", - }: endpoint{ - Hostname: "fms-fips.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-east-1", - }: endpoint{ - Hostname: "fms-fips.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-1", - }: endpoint{ - Hostname: "fms-fips.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-2", - }: endpoint{ - Hostname: "fms-fips.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-south-1", - }: endpoint{ - Hostname: "fms-fips.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-1", - }: endpoint{ - Hostname: "fms-fips.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-2", - }: endpoint{ - Hostname: "fms-fips.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "fms-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "fms-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-central-1", - }: endpoint{ - Hostname: "fms-fips.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-south-1", - }: endpoint{ - Hostname: "fms-fips.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-1", - }: endpoint{ - Hostname: "fms-fips.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-2", - }: endpoint{ - Hostname: "fms-fips.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-3", - }: endpoint{ - Hostname: "fms-fips.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-me-south-1", - }: endpoint{ - Hostname: "fms-fips.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-sa-east-1", - }: endpoint{ - Hostname: "fms-fips.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "fms-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "fms-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "fms-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "fms-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.me-south-1.amazonaws.com", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.sa-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.us-west-2.amazonaws.com", - }, - }, - }, - "forecast": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "forecast-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "forecast-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "forecast-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "forecast-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "forecast-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "forecast-fips.us-west-2.amazonaws.com", - }, - }, - }, - "forecastquery": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "forecastquery-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "forecastquery-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "forecastquery-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "forecastquery-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "forecastquery-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "forecastquery-fips.us-west-2.amazonaws.com", - }, - }, - }, - "frauddetector": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "fsx": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "fsx-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "fsx-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-prod-ca-central-1", - }: endpoint{ - Hostname: "fsx-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-prod-ca-west-1", - }: endpoint{ - Hostname: "fsx-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-prod-us-east-1", - }: endpoint{ - Hostname: "fsx-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-prod-us-east-2", - }: endpoint{ - Hostname: "fsx-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-prod-us-west-1", - }: endpoint{ - Hostname: "fsx-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-prod-us-west-2", - }: endpoint{ - Hostname: "fsx-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "fsx-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "fsx-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "fsx-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "fsx-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "prod-ca-central-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-ca-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-east-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-west-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-west-2.amazonaws.com", - }, - }, - }, - "gamelift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "geo": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glacier-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "glacier-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "glacier-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "glacier-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "glacier-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "glacier-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glacier-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glacier-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glacier-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glacier-fips.us-west-2.amazonaws.com", - }, - }, - }, - "globalaccelerator": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "globalaccelerator-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "glue": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "glue-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "glue-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "glue-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "glue-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glue-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glue-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glue-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glue-fips.us-west-2.amazonaws.com", - }, - }, - }, - "grafana": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "grafana.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "grafana.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "grafana.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "grafana.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "grafana.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "grafana.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "grafana.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "grafana.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "grafana.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "grafana.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "greengrass": service{ - IsRegionalized: boxedTrue, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "greengrass-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "greengrass-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "greengrass-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "greengrass-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "greengrass-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "greengrass-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "greengrass-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "greengrass-fips.us-west-2.amazonaws.com", - }, - }, - }, - "groundstation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "groundstation-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "groundstation-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "groundstation-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "groundstation-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "groundstation-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "groundstation-fips.us-west-2.amazonaws.com", - }, - }, - }, - "guardduty": service{ - IsRegionalized: boxedTrue, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "guardduty-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "guardduty-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "guardduty-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "guardduty-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "guardduty-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "guardduty-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "guardduty-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "guardduty-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "health": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SSLCommonName: "health.us-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "global.health.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "health-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "health-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "healthlake": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "iam.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "aws-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iam-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "aws-global-fips", - }: endpoint{ - Hostname: "iam-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "iam", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "iam", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iam-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "iam-fips", - }: endpoint{ - Hostname: "iam-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "identity-chime": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "identity-chime-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "identity-chime-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "identitystore": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "importexport": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "importexport.amazonaws.com", - SignatureVersions: []string{"v2", "v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - Service: "IngestionService", - }, - }, - }, - }, - "ingest.timestream": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "ingest-fips-us-east-1", - }: endpoint{ - Hostname: "ingest.timestream-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ingest-fips-us-east-2", - }: endpoint{ - Hostname: "ingest.timestream-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ingest-fips-us-west-2", - }: endpoint{ - Hostname: "ingest.timestream-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ingest-us-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ingest-us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ingest.timestream-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ingest-us-east-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ingest-us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ingest.timestream-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ingest-us-west-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ingest-us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ingest.timestream-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "inspector": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "inspector-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "inspector-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "inspector-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "inspector-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector-fips.us-west-2.amazonaws.com", - }, - }, - }, - "inspector2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "inspector2-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "inspector2-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "inspector2-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "inspector2-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector2-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector2-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector2-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector2-fips.us-west-2.amazonaws.com", - }, - }, - }, - "internetmonitor": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "internetmonitor.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "internetmonitor.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "internetmonitor.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "internetmonitor.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "internetmonitor.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "internetmonitor.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "internetmonitor.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "internetmonitor.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "internetmonitor.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "internetmonitor.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "internetmonitor.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "internetmonitor.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "internetmonitor-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "internetmonitor.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "internetmonitor.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "internetmonitor.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "internetmonitor.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "internetmonitor.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "internetmonitor.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "internetmonitor.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "internetmonitor.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "internetmonitor.eu-west-3.api.aws", - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "internetmonitor.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "internetmonitor.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "internetmonitor.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "internetmonitor.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "internetmonitor.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "internetmonitor-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "internetmonitor.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "internetmonitor-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "internetmonitor.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "internetmonitor-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "internetmonitor.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "internetmonitor-fips.us-west-2.amazonaws.com", - }, - }, - }, - "iot": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iot-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "iot-fips.ca-central-1.amazonaws.com", - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "iot-fips.us-east-1.amazonaws.com", - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "iot-fips.us-east-2.amazonaws.com", - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "iot-fips.us-west-1.amazonaws.com", - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "iot-fips.us-west-2.amazonaws.com", - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iot-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iot-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iot-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iot-fips.us-west-2.amazonaws.com", - }, - }, - }, - "iotanalytics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "iotevents": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotevents-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "iotevents-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "iotevents-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "iotevents-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "iotevents-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotevents-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotevents-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotevents-fips.us-west-2.amazonaws.com", - }, - }, - }, - "ioteventsdata": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "data.iotevents.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "data.iotevents.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "data.iotevents.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "data.iotevents.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "data.iotevents.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "data.iotevents.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iotevents-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "data.iotevents.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "data.iotevents.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "data.iotevents.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "data.iotevents-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "data.iotevents-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "data.iotevents-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "data.iotevents-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "data.iotevents.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iotevents-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "data.iotevents.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iotevents-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "data.iotevents.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iotevents-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "iotfleetwise": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "iotsecuredtunneling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-west-2.amazonaws.com", - }, - }, - }, - "iotsitewise": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotsitewise-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "iotsitewise-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "iotsitewise-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "iotsitewise-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "iotsitewise-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotsitewise-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotsitewise-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotsitewise-fips.us-west-2.amazonaws.com", - }, - }, - }, - "iotthingsgraph": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "iotthingsgraph", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "iottwinmaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "api-ap-northeast-1", - }: endpoint{ - Hostname: "api.iottwinmaker.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "api-ap-northeast-2", - }: endpoint{ - Hostname: "api.iottwinmaker.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "api-ap-south-1", - }: endpoint{ - Hostname: "api.iottwinmaker.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "api-ap-southeast-1", - }: endpoint{ - Hostname: "api.iottwinmaker.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "api-ap-southeast-2", - }: endpoint{ - Hostname: "api.iottwinmaker.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "api-eu-central-1", - }: endpoint{ - Hostname: "api.iottwinmaker.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "api-eu-west-1", - }: endpoint{ - Hostname: "api.iottwinmaker.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "api-us-east-1", - }: endpoint{ - Hostname: "api.iottwinmaker.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "api-us-west-2", - }: endpoint{ - Hostname: "api.iottwinmaker.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "data-ap-northeast-1", - }: endpoint{ - Hostname: "data.iottwinmaker.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "data-ap-northeast-2", - }: endpoint{ - Hostname: "data.iottwinmaker.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "data-ap-south-1", - }: endpoint{ - Hostname: "data.iottwinmaker.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "data-ap-southeast-1", - }: endpoint{ - Hostname: "data.iottwinmaker.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "data-ap-southeast-2", - }: endpoint{ - Hostname: "data.iottwinmaker.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "data-eu-central-1", - }: endpoint{ - Hostname: "data.iottwinmaker.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "data-eu-west-1", - }: endpoint{ - Hostname: "data.iottwinmaker.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "data-us-east-1", - }: endpoint{ - Hostname: "data.iottwinmaker.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "data-us-west-2", - }: endpoint{ - Hostname: "data.iottwinmaker.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "fips-api-us-east-1", - }: endpoint{ - Hostname: "api.iottwinmaker-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "fips-api-us-west-2", - }: endpoint{ - Hostname: "api.iottwinmaker-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "fips-data-us-east-1", - }: endpoint{ - Hostname: "data.iottwinmaker-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "fips-data-us-west-2", - }: endpoint{ - Hostname: "data.iottwinmaker-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "iottwinmaker-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "iottwinmaker-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iottwinmaker-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iottwinmaker-fips.us-west-2.amazonaws.com", - }, - }, - }, - "iotwireless": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "api.iotwireless.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "api.iotwireless.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "api.iotwireless.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "api.iotwireless.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "api.iotwireless.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "ivs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "ivschat": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "ivsrealtime": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "kafka": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kafka-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kafka-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "kafka-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "kafka-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "kafka-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "kafka-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "kafka-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "kafka-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kafka-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kafka-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kafka-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kafka-fips.us-west-2.amazonaws.com", - }, - }, - }, - "kafkaconnect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "kendra": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "kendra-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "kendra-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "kendra-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "kendra-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-fips.us-west-2.amazonaws.com", - }, - }, - }, - "kendra-ranking": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "kendra-ranking.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "kendra-ranking.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "kendra-ranking.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "kendra-ranking.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "kendra-ranking.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "kendra-ranking.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "kendra-ranking.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "kendra-ranking.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "kendra-ranking.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "kendra-ranking.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "kendra-ranking.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "kendra-ranking.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-ranking-fips.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "kendra-ranking.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "kendra-ranking.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "kendra-ranking.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "kendra-ranking.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "kendra-ranking.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "kendra-ranking.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "kendra-ranking.eu-west-3.api.aws", - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "kendra-ranking.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "kendra-ranking.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "kendra-ranking.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "kendra-ranking.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "kendra-ranking.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-ranking-fips.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "kendra-ranking.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-ranking-fips.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "kendra-ranking.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "kendra-ranking.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-ranking-fips.us-west-2.api.aws", - }, - }, - }, - "kinesis": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "kinesis-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "kinesis-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "kinesis-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "kinesis-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kinesis-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kinesis-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kinesis-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kinesis-fips.us-west-2.amazonaws.com", - }, - }, - }, - "kinesisanalytics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "kinesisvideo": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "kms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ProdFips", - }: endpoint{ - Hostname: "kms-fips.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.af-south-1.amazonaws.com", - }, - endpointKey{ - Region: "af-south-1-fips", - }: endpoint{ - Hostname: "kms-fips.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-east-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-east-1-fips", - }: endpoint{ - Hostname: "kms-fips.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-northeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-1-fips", - }: endpoint{ - Hostname: "kms-fips.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-northeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-2-fips", - }: endpoint{ - Hostname: "kms-fips.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-northeast-3.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-3-fips", - }: endpoint{ - Hostname: "kms-fips.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-south-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-south-1-fips", - }: endpoint{ - Hostname: "kms-fips.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-south-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-south-2-fips", - }: endpoint{ - Hostname: "kms-fips.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-southeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-1-fips", - }: endpoint{ - Hostname: "kms-fips.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-southeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-2-fips", - }: endpoint{ - Hostname: "kms-fips.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-southeast-3.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-3-fips", - }: endpoint{ - Hostname: "kms-fips.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ap-southeast-4.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-4-fips", - }: endpoint{ - Hostname: "kms-fips.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "kms-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - Hostname: "kms-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.eu-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1-fips", - }: endpoint{ - Hostname: "kms-fips.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.eu-central-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-2-fips", - }: endpoint{ - Hostname: "kms-fips.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.eu-north-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-north-1-fips", - }: endpoint{ - Hostname: "kms-fips.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.eu-south-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-south-1-fips", - }: endpoint{ - Hostname: "kms-fips.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.eu-south-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-south-2-fips", - }: endpoint{ - Hostname: "kms-fips.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.eu-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-1-fips", - }: endpoint{ - Hostname: "kms-fips.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.eu-west-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-2-fips", - }: endpoint{ - Hostname: "kms-fips.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.eu-west-3.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-3-fips", - }: endpoint{ - Hostname: "kms-fips.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.il-central-1.amazonaws.com", - }, - endpointKey{ - Region: "il-central-1-fips", - }: endpoint{ - Hostname: "kms-fips.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.me-central-1.amazonaws.com", - }, - endpointKey{ - Region: "me-central-1-fips", - }: endpoint{ - Hostname: "kms-fips.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.me-south-1.amazonaws.com", - }, - endpointKey{ - Region: "me-south-1-fips", - }: endpoint{ - Hostname: "kms-fips.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.sa-east-1.amazonaws.com", - }, - endpointKey{ - Region: "sa-east-1-fips", - }: endpoint{ - Hostname: "kms-fips.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "kms-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "kms-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "kms-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "kms-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "lakeformation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "lakeformation-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "lakeformation-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "lakeformation-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "lakeformation-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lakeformation-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lakeformation-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lakeformation-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lakeformation-fips.us-west-2.amazonaws.com", - }, - }, - }, - "lambda": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.eu-west-3.api.aws", - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "lambda-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "lambda-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "lambda-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "lambda-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lambda-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lambda-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lambda-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lambda-fips.us-west-2.amazonaws.com", - }, - }, - }, - "license-manager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "license-manager-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "license-manager-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "license-manager-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "license-manager-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-fips.us-west-2.amazonaws.com", - }, - }, - }, - "license-manager-linux-subscriptions": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "license-manager-linux-subscriptions-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "license-manager-linux-subscriptions-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "license-manager-linux-subscriptions-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "license-manager-linux-subscriptions-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-linux-subscriptions-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-linux-subscriptions-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-linux-subscriptions-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-linux-subscriptions-fips.us-west-2.amazonaws.com", - }, - }, - }, - "license-manager-user-subscriptions": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "license-manager-user-subscriptions-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "license-manager-user-subscriptions-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "license-manager-user-subscriptions-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "license-manager-user-subscriptions-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-user-subscriptions-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-user-subscriptions-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-user-subscriptions-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-user-subscriptions-fips.us-west-2.amazonaws.com", - }, - }, - }, - "lightsail": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "logs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "logs-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.ca-west-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "logs-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.eu-west-3.api.aws", - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "logs-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "logs-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "logs-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "logs-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "logs-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "logs-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "logs-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "logs-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "logs-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "logs.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "logs-fips.us-west-2.amazonaws.com", - }, - }, - }, - "lookoutequipment": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "lookoutmetrics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "lookoutvision": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "m2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{}, - }, - }, - "machinelearning": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "macie2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "macie2-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "macie2-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "macie2-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "macie2-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "macie2-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "macie2-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "macie2-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "macie2-fips.us-west-2.amazonaws.com", - }, - }, - }, - "managedblockchain": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "managedblockchain-query": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "marketplacecommerceanalytics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "media-pipelines-chime": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "media-pipelines-chime-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "media-pipelines-chime-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "media-pipelines-chime-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "media-pipelines-chime-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "mediaconnect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "mediaconvert": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mediaconvert-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "mediaconvert-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "mediaconvert-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "mediaconvert-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "mediaconvert-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "mediaconvert-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mediaconvert-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mediaconvert-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mediaconvert-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mediaconvert-fips.us-west-2.amazonaws.com", - }, - }, - }, - "medialive": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "medialive-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "medialive-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "medialive-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "medialive-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "medialive-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "medialive-fips.us-west-2.amazonaws.com", - }, - }, - }, - "mediapackage": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "mediapackage-vod": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "mediapackagev2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "mediastore": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "meetings-chime": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "meetings-chime-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "meetings-chime-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "meetings-chime-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "meetings-chime-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "meetings-chime-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "meetings-chime-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "memory-db": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "memory-db-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "messaging-chime": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "messaging-chime-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "messaging-chime-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "metering.marketplace": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "metrics.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "mgh": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "mgn": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "mgn-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "mgn-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "mgn-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "mgn-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mgn-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mgn-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mgn-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mgn-fips.us-west-2.amazonaws.com", - }, - }, - }, - "migrationhub-orchestrator": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "migrationhub-strategy": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "mobileanalytics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "models-v2-lex": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "models.lex": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "models-fips.lex.{region}.{dnsSuffix}", - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "models-fips.lex.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "models-fips.lex.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "models-fips.lex.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "models-fips.lex.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "monitoring": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "monitoring-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "monitoring-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "monitoring-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "monitoring-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "monitoring-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "monitoring-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "monitoring-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "monitoring-fips.us-west-2.amazonaws.com", - }, - }, - }, - "mq": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "mq-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "mq-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "mq-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "mq-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mq-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mq-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mq-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mq-fips.us-west-2.amazonaws.com", - }, - }, - }, - "mturk-requester": service{ - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "sandbox", - }: endpoint{ - Hostname: "mturk-requester-sandbox.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "neptune": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "rds.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "rds.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "rds.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "rds.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "rds.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "rds.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "rds.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "rds.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "rds.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "rds.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "rds.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "rds.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "rds.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "rds.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "rds.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "rds.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "rds.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "rds.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "network-firewall": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "network-firewall-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "network-firewall-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "network-firewall-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "network-firewall-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "network-firewall-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "network-firewall-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "network-firewall-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "network-firewall-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "network-firewall-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "network-firewall-fips.us-west-2.amazonaws.com", - }, - }, - }, - "networkmanager": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "networkmanager.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "aws-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "networkmanager-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "fips-aws-global", - }: endpoint{ - Hostname: "networkmanager-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "nimble": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "oam": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "oidc": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "oidc.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "oidc.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "oidc.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "oidc.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "oidc.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "oidc.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "oidc.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "oidc.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "oidc.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "oidc.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "oidc.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "oidc.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "oidc.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "oidc.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "oidc.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "oidc.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "oidc.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "oidc.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "oidc.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "oidc.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "oidc.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "oidc.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "oidc.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "oidc.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "oidc.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "oidc.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "oidc.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "oidc.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "oidc.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "omics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "omics.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "omics.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "omics.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "omics.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "omics-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "omics-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "omics.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "omics.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "omics-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "omics.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "omics-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "opsworks": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "opsworks-cm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "organizations": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "organizations.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "aws-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "organizations-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "fips-aws-global", - }: endpoint{ - Hostname: "organizations-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "osis": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "outposts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "outposts-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "outposts-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "outposts-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "outposts-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "outposts-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "outposts-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "outposts-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "outposts-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "outposts-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "outposts-fips.us-west-2.amazonaws.com", - }, - }, - }, - "participant.connect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "participant.connect-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "participant.connect-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "participant.connect-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "participant.connect-fips.us-west-2.amazonaws.com", - }, - }, - }, - "personalize": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "pi": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.af-south-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-east-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-northeast-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-northeast-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-northeast-3.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-south-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-south-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-southeast-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-southeast-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-southeast-3.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ap-southeast-4.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ca-central-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pi-fips.ca-central-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "pi-fips.ca-central-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.ca-west-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pi-fips.ca-west-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "pi-fips.ca-west-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.eu-central-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.eu-central-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.eu-north-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.eu-south-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.eu-south-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.eu-west-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.eu-west-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.eu-west-3.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "pi-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "pi-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "pi-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "pi-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "pi-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "pi-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.il-central-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.me-central-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.me-south-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.sa-east-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.us-east-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pi-fips.us-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "pi-fips.us-east-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.us-east-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pi-fips.us-east-2.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "pi-fips.us-east-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.us-west-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pi-fips.us-west-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "pi-fips.us-west-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.us-west-2.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pi-fips.us-west-2.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "pi-fips.us-west-2.api.aws", - Protocols: []string{"https"}, - }, - }, - }, - "pinpoint": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "mobiletargeting", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "pinpoint.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pinpoint-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "pinpoint-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "pinpoint-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "pinpoint-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "pinpoint-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "pinpoint.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pinpoint-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "pinpoint.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pinpoint-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "pinpoint.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pinpoint-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "pipes": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "polly": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "polly-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "polly-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "polly-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "polly-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "polly-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "polly-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "polly-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "polly-fips.us-west-2.amazonaws.com", - }, - }, - }, - "portal.sso": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "portal.sso.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "portal.sso.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "portal.sso.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "portal.sso.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "portal.sso.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "portal.sso.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "portal.sso.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "portal.sso.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "portal.sso.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "portal.sso.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "portal.sso.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "portal.sso.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "portal.sso.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "portal.sso.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "portal.sso.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "portal.sso.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "portal.sso.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "portal.sso.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "portal.sso.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "portal.sso.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "portal.sso.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "portal.sso.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "portal.sso.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "portal.sso.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "portal.sso.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "portal.sso.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "portal.sso.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "portal.sso.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "portal.sso.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "private-networks": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "profile": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "profile-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "profile-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "profile-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "profile-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "profile-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "profile-fips.us-west-2.amazonaws.com", - }, - }, - }, - "projects.iot1click": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "proton": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "qbusiness": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "qbusiness.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "qbusiness.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "qbusiness.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "qbusiness.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "qbusiness.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "qbusiness.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "qbusiness.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "qbusiness.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "qbusiness.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "qbusiness.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "qbusiness.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "qbusiness.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "qbusiness.ca-west-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "qbusiness.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "qbusiness.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "qbusiness.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "qbusiness.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "qbusiness.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "qbusiness.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "qbusiness.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "qbusiness.eu-west-3.api.aws", - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "qbusiness.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "qbusiness.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "qbusiness.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "qbusiness.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "qbusiness.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "qbusiness.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "qbusiness.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "qbusiness.us-west-2.api.aws", - }, - }, - }, - "qldb": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "qldb-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "qldb-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "qldb-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "qldb-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "qldb-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "qldb-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "qldb-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "qldb-fips.us-west-2.amazonaws.com", - }, - }, - }, - "quicksight": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "api", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "ram": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ram-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ram-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "ram-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "ram-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ram-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ram-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ram-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ram-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ram-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ram-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ram-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ram-fips.us-west-2.amazonaws.com", - }, - }, - }, - "rbin": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "rbin-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "rbin-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "rbin-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "rbin-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "rbin-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "rbin-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-west-2.amazonaws.com", - }, - }, - }, - "rds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "rds-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - Hostname: "rds-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "rds-fips.ca-central-1", - }: endpoint{ - Hostname: "rds-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds-fips.ca-west-1", - }: endpoint{ - Hostname: "rds-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds-fips.us-east-1", - }: endpoint{ - Hostname: "rds-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds-fips.us-east-2", - }: endpoint{ - Hostname: "rds-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds-fips.us-west-1", - }: endpoint{ - Hostname: "rds-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds-fips.us-west-2", - }: endpoint{ - Hostname: "rds-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.ca-central-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.ca-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-east-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-west-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - SSLCommonName: "{service}.{dnsSuffix}", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.us-east-1.amazonaws.com", - SSLCommonName: "{service}.{dnsSuffix}", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "rds-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "rds-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "rds-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "rds-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "rds-data": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "rds-data-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "rds-data-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "rds-data-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "rds-data-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-data-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-data-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-data-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds-data-fips.us-west-2.amazonaws.com", - }, - }, - }, - "redshift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "redshift-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "redshift-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "redshift-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "redshift-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "redshift-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "redshift-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-fips.us-west-2.amazonaws.com", - }, - }, - }, - "redshift-serverless": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-serverless-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "redshift-serverless-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "redshift-serverless-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "redshift-serverless-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "redshift-serverless-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "redshift-serverless-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-serverless-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-serverless-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-serverless-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "redshift-serverless-fips.us-west-2.amazonaws.com", - }, - }, - }, - "rekognition": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "rekognition-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "rekognition-fips.ca-central-1", - }: endpoint{ - Hostname: "rekognition-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition-fips.us-east-1", - }: endpoint{ - Hostname: "rekognition-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition-fips.us-east-2", - }: endpoint{ - Hostname: "rekognition-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition-fips.us-west-1", - }: endpoint{ - Hostname: "rekognition-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition-fips.us-west-2", - }: endpoint{ - Hostname: "rekognition-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.ca-central-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-east-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-west-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "rekognition-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "rekognition-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "rekognition-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "rekognition-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "resiliencehub": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "resource-explorer-2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "resource-groups": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "resource-groups-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "resource-groups-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "resource-groups-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "resource-groups-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "resource-groups-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "resource-groups-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "resource-groups-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "resource-groups-fips.us-west-2.amazonaws.com", - }, - }, - }, - "robomaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "rolesanywhere": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "rolesanywhere-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "rolesanywhere-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "rolesanywhere-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "rolesanywhere-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rolesanywhere-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rolesanywhere-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rolesanywhere-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rolesanywhere-fips.us-west-2.amazonaws.com", - }, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "route53.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "aws-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "route53-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "fips-aws-global", - }: endpoint{ - Hostname: "route53-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "route53-recovery-control-config": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "route53-recovery-control-config.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "route53domains": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - }, - }, - "route53resolver": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "rum": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "runtime-v2-lex": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "runtime.lex": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.lex.{region}.{dnsSuffix}", - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.lex.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "runtime-fips.lex.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.lex.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "runtime-fips.lex.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "runtime.sagemaker": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.sagemaker.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.sagemaker.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "runtime-fips.sagemaker.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.sagemaker.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "runtime-fips.sagemaker.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.sagemaker.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "runtime-fips.sagemaker.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.sagemaker.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "runtime-fips.sagemaker.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "s3": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedTrue, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - defaultKey{ - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "{service}-fips.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.af-south-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-east-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "s3.ap-northeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-northeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-northeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-northeast-3.amazonaws.com", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-south-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-south-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "s3.ap-southeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-southeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "s3.ap-southeast-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-southeast-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-southeast-3.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ap-southeast-4.amazonaws.com", - }, - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "s3.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.eu-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.eu-central-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.eu-north-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.eu-south-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.eu-south-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "s3.eu-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.eu-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.eu-west-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.eu-west-3.amazonaws.com", - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "s3-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "s3-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "s3-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "s3-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "s3-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "s3-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.il-central-1.amazonaws.com", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.me-central-1.amazonaws.com", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.me-south-1.amazonaws.com", - }, - endpointKey{ - Region: "s3-external-1", - }: endpoint{ - Hostname: "s3-external-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "s3.sa-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.sa-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "s3.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "s3.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "s3.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - }, - }, - "s3-control": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - defaultKey{ - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "{service}-fips.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "s3-control.af-south-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.af-south-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "s3-control.ap-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "s3-control.ap-northeast-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-northeast-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "s3-control.ap-northeast-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-northeast-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "s3-control.ap-northeast-3.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-northeast-3.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "s3-control.ap-south-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-south-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "s3-control.ap-south-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-south-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "s3-control.ap-southeast-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-southeast-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "s3-control.ap-southeast-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-southeast-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "s3-control.ap-southeast-3.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-southeast-3.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "s3-control.ap-southeast-4.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ap-southeast-4.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "s3-control.ca-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ca-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.ca-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.ca-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.ca-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "s3-control.ca-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.ca-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.ca-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.ca-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.ca-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "s3-control.eu-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.eu-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "s3-control.eu-central-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.eu-central-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "s3-control.eu-north-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.eu-north-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "s3-control.eu-south-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.eu-south-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "s3-control.eu-south-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.eu-south-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "s3-control.eu-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.eu-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "s3-control.eu-west-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.eu-west-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "s3-control.eu-west-3.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.eu-west-3.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "s3-control.il-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.il-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "s3-control.me-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.me-central-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "s3-control.me-south-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.me-south-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "s3-control.sa-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.sa-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "s3-control.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "s3-control.us-east-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-east-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-east-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-east-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-east-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "s3-control.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "s3-control.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "s3-outposts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - }, - }, - "sagemaker-geospatial": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "savingsplans": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "savingsplans.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "scheduler": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "schemas": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "sdb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"v2"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "sdb.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "secretsmanager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - - Deprecated: boxedTrue, - }, - }, - }, - "securityhub": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "securityhub-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "securityhub-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "securityhub-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "securityhub-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securityhub-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securityhub-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securityhub-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securityhub-fips.us-west-2.amazonaws.com", - }, - }, - }, - "securitylake": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "securitylake-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "securitylake-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "securitylake-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "securitylake-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securitylake-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securitylake-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securitylake-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securitylake-fips.us-west-2.amazonaws.com", - }, - }, - }, - "serverlessrepo": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "serverlessrepo-fips.us-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "serverlessrepo-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "serverlessrepo-fips.us-east-2.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "serverlessrepo-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "serverlessrepo-fips.us-west-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "serverlessrepo-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "serverlessrepo-fips.us-west-2.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "serverlessrepo-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "servicecatalog": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "servicecatalog-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "servicecatalog-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "servicecatalog-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "servicecatalog-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "servicecatalog-appregistry": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-appregistry-fips.us-west-2.amazonaws.com", - }, - }, - }, - "servicediscovery": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "af-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-east-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-northeast-1.api.aws", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-northeast-3.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-south-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ap-southeast-4.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.ca-west-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.ca-west-1.api.aws", - }, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.eu-central-2.api.aws", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.eu-north-1.api.aws", - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.eu-south-1.api.aws", - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.eu-south-2.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.eu-west-3.api.aws", - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.il-central-1.api.aws", - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.me-central-1.api.aws", - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.me-south-1.api.aws", - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.sa-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "servicequotas": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "session.qldb": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "session.qldb-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "session.qldb-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "session.qldb-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "session.qldb-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "session.qldb-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "session.qldb-fips.us-west-2.amazonaws.com", - }, - }, - }, - "shield": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SSLCommonName: "shield.us-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "shield.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "aws-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "shield-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "fips-aws-global", - }: endpoint{ - Hostname: "shield-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "signer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "signer-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "signer-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "signer-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "signer-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-verification-us-east-1", - }: endpoint{ - Hostname: "verification.signer-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "fips-verification-us-east-2", - }: endpoint{ - Hostname: "verification.signer-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "fips-verification-us-west-1", - }: endpoint{ - Hostname: "verification.signer-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "fips-verification-us-west-2", - }: endpoint{ - Hostname: "verification.signer-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "signer-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "signer-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "signer-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "signer-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "verification-af-south-1", - }: endpoint{ - Hostname: "verification.signer.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "verification-ap-east-1", - }: endpoint{ - Hostname: "verification.signer.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "verification-ap-northeast-1", - }: endpoint{ - Hostname: "verification.signer.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "verification-ap-northeast-2", - }: endpoint{ - Hostname: "verification.signer.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "verification-ap-south-1", - }: endpoint{ - Hostname: "verification.signer.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "verification-ap-southeast-1", - }: endpoint{ - Hostname: "verification.signer.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "verification-ap-southeast-2", - }: endpoint{ - Hostname: "verification.signer.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "verification-ca-central-1", - }: endpoint{ - Hostname: "verification.signer.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "verification-eu-central-1", - }: endpoint{ - Hostname: "verification.signer.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "verification-eu-north-1", - }: endpoint{ - Hostname: "verification.signer.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "verification-eu-south-1", - }: endpoint{ - Hostname: "verification.signer.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "verification-eu-west-1", - }: endpoint{ - Hostname: "verification.signer.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "verification-eu-west-2", - }: endpoint{ - Hostname: "verification.signer.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "verification-eu-west-3", - }: endpoint{ - Hostname: "verification.signer.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "verification-me-south-1", - }: endpoint{ - Hostname: "verification.signer.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "verification-sa-east-1", - }: endpoint{ - Hostname: "verification.signer.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "verification-us-east-1", - }: endpoint{ - Hostname: "verification.signer.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "verification-us-east-2", - }: endpoint{ - Hostname: "verification.signer.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "verification-us-west-1", - }: endpoint{ - Hostname: "verification.signer.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "verification-us-west-2", - }: endpoint{ - Hostname: "verification.signer.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "simspaceweaver": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "sms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "sms-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-fips.us-west-2.amazonaws.com", - }, - }, - }, - "sms-voice": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-voice-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "sms-voice-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "sms-voice-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "sms-voice-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "sms-voice-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "sms-voice-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-voice-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-voice-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-voice-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-voice-fips.us-west-2.amazonaws.com", - }, - }, - }, - "snowball": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.ap-northeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.ap-northeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.ap-northeast-3.amazonaws.com", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.ap-south-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.ap-southeast-1.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.ap-southeast-2.amazonaws.com", - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.eu-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.eu-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.eu-west-2.amazonaws.com", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.eu-west-3.amazonaws.com", - }, - endpointKey{ - Region: "fips-ap-northeast-1", - }: endpoint{ - Hostname: "snowball-fips.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-2", - }: endpoint{ - Hostname: "snowball-fips.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-3", - }: endpoint{ - Hostname: "snowball-fips.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-south-1", - }: endpoint{ - Hostname: "snowball-fips.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-1", - }: endpoint{ - Hostname: "snowball-fips.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-2", - }: endpoint{ - Hostname: "snowball-fips.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "snowball-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-central-1", - }: endpoint{ - Hostname: "snowball-fips.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-1", - }: endpoint{ - Hostname: "snowball-fips.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-2", - }: endpoint{ - Hostname: "snowball-fips.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-3", - }: endpoint{ - Hostname: "snowball-fips.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-sa-east-1", - }: endpoint{ - Hostname: "snowball-fips.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "snowball-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "snowball-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "snowball-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "snowball-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.sa-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.us-west-2.amazonaws.com", - }, - }, - }, - "sns": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sns-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "sns-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "sns-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "sns-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "sns-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "sns-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sns-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sns-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sns-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sns-fips.us-west-2.amazonaws.com", - }, - }, - }, - "sqs": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "sqs-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "sqs-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "sqs-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "sqs-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - SSLCommonName: "queue.{dnsSuffix}", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sqs-fips.us-east-1.amazonaws.com", - SSLCommonName: "queue.{dnsSuffix}", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sqs-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sqs-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sqs-fips.us-west-2.amazonaws.com", - }, - }, - }, - "ssm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "ssm-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "ssm-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ssm-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ssm-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ssm-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ssm-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-fips.us-west-2.amazonaws.com", - }, - }, - }, - "ssm-contacts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ssm-contacts-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ssm-contacts-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ssm-contacts-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ssm-contacts-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-contacts-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-contacts-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-contacts-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-contacts-fips.us-west-2.amazonaws.com", - }, - }, - }, - "ssm-incidents": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-incidents-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "ssm-incidents-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ssm-incidents-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ssm-incidents-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ssm-incidents-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ssm-incidents-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-incidents-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-incidents-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-incidents-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-incidents-fips.us-west-2.amazonaws.com", - }, - }, - }, - "ssm-sap": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-sap-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "ssm-sap-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "ssm-sap-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "ssm-sap-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "ssm-sap-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "ssm-sap-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-sap-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-sap-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-sap-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm-sap-fips.us-west-2.amazonaws.com", - }, - }, - }, - "sso": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "states": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "states-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "states-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "states-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "states-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-west-2.amazonaws.com", - }, - }, - }, - "storagegateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "storagegateway-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1-fips", - }: endpoint{ - Hostname: "storagegateway-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "streams.dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "local", - }: endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "sts": service{ - PartitionEndpoint: "aws-global", - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "sts.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sts-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "sts-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sts-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "sts-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sts-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "sts-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sts-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "sts-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "support": service{ - PartitionEndpoint: "aws-global", - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "support.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "supportapp": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "swf": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "swf-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "swf-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "swf-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "swf-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "swf-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "swf-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "swf-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "swf-fips.us-west-2.amazonaws.com", - }, - }, - }, - "synthetics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "synthetics-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "synthetics-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "synthetics-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "synthetics-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "synthetics-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "synthetics-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "synthetics-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "synthetics-fips.us-west-2.amazonaws.com", - }, - }, - }, - "tagging": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "tax": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "tax.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "textract": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.ap-northeast-2.api.aws", - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.ap-south-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.ap-southeast-1.api.aws", - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.ap-southeast-2.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.ca-central-1.api.aws", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "textract-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "textract-fips.ca-central-1.api.aws", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.eu-central-1.api.aws", - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.eu-west-1.api.aws", - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.eu-west-2.api.aws", - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.eu-west-3.api.aws", - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "textract-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "textract-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "textract-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "textract-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "textract-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "textract-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "textract-fips.us-east-1.api.aws", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "textract-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "textract-fips.us-east-2.api.aws", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "textract-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "textract-fips.us-west-1.api.aws", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.us-west-2.api.aws", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "textract-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "textract-fips.us-west-2.api.aws", - }, - }, - }, - "thinclient": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "tnb": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "transcribe": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "fips.transcribe.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "fips.transcribe.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "fips.transcribe.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "fips.transcribe.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "fips.transcribe.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.us-west-2.amazonaws.com", - }, - }, - }, - "transcribestreaming": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "transcribestreaming-ca-central-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transcribestreaming-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-fips-ca-central-1", - }: endpoint{ - Hostname: "transcribestreaming-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-fips-us-east-1", - }: endpoint{ - Hostname: "transcribestreaming-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-fips-us-east-2", - }: endpoint{ - Hostname: "transcribestreaming-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-fips-us-west-2", - }: endpoint{ - Hostname: "transcribestreaming-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-us-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transcribestreaming-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-us-east-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transcribestreaming-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-us-west-2", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "transcribestreaming-us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transcribestreaming-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "transfer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transfer-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transfer-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "transfer-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "transfer-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "transfer-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "transfer-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "transfer-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "transfer-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transfer-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transfer-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transfer-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transfer-fips.us-west-2.amazonaws.com", - }, - }, - }, - "translate": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "translate-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "translate-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "translate-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2-fips", - }: endpoint{ - Hostname: "translate-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "translate-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1-fips", - }: endpoint{ - Hostname: "translate-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "translate-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "translate-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "verifiedpermissions": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "verifiedpermissions-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "verifiedpermissions-fips.ca-west-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "verifiedpermissions-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "verifiedpermissions-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-west-2.amazonaws.com", - }, - }, - }, - "voice-chime": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "voice-chime-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "ca-central-1-fips", - }: endpoint{ - Hostname: "voice-chime-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "voice-chime-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-1-fips", - }: endpoint{ - Hostname: "voice-chime-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "voice-chime-fips.us-west-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2-fips", - }: endpoint{ - Hostname: "voice-chime-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - }, - }, - "voiceid": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "voiceid-fips.ca-central-1.amazonaws.com", - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "voiceid-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "voiceid-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "voiceid-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "voiceid-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "voiceid-fips.us-west-2.amazonaws.com", - }, - }, - }, - "vpc-lattice": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "waf": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "aws", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "aws-fips", - }: endpoint{ - Hostname: "waf-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "aws-global", - }: endpoint{ - Hostname: "waf.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "aws-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "aws-global-fips", - }: endpoint{ - Hostname: "waf-fips.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "waf-regional": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "waf-regional.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "af-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "waf-regional.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "waf-regional.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "waf-regional.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "waf-regional.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "waf-regional.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "waf-regional.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-south-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "waf-regional.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "waf-regional.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "waf-regional.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "waf-regional.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "waf-regional.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "waf-regional.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "waf-regional.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-central-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "waf-regional.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-north-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "waf-regional.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "waf-regional.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-south-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "waf-regional.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "waf-regional.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "waf-regional.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "eu-west-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "fips-af-south-1", - }: endpoint{ - Hostname: "waf-regional-fips.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-east-1", - }: endpoint{ - Hostname: "waf-regional-fips.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-1", - }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-2", - }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-3", - }: endpoint{ - Hostname: "waf-regional-fips.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-south-1", - }: endpoint{ - Hostname: "waf-regional-fips.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-south-2", - }: endpoint{ - Hostname: "waf-regional-fips.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-1", - }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-2", - }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-3", - }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-4", - }: endpoint{ - Hostname: "waf-regional-fips.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "waf-regional-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-central-1", - }: endpoint{ - Hostname: "waf-regional-fips.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-central-2", - }: endpoint{ - Hostname: "waf-regional-fips.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-north-1", - }: endpoint{ - Hostname: "waf-regional-fips.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-south-1", - }: endpoint{ - Hostname: "waf-regional-fips.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-south-2", - }: endpoint{ - Hostname: "waf-regional-fips.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-1", - }: endpoint{ - Hostname: "waf-regional-fips.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-2", - }: endpoint{ - Hostname: "waf-regional-fips.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-3", - }: endpoint{ - Hostname: "waf-regional-fips.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-il-central-1", - }: endpoint{ - Hostname: "waf-regional-fips.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-me-central-1", - }: endpoint{ - Hostname: "waf-regional-fips.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-me-south-1", - }: endpoint{ - Hostname: "waf-regional-fips.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-sa-east-1", - }: endpoint{ - Hostname: "waf-regional-fips.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "waf-regional-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "waf-regional-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "waf-regional-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "waf-regional-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "waf-regional.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "il-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "waf-regional.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "waf-regional.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "me-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "waf-regional.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "waf-regional.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "waf-regional.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "waf-regional.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "waf-regional.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "wafv2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "wafv2.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "af-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "wafv2.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{ - Hostname: "wafv2.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{ - Hostname: "wafv2.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "wafv2.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-northeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - }, - endpointKey{ - Region: "ap-south-1", - }: endpoint{ - Hostname: "wafv2.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "wafv2.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-south-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{ - Hostname: "wafv2.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{ - Hostname: "wafv2.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "wafv2.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "wafv2.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ap-southeast-4", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - }, - endpointKey{ - Region: "ca-central-1", - }: endpoint{ - Hostname: "wafv2.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - }, - endpointKey{ - Region: "ca-west-1", - }: endpoint{ - Hostname: "wafv2.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "ca-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - }: endpoint{ - Hostname: "wafv2.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "wafv2.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-central-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - }, - endpointKey{ - Region: "eu-north-1", - }: endpoint{ - Hostname: "wafv2.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-north-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - }: endpoint{ - Hostname: "wafv2.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "wafv2.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-south-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - }, - endpointKey{ - Region: "eu-west-1", - }: endpoint{ - Hostname: "wafv2.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - }, - endpointKey{ - Region: "eu-west-2", - }: endpoint{ - Hostname: "wafv2.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - }, - endpointKey{ - Region: "eu-west-3", - }: endpoint{ - Hostname: "wafv2.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "eu-west-3", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - }, - endpointKey{ - Region: "fips-af-south-1", - }: endpoint{ - Hostname: "wafv2-fips.af-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "af-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-east-1", - }: endpoint{ - Hostname: "wafv2-fips.ap-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-1", - }: endpoint{ - Hostname: "wafv2-fips.ap-northeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-2", - }: endpoint{ - Hostname: "wafv2-fips.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-northeast-3", - }: endpoint{ - Hostname: "wafv2-fips.ap-northeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-south-1", - }: endpoint{ - Hostname: "wafv2-fips.ap-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-south-2", - }: endpoint{ - Hostname: "wafv2-fips.ap-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-south-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-1", - }: endpoint{ - Hostname: "wafv2-fips.ap-southeast-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-2", - }: endpoint{ - Hostname: "wafv2-fips.ap-southeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-3", - }: endpoint{ - Hostname: "wafv2-fips.ap-southeast-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ap-southeast-4", - }: endpoint{ - Hostname: "wafv2-fips.ap-southeast-4.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-southeast-4", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-central-1", - }: endpoint{ - Hostname: "wafv2-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-ca-west-1", - }: endpoint{ - Hostname: "wafv2-fips.ca-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ca-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-central-1", - }: endpoint{ - Hostname: "wafv2-fips.eu-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-central-2", - }: endpoint{ - Hostname: "wafv2-fips.eu-central-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-central-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-north-1", - }: endpoint{ - Hostname: "wafv2-fips.eu-north-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-north-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-south-1", - }: endpoint{ - Hostname: "wafv2-fips.eu-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-south-2", - }: endpoint{ - Hostname: "wafv2-fips.eu-south-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-south-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-1", - }: endpoint{ - Hostname: "wafv2-fips.eu-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-2", - }: endpoint{ - Hostname: "wafv2-fips.eu-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-eu-west-3", - }: endpoint{ - Hostname: "wafv2-fips.eu-west-3.amazonaws.com", - CredentialScope: credentialScope{ - Region: "eu-west-3", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-il-central-1", - }: endpoint{ - Hostname: "wafv2-fips.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-me-central-1", - }: endpoint{ - Hostname: "wafv2-fips.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-me-south-1", - }: endpoint{ - Hostname: "wafv2-fips.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-sa-east-1", - }: endpoint{ - Hostname: "wafv2-fips.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "wafv2-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "wafv2-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "wafv2-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "wafv2-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{ - Hostname: "wafv2.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "il-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.il-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "il-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "wafv2.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-central-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.me-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-central-1", - }, - }, - endpointKey{ - Region: "me-south-1", - }: endpoint{ - Hostname: "wafv2.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "me-south-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.me-south-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "me-south-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - }: endpoint{ - Hostname: "wafv2.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "sa-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.sa-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "sa-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{ - Hostname: "wafv2.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{ - Hostname: "wafv2.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{ - Hostname: "wafv2.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{ - Hostname: "wafv2.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "wellarchitected": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "wisdom": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "ui-ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ui-ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ui-ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ui-ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ui-ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ui-eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "ui-eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "ui-us-east-1", - }: endpoint{}, - endpointKey{ - Region: "ui-us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{}, - }, - }, - "workdocs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "workdocs-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "workdocs-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "workdocs-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "workdocs-fips.us-west-2.amazonaws.com", - }, - }, - }, - "workmail": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "workspaces": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "workspaces-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "workspaces-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "workspaces-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "workspaces-fips.us-west-2.amazonaws.com", - }, - }, - }, - "workspaces-web": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - }, - }, - "xray": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-east-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-south-1", - }: endpoint{}, - endpointKey{ - Region: "ap-south-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-1", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-2", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{}, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{}, - endpointKey{ - Region: "ca-central-1", - }: endpoint{}, - endpointKey{ - Region: "ca-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-1", - }: endpoint{}, - endpointKey{ - Region: "eu-central-2", - }: endpoint{}, - endpointKey{ - Region: "eu-north-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-1", - }: endpoint{}, - endpointKey{ - Region: "eu-south-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-1", - }: endpoint{}, - endpointKey{ - Region: "eu-west-2", - }: endpoint{}, - endpointKey{ - Region: "eu-west-3", - }: endpoint{}, - endpointKey{ - Region: "fips-us-east-1", - }: endpoint{ - Hostname: "xray-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-east-2", - }: endpoint{ - Hostname: "xray-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-1", - }: endpoint{ - Hostname: "xray-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-west-2", - }: endpoint{ - Hostname: "xray-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "il-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-central-1", - }: endpoint{}, - endpointKey{ - Region: "me-south-1", - }: endpoint{}, - endpointKey{ - Region: "sa-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "xray-fips.us-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-east-2", - }: endpoint{}, - endpointKey{ - Region: "us-east-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "xray-fips.us-east-2.amazonaws.com", - }, - endpointKey{ - Region: "us-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "xray-fips.us-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-west-2", - }: endpoint{}, - endpointKey{ - Region: "us-west-2", - Variant: fipsVariant, - }: endpoint{ - Hostname: "xray-fips.us-west-2.amazonaws.com", - }, - }, - }, - }, -} - -// AwsCnPartition returns the Resolver for AWS China. -func AwsCnPartition() Partition { - return awscnPartition.Partition() -} - -var awscnPartition = partition{ - ID: "aws-cn", - Name: "AWS China", - DNSSuffix: "amazonaws.com.cn", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^cn\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - DNSSuffix: "api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - Regions: regions{ - "cn-north-1": region{ - Description: "China (Beijing)", - }, - "cn-northwest-1": region{ - Description: "China (Ningxia)", - }, - }, - Services: services{ - "access-analyzer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "account": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "account.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "acm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "acm-pca": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "airflow": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "api.ecr": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "api.ecr.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "api.ecr.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "api.pricing": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "pricing", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "api.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "api.tunneling.iot": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "apigateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "appconfig": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "appconfigdata": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "application-autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "applicationinsights": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "appmesh": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "appmesh.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "appsync": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "arc-zonal-shift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "athena": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "autoscaling-plans": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "backup": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "batch": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "budgets": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "budgets.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "cassandra": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "ce": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "ce.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "cloudcontrolapi": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "cloudformation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "cloudfront": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "cloudfront.cn-northwest-1.amazonaws.com.cn", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "cloudtrail": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "codebuild": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "codecommit": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "codedeploy": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "codepipeline": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "cognito-identity": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "compute-optimizer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "compute-optimizer.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "compute-optimizer.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "config": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "cur": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "data-ats.iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Service: "iotdata", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "data.ats.iot.cn-north-1.amazonaws.com.cn", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "data.jobs.iot": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "databrew": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "datasync": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "datazone": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.amazonwebservices.com.cn", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.amazonwebservices.com.cn", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "datazone.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "datazone.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "dax": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "directconnect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "dlm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "dms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "docdb": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "rds.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "ds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "ebs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "ecs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "eks": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "eks-auth": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.amazonwebservices.com.cn", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.amazonwebservices.com.cn", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "eks-auth.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "eks-auth.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "elasticache": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "elasticbeanstalk": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "elasticfilesystem": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.cn-north-1.amazonaws.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.cn-northwest-1.amazonaws.com.cn", - }, - endpointKey{ - Region: "fips-cn-north-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-cn-northwest-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "elasticmapreduce": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "elasticmapreduce.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "elasticmapreduce.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "emr-containers": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "emr-serverless": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "entitlement.marketplace": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "entitlement-marketplace.cn-northwest-1.amazonaws.com.cn", - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "es": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "events": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "firehose": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "firehose.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "firehose.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "fms": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "fsx": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "gamelift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "glue": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "greengrass": service{ - IsRegionalized: boxedTrue, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "guardduty": service{ - IsRegionalized: boxedTrue, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "health": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SSLCommonName: "health.cn-northwest-1.amazonaws.com.cn", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "global.health.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "iam.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - }, - }, - "identitystore": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "inspector2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "internetmonitor": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.amazonwebservices.com.cn", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.amazonwebservices.com.cn", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "internetmonitor.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "internetmonitor.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "iot": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "iotanalytics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "iotevents": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "ioteventsdata": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "data.iotevents.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - }, - }, - "iotsecuredtunneling": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "iotsitewise": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "iottwinmaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "api-cn-north-1", - }: endpoint{ - Hostname: "api.iottwinmaker.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "data-cn-north-1", - }: endpoint{ - Hostname: "data.iottwinmaker.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - }, - }, - "kafka": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "kendra-ranking": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.amazonwebservices.com.cn", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.amazonwebservices.com.cn", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "kendra-ranking.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "kendra-ranking.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "kinesis": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "kinesisanalytics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "kinesisvideo": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "kms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "lakeformation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "lambda": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "license-manager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "license-manager-linux-subscriptions": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "logs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "mediaconvert": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "mediaconvert.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "memory-db": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "metrics.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "monitoring": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "mq": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "neptune": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "rds.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "rds.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "network-firewall": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "oam": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "oidc": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "oidc.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "oidc.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "organizations": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "organizations.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "personalize": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "pi": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.cn-north-1.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.cn-northwest-1.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - }, - }, - }, - "pipes": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "polly": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "portal.sso": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "portal.sso.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "portal.sso.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "qbusiness": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.amazonwebservices.com.cn", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.amazonwebservices.com.cn", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "qbusiness.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "qbusiness.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "quicksight": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "ram": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "rbin": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "rds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "redshift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "redshift-serverless": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "resource-groups": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "rolesanywhere": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "route53.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "route53resolver": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "runtime.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "s3": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com.cn", - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.cn-north-1.amazonaws.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.cn-northwest-1.amazonaws.com.cn", - }, - }, - }, - "s3-control": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "s3-control.cn-north-1.amazonaws.com.cn", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.cn-north-1.amazonaws.com.cn", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "s3-control.cn-northwest-1.amazonaws.com.cn", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.cn-northwest-1.amazonaws.com.cn", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "savingsplans": service{ - IsRegionalized: boxedTrue, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "savingsplans.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "savingsplans.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "schemas": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "secretsmanager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{}, - }, - }, - "securityhub": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "serverlessrepo": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - }, - }, - "servicecatalog": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "servicediscovery": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "servicequotas": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "signer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "verification-cn-north-1", - }: endpoint{ - Hostname: "verification.signer.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "verification-cn-northwest-1", - }: endpoint{ - Hostname: "verification.signer.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "sms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - }, - }, - "snowball": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.cn-north-1.amazonaws.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.cn-northwest-1.amazonaws.com.cn", - }, - endpointKey{ - Region: "fips-cn-north-1", - }: endpoint{ - Hostname: "snowball-fips.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-cn-northwest-1", - }: endpoint{ - Hostname: "snowball-fips.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "sns": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "sqs": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "ssm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "sso": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "states": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-north-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "states.cn-north-1.api.amazonwebservices.com.cn", - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "states.cn-northwest-1.api.amazonwebservices.com.cn", - }, - }, - }, - "storagegateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "sts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "support": service{ - PartitionEndpoint: "aws-cn-global", - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-cn-global", - }: endpoint{ - Hostname: "support.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - }, - }, - "swf": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "synthetics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "tagging": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "transcribe": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "cn.transcribe.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "cn.transcribe.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - "transcribestreaming": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "transfer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "waf-regional": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "waf-regional.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-north-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "waf-regional.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - endpointKey{ - Region: "fips-cn-north-1", - }: endpoint{ - Hostname: "waf-regional-fips.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-cn-northwest-1", - }: endpoint{ - Hostname: "waf-regional-fips.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "wafv2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{ - Hostname: "wafv2.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-north-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{ - Hostname: "wafv2.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - endpointKey{ - Region: "cn-northwest-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - }, - endpointKey{ - Region: "fips-cn-north-1", - }: endpoint{ - Hostname: "wafv2-fips.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-cn-northwest-1", - }: endpoint{ - Hostname: "wafv2-fips.cn-northwest-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-northwest-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "workspaces": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - "xray": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "cn-north-1", - }: endpoint{}, - endpointKey{ - Region: "cn-northwest-1", - }: endpoint{}, - }, - }, - }, -} - -// AwsUsGovPartition returns the Resolver for AWS GovCloud (US). -func AwsUsGovPartition() Partition { - return awsusgovPartition.Partition() -} - -var awsusgovPartition = partition{ - ID: "aws-us-gov", - Name: "AWS GovCloud (US)", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^us\\-gov\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - Regions: regions{ - "us-gov-east-1": region{ - Description: "AWS GovCloud (US-East)", - }, - "us-gov-west-1": region{ - Description: "AWS GovCloud (US-West)", - }, - }, - Services: services{ - "access-analyzer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "access-analyzer.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "access-analyzer.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "access-analyzer.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "access-analyzer.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "access-analyzer.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "access-analyzer.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "acm": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "acm.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "acm.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "acm-pca": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "acm-pca.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "acm-pca.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "acm-pca.us-gov-west-1.amazonaws.com", - }, - }, - }, - "api.detective": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.detective-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "api.detective-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.detective-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "api.detective-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "api.ecr": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "dkr-us-gov-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-gov-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dkr-us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-dkr-us-gov-east-1", - }: endpoint{ - Hostname: "ecr-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-dkr-us-gov-west-1", - }: endpoint{ - Hostname: "ecr-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "ecr-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "ecr-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "api.ecr.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "api.ecr.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecr-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "api.sagemaker": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "api-fips.sagemaker.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api-fips.sagemaker.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "api-fips.sagemaker.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1-fips-secondary", - }: endpoint{ - Hostname: "api.sagemaker.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1-secondary", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1-secondary", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.sagemaker.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "api.tunneling.iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "apigateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "appconfig": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "appconfig.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "appconfig.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appconfig.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appconfig.us-gov-west-1.amazonaws.com", - }, - }, - }, - "appconfigdata": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "appconfigdata.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "appconfigdata.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appconfigdata.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appconfigdata.us-gov-west-1.amazonaws.com", - }, - }, - }, - "application-autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "application-autoscaling", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", - Protocols: []string{"http", "https"}, - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - - Deprecated: boxedTrue, - }, - }, - }, - "applicationinsights": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "applicationinsights.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "applicationinsights.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "appstream2": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Service: "appstream", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "appstream2-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appstream2-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "appstream2-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "appstream2-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "appstream2-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "arc-zonal-shift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "athena": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "athena-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "athena-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "athena-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "athena-fips.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "athena.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "athena-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "athena-fips.us-gov-west-1.api.aws", - }, - }, - }, - "autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "autoscaling-plans": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling-plans.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "autoscaling-plans.us-gov-east-1.amazonaws.com", - Protocols: []string{"http", "https"}, - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "autoscaling-plans.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "autoscaling-plans.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - - Deprecated: boxedTrue, - }, - }, - }, - "backup": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "backup-gateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "batch": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "batch.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "batch.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "batch.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "batch.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "batch.us-gov-west-1.amazonaws.com", - }, - }, - }, - "bedrock": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "bedrock-fips-us-gov-west-1", - }: endpoint{ - Hostname: "bedrock-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-fips-us-gov-west-1", - }: endpoint{ - Hostname: "bedrock-runtime-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "bedrock-runtime-us-gov-west-1", - }: endpoint{ - Hostname: "bedrock-runtime.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "bedrock-us-gov-west-1", - }: endpoint{ - Hostname: "bedrock.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "cassandra": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "cassandra.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cassandra.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "cassandra.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "cassandra.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cassandra.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "cassandra.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "cloudcontrolapi": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "cloudcontrolapi-fips.us-gov-west-1.api.aws", - }, - }, - }, - "clouddirectory": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "clouddirectory.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "clouddirectory.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "cloudformation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "cloudformation.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudformation.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "cloudformation.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "cloudformation.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudformation.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "cloudformation.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "cloudhsm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "cloudhsmv2": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "cloudhsm", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "cloudtrail": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudtrail.us-gov-west-1.amazonaws.com", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "cloudtrail.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "cloudtrail.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudtrail.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cloudtrail.us-gov-west-1.amazonaws.com", - }, - }, - }, - "codebuild": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codebuild-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "codebuild-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codebuild-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "codebuild-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "codecommit": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "codecommit-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codecommit-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "codecommit-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codecommit-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "codecommit-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "codedeploy": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codedeploy-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "codedeploy-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codedeploy-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "codedeploy-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "codepipeline": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "codepipeline-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "codepipeline-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codepipeline-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "codepipeline-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "codestar-connections": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - }, - }, - "cognito-identity": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "cognito-identity-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-identity-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "cognito-idp": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "cognito-idp-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "cognito-idp-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "comprehend": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "comprehend-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehend-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "comprehendmedical": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "comprehendmedical-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "comprehendmedical-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "compute-optimizer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "compute-optimizer-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "compute-optimizer-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "config": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "config.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "config.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "config.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "config.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "config.us-gov-west-1.amazonaws.com", - }, - }, - }, - "connect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "connect.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "connect.us-gov-west-1.amazonaws.com", - }, - }, - }, - "controltower": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "controltower-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "controltower-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "controltower-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "controltower-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "data-ats.iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Service: "iotdata", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "data.iot-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "iotdata", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "data.iot-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "iotdata", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iot-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iot-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "data.jobs.iot": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.jobs.iot-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "databrew": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "databrew.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "databrew.us-gov-west-1.amazonaws.com", - }, - }, - }, - "datasync": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "datasync-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "datasync-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "datazone": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "datazone.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "datazone.us-gov-west-1.api.aws", - }, - }, - }, - "directconnect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "directconnect-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "directconnect-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "directconnect-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "directconnect-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "dlm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dlm.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "dlm.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dlm.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "dlm.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "dms": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "dms", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dms", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dms-fips", - }: endpoint{ - Hostname: "dms.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "dms.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "dms.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "docdb": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "rds.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "drs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "drs-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "drs-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "drs-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "drs-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "ds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "ds-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "ds-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ds-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ds-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "dynamodb.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dynamodb.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "dynamodb.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "ebs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "ec2.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "ec2.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "ec2.us-gov-east-1.api.aws", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "ec2.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "ec2.us-gov-west-1.api.aws", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "ecs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "ecs-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "ecs-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecs-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ecs-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "eks": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "eks.{region}.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "eks.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "eks.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "eks.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "eks.us-gov-west-1.amazonaws.com", - }, - }, - }, - "eks-auth": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "eks-auth.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "eks-auth.us-gov-west-1.api.aws", - }, - }, - }, - "elasticache": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticache.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "elasticache.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticache.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "elasticache.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "elasticbeanstalk": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "elasticbeanstalk.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticbeanstalk.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "elasticbeanstalk.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "elasticbeanstalk.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticbeanstalk.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "elasticbeanstalk.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "elasticfilesystem": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticloadbalancing.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "elasticloadbalancing.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "elasticloadbalancing.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticloadbalancing.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticloadbalancing.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - }, - }, - "elasticmapreduce": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "elasticmapreduce.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "elasticmapreduce.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "elasticmapreduce.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "elasticmapreduce.us-gov-west-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce.us-gov-west-1.amazonaws.com", - Protocols: []string{"https"}, - }, - }, - }, - "email": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "email-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "email-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "email-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "email-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "emr-containers": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "emr-containers.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "emr-containers.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-containers.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-containers.us-gov-west-1.amazonaws.com", - }, - }, - }, - "emr-serverless": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "emr-serverless.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "emr-serverless.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-serverless.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "emr-serverless.us-gov-west-1.amazonaws.com", - }, - }, - }, - "es": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "es-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "es-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "es-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "aos.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "es-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "es-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "events": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "events.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "events.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "events.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "events.us-gov-west-1.amazonaws.com", - }, - }, - }, - "firehose": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "firehose-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "firehose-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "firehose-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "firehose-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "fms": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "fms-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "fms-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fms-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "fsx": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-prod-us-gov-east-1", - }: endpoint{ - Hostname: "fsx-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-prod-us-gov-west-1", - }: endpoint{ - Hostname: "fsx-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "fsx-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "fsx-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-gov-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-gov-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "geo": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "geo-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "geo-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "glacier": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "glacier.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "glacier.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glacier.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glacier.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - }, - }, - "glue": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "glue-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "glue-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "glue.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glue-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "glue-fips.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "glue.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "glue-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "glue-fips.us-gov-west-1.api.aws", - }, - }, - }, - "greengrass": service{ - IsRegionalized: boxedTrue, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "dataplane-us-gov-east-1", - }: endpoint{ - Hostname: "greengrass-ats.iot.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "dataplane-us-gov-west-1", - }: endpoint{ - Hostname: "greengrass-ats.iot.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "greengrass.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "greengrass.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "greengrass.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "greengrass.us-gov-west-1.amazonaws.com", - }, - }, - }, - "guardduty": service{ - IsRegionalized: boxedTrue, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "guardduty.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "guardduty.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "guardduty.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "guardduty.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "guardduty.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "health": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SSLCommonName: "health.us-gov-west-1.amazonaws.com", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-us-gov-global", - }: endpoint{ - Hostname: "global.health.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "health-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "health-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-us-gov-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-us-gov-global", - }: endpoint{ - Hostname: "iam.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "aws-us-gov-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iam.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "aws-us-gov-global-fips", - }: endpoint{ - Hostname: "iam.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "iam-govcloud", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "iam-govcloud", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iam.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "iam-govcloud-fips", - }: endpoint{ - Hostname: "iam.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "identitystore": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "identitystore.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "identitystore.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "identitystore.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "identitystore.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "identitystore.us-gov-west-1.amazonaws.com", - }, - }, - }, - "ingest.timestream": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ingest.timestream.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "ingest.timestream.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "inspector": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "inspector-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "inspector-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "inspector2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "inspector2-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "inspector2-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector2-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "inspector2-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "internetmonitor": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "internetmonitor.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "internetmonitor.us-gov-west-1.api.aws", - }, - }, - }, - "iot": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "iot-fips.us-gov-east-1.amazonaws.com", - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "iot-fips.us-gov-west-1.amazonaws.com", - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iot-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iot-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "iotevents": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "iotevents-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotevents-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "ioteventsdata": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "data.iotevents-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "data.iotevents.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "data.iotevents-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "iotsecuredtunneling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "api.tunneling.iot-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "iotsitewise": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "iotsitewise-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iotsitewise-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "iottwinmaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "api-us-gov-west-1", - }: endpoint{ - Hostname: "api.iottwinmaker.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "data-us-gov-west-1", - }: endpoint{ - Hostname: "data.iottwinmaker.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-api-us-gov-west-1", - }: endpoint{ - Hostname: "api.iottwinmaker-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-data-us-gov-west-1", - }: endpoint{ - Hostname: "data.iottwinmaker-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "iottwinmaker-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "iottwinmaker-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "kafka": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "kafka.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kafka.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "kafka.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "kafka.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kafka.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "kafka.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "kendra": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "kendra-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kendra-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "kendra-ranking": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "kendra-ranking.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "kendra-ranking.us-gov-west-1.api.aws", - }, - }, - }, - "kinesis": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "kinesis.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "kinesis.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "kinesis.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kinesis.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "kinesis.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kinesis.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "kinesisanalytics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "kinesisvideo": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "kinesisvideo-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "kinesisvideo-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "kinesisvideo-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kinesisvideo-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "kinesisvideo-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kinesisvideo-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "kms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ProdFips", - }: endpoint{ - Hostname: "kms-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "kms-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "kms-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "lakeformation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "lakeformation-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "lakeformation-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lakeformation.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lakeformation-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "lakeformation-fips.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lakeformation.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lakeformation-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "lakeformation-fips.us-gov-west-1.api.aws", - }, - }, - }, - "lambda": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "lambda-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "lambda-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lambda-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "lambda.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "lambda-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "license-manager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "license-manager-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "license-manager-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "license-manager-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "license-manager-linux-subscriptions": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "license-manager-user-subscriptions": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "logs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "logs.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "logs.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "logs.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "logs.us-gov-west-1.amazonaws.com", - }, - }, - }, - "m2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{}, - }, - }, - "managedblockchain": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "mediaconvert": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "mediaconvert.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mediaconvert.us-gov-west-1.amazonaws.com", - }, - }, - }, - "meetings-chime": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "meetings-chime-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "meetings-chime-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "meetings-chime-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "meetings-chime-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "metering.marketplace": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "metrics.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "mgn": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "mgn-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "mgn-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mgn-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mgn-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "models-v2-lex": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "models.lex": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "models-fips.lex.{region}.{dnsSuffix}", - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "models-fips.lex.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "models-fips.lex.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "monitoring": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "monitoring.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "monitoring.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "monitoring.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "monitoring.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "monitoring.us-gov-west-1.amazonaws.com", - }, - }, - }, - "mq": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "mq-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "mq-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mq-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "mq-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "neptune": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "rds.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "rds.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "network-firewall": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "network-firewall-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "network-firewall-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "network-firewall-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "network-firewall-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "networkmanager": service{ - PartitionEndpoint: "aws-us-gov-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-us-gov-global", - }: endpoint{ - Hostname: "networkmanager.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "aws-us-gov-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "networkmanager.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-aws-us-gov-global", - }: endpoint{ - Hostname: "networkmanager.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "oidc": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "oidc.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "oidc.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "organizations": service{ - PartitionEndpoint: "aws-us-gov-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-us-gov-global", - }: endpoint{ - Hostname: "organizations.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "aws-us-gov-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "organizations.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-aws-us-gov-global", - }: endpoint{ - Hostname: "organizations.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "outposts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "outposts.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "outposts.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "outposts.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "outposts.us-gov-west-1.amazonaws.com", - }, - }, - }, - "participant.connect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "participant.connect.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "participant.connect.us-gov-west-1.amazonaws.com", - }, - }, - }, - "pi": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "pi-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "pi-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.us-gov-east-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pi-fips.us-gov-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "pi-fips.us-gov-east-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "pi.us-gov-west-1.api.aws", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pi-fips.us-gov-west-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "pi-fips.us-gov-west-1.api.aws", - Protocols: []string{"https"}, - }, - }, - }, - "pinpoint": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "mobiletargeting", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "pinpoint-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "pinpoint.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "pinpoint-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "polly": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "polly-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "polly-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "portal.sso": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "portal.sso.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "portal.sso.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "qbusiness": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - DNSSuffix: "api.aws", - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "api.aws", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "qbusiness.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "qbusiness.us-gov-west-1.api.aws", - }, - }, - }, - "quicksight": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "api", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "ram": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "ram.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ram.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "ram.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "ram.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ram.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "ram.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "rbin": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "rbin-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "rbin-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "rds": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "rds.us-gov-east-1", - }: endpoint{ - Hostname: "rds.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-gov-west-1", - }: endpoint{ - Hostname: "rds.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "rds.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "rds.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "redshift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "redshift.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "redshift.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "rekognition": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "rekognition-fips.us-gov-west-1", - }: endpoint{ - Hostname: "rekognition-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-gov-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rekognition.us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rekognition-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "rekognition-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "resiliencehub": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "resiliencehub-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "resiliencehub-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "resiliencehub-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "resiliencehub-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "resource-groups": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "resource-groups.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "resource-groups.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "resource-groups.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "resource-groups.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "resource-groups.us-gov-west-1.amazonaws.com", - }, - }, - }, - "robomaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "rolesanywhere": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "rolesanywhere-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "rolesanywhere-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rolesanywhere-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rolesanywhere-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-us-gov-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-us-gov-global", - }: endpoint{ - Hostname: "route53.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "aws-us-gov-global", - Variant: fipsVariant, - }: endpoint{ - Hostname: "route53.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-aws-us-gov-global", - }: endpoint{ - Hostname: "route53.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "route53resolver": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "route53resolver.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "route53resolver.us-gov-east-1.amazonaws.com", - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "route53resolver.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "route53resolver.us-gov-west-1.amazonaws.com", - - Deprecated: boxedTrue, - }, - }, - }, - "runtime-v2-lex": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "runtime.lex": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.lex.{region}.{dnsSuffix}", - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime-fips.lex.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "runtime-fips.lex.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "runtime.sagemaker": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime.sagemaker.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "runtime.sagemaker.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "runtime.sagemaker.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "s3": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SignatureVersions: []string{"s3", "s3v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - defaultKey{ - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "{service}-fips.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "s3-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "s3-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "s3.us-gov-east-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.us-gov-east-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-gov-east-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "s3.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3.dualstack.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - }, - }, - "s3-control": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - defaultKey{ - Variant: dualStackVariant, - }: endpoint{ - Hostname: "{service}.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - defaultKey{ - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "{service}-fips.dualstack.{region}.{dnsSuffix}", - DNSSuffix: "amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "s3-control.us-gov-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-gov-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-gov-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-gov-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-gov-east-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "s3-control.us-gov-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-gov-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-gov-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-gov-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-gov-west-1.amazonaws.com", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "s3-outposts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - }, - }, - "secretsmanager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - - Deprecated: boxedTrue, - }, - }, - }, - "securityhub": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "securityhub-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "securityhub-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securityhub-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securityhub-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "securitylake": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securitylake.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "securitylake.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "securitylake.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "securitylake.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "serverlessrepo": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "serverlessrepo.us-gov-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "serverlessrepo.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "serverlessrepo.us-gov-west-1.amazonaws.com", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "serverlessrepo.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "servicecatalog": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "servicecatalog-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "servicecatalog-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "servicecatalog-appregistry": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicecatalog-appregistry.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "servicediscovery": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "servicediscovery", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "servicediscovery", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "servicediscovery-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "servicediscovery-fips.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "servicediscovery-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "servicequotas": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicequotas.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "servicequotas.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "servicequotas.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicequotas.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "servicequotas.us-gov-west-1.amazonaws.com", - }, - }, - }, - "signer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "signer-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "signer-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-verification-us-gov-east-1", - }: endpoint{ - Hostname: "verification.signer-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "fips-verification-us-gov-west-1", - }: endpoint{ - Hostname: "verification.signer-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "signer-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "signer-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "verification-us-gov-east-1", - }: endpoint{ - Hostname: "verification.signer.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "verification-us-gov-west-1", - }: endpoint{ - Hostname: "verification.signer.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "simspaceweaver": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "simspaceweaver.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "simspaceweaver.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "simspaceweaver.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "simspaceweaver.us-gov-west-1.amazonaws.com", - }, - }, - }, - "sms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "sms-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "sms-voice": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "sms-voice-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "sms-voice-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-voice-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sms-voice-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "snowball": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "snowball-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "snowball-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "snowball-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "sns": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "sns.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "sns.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sns.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sns.us-gov-west-1.amazonaws.com", - Protocols: []string{"https"}, - }, - }, - }, - "sqs": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "sqs.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "sqs.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "sqs.us-gov-west-1.amazonaws.com", - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "ssm": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "ssm.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "ssm.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "ssm.us-gov-west-1.amazonaws.com", - }, - }, - }, - "sso": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "sso.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sso.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "sso.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "sso.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sso.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "sso.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "states": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "states-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "states.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "states.us-gov-west-1.amazonaws.com", - }, - }, - }, - "storagegateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "streams.dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "streams.dynamodb.{region}.{dnsSuffix}", - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "streams.dynamodb.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "streams.dynamodb.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "streams.dynamodb.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "streams.dynamodb.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "sts": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "sts.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sts.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "sts.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "sts.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "sts.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "support": service{ - PartitionEndpoint: "aws-us-gov-global", - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-us-gov-global", - }: endpoint{ - Hostname: "support.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "support.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "support.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "swf": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "swf.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "swf.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1-fips", - }: endpoint{ - Hostname: "swf.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "swf.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "swf.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "swf.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "synthetics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "synthetics-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "synthetics-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "synthetics-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "synthetics-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "tagging": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "textract": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "textract-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "textract-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "textract-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "textract-fips.us-gov-east-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "textract.us-gov-west-1.api.aws", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "textract-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "textract-fips.us-gov-west-1.api.aws", - }, - }, - }, - "transcribe": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "fips.transcribe.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "fips.transcribe.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fips.transcribe.us-gov-west-1.amazonaws.com", - }, - }, - }, - "transcribestreaming": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "transfer": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "transfer-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "transfer-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transfer-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "transfer-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "translate": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "translate-fips.us-gov-west-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1-fips", - }: endpoint{ - Hostname: "translate-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "verifiedpermissions": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "verifiedpermissions-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "waf-regional": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "waf-regional-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "waf-regional-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "waf-regional.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "waf-regional.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "waf-regional-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "wafv2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "wafv2-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "wafv2-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{ - Hostname: "wafv2.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{ - Hostname: "wafv2.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "wafv2-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "wellarchitected": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - }, - }, - "workspaces": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "workspaces-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "workspaces-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "workspaces-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "workspaces-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - "xray": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-gov-east-1", - }: endpoint{ - Hostname: "xray-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-gov-west-1", - }: endpoint{ - Hostname: "xray-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-gov-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "xray-fips.us-gov-east-1.amazonaws.com", - }, - endpointKey{ - Region: "us-gov-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-gov-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "xray-fips.us-gov-west-1.amazonaws.com", - }, - }, - }, - }, -} - -// AwsIsoPartition returns the Resolver for AWS ISO (US). -func AwsIsoPartition() Partition { - return awsisoPartition.Partition() -} - -var awsisoPartition = partition{ - ID: "aws-iso", - Name: "AWS ISO (US)", - DNSSuffix: "c2s.ic.gov", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^us\\-iso\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - Regions: regions{ - "us-iso-east-1": region{ - Description: "US ISO East", - }, - "us-iso-west-1": region{ - Description: "US ISO WEST", - }, - }, - Services: services{ - "api.ecr": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Hostname: "api.ecr.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{ - Hostname: "api.ecr.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - }, - }, - }, - "api.pricing": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "pricing", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "api.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "apigateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "appconfig": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "appconfigdata": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "application-autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "arc-zonal-shift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "athena": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "autoscaling": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "cloudcontrolapi": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "cloudformation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "cloudtrail": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "codedeploy": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "comprehend": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "config": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "datapipeline": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "datasync": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-iso-east-1", - }: endpoint{ - Hostname: "datasync-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-iso-west-1", - }: endpoint{ - Hostname: "datasync-fips.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.us-iso-east-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "datasync-fips.us-iso-west-1.c2s.ic.gov", - }, - }, - }, - "directconnect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "dlm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "dms": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "dms", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dms", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dms-fips", - }: endpoint{ - Hostname: "dms.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.us-iso-east-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-east-1-fips", - }: endpoint{ - Hostname: "dms.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.us-iso-west-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-west-1-fips", - }: endpoint{ - Hostname: "dms.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "ds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "dynamodb": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "ebs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "ec2": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "ecs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "eks": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "elasticache": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "elasticfilesystem": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-iso-east-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-iso-west-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-iso-east-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-iso-west-1.c2s.ic.gov", - }, - }, - }, - "elasticloadbalancing": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "elasticmapreduce": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-iso-east-1", - }: endpoint{ - Hostname: "elasticmapreduce.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-iso-west-1", - }: endpoint{ - Hostname: "elasticmapreduce.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce.us-iso-east-1.c2s.ic.gov", - Protocols: []string{"https"}, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce.us-iso-west-1.c2s.ic.gov", - }, - }, - }, - "es": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "events": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "firehose": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "fsx": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-prod-us-iso-east-1", - }: endpoint{ - Hostname: "fsx-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-iso-east-1", - }: endpoint{ - Hostname: "fsx-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-iso-east-1", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "prod-us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "fsx-fips.us-iso-east-1.c2s.ic.gov", - }, - }, - }, - "glacier": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "glue": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "guardduty": service{ - IsRegionalized: boxedTrue, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "health": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-iso-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-iso-global", - }: endpoint{ - Hostname: "iam.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - }, - }, - "kinesis": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "kms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ProdFips", - }: endpoint{ - Hostname: "kms-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-iso-east-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-east-1-fips", - }: endpoint{ - Hostname: "kms-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-iso-west-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-west-1-fips", - }: endpoint{ - Hostname: "kms-fips.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "lambda": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "license-manager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "logs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "medialive": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "mediapackage": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "metrics.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "monitoring": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "outposts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "ram": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "rbin": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-iso-east-1", - }: endpoint{ - Hostname: "rbin-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-iso-west-1", - }: endpoint{ - Hostname: "rbin-fips.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-iso-east-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-iso-west-1.c2s.ic.gov", - }, - }, - }, - "rds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "rds.us-iso-east-1", - }: endpoint{ - Hostname: "rds.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "rds.us-iso-west-1", - }: endpoint{ - Hostname: "rds.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds.us-iso-east-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-east-1-fips", - }: endpoint{ - Hostname: "rds.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds.us-iso-west-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-west-1-fips", - }: endpoint{ - Hostname: "rds.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "redshift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Hostname: "redshift.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{ - Hostname: "redshift.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - }, - }, - }, - "resource-groups": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-iso-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-iso-global", - }: endpoint{ - Hostname: "route53.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - }, - }, - "route53resolver": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "runtime.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "s3": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-iso-east-1", - }: endpoint{ - Hostname: "s3-fips.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "fips-us-iso-west-1", - }: endpoint{ - Hostname: "s3-fips.us-iso-west-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-iso-east-1.c2s.ic.gov", - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.us-iso-east-1.c2s.ic.gov", - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-iso-west-1.c2s.ic.gov", - }, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.us-iso-west-1.c2s.ic.gov", - }, - }, - }, - "s3-control": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Hostname: "s3-control.us-iso-east-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - endpointKey{ - Region: "us-iso-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-iso-east-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-iso-east-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-iso-east-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - endpointKey{ - Region: "us-iso-east-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-iso-east-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{ - Hostname: "s3-control.us-iso-west-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - }, - endpointKey{ - Region: "us-iso-west-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-iso-west-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - }, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-iso-west-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - }, - endpointKey{ - Region: "us-iso-west-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-iso-west-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - }, - endpointKey{ - Region: "us-iso-west-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-iso-west-1.c2s.ic.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-iso-west-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "s3-outposts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-iso-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-east-1", - Variant: fipsVariant, - }: endpoint{}, - }, - }, - "secretsmanager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "snowball": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "sns": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "sqs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{ - Protocols: []string{"http", "https"}, - }, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "ssm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "states": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "sts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "support": service{ - PartitionEndpoint: "aws-iso-global", - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-iso-global", - }: endpoint{ - Hostname: "support.us-iso-east-1.c2s.ic.gov", - CredentialScope: credentialScope{ - Region: "us-iso-east-1", - }, - }, - }, - }, - "swf": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "synthetics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "tagging": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - "textract": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "transcribe": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "transcribestreaming": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "translate": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - }, - }, - "workspaces": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-iso-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-iso-west-1", - }: endpoint{}, - }, - }, - }, -} - -// AwsIsoBPartition returns the Resolver for AWS ISOB (US). -func AwsIsoBPartition() Partition { - return awsisobPartition.Partition() -} - -var awsisobPartition = partition{ - ID: "aws-iso-b", - Name: "AWS ISOB (US)", - DNSSuffix: "sc2s.sgov.gov", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^us\\-isob\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - Regions: regions{ - "us-isob-east-1": region{ - Description: "US ISOB East (Ohio)", - }, - }, - Services: services{ - "api.ecr": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{ - Hostname: "api.ecr.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - }, - }, - "api.pricing": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "pricing", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "api.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "apigateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "appconfig": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "appconfigdata": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "application-autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "arc-zonal-shift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "autoscaling": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "cloudcontrolapi": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "cloudformation": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "cloudtrail": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "codedeploy": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "config": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "directconnect": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "dlm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "dms": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{}, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.{region}.{dnsSuffix}", - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "dms", - }: endpoint{ - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dms", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "dms-fips", - }: endpoint{ - Hostname: "dms.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "dms.us-isob-east-1.sc2s.sgov.gov", - }, - endpointKey{ - Region: "us-isob-east-1-fips", - }: endpoint{ - Hostname: "dms.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "ds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "ebs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "ecs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "eks": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "elasticache": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "elasticfilesystem": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-isob-east-1", - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticfilesystem-fips.us-isob-east-1.sc2s.sgov.gov", - }, - }, - }, - "elasticloadbalancing": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{ - Protocols: []string{"https"}, - }, - }, - }, - "elasticmapreduce": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-isob-east-1", - }: endpoint{ - Hostname: "elasticmapreduce.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "elasticmapreduce.us-isob-east-1.sc2s.sgov.gov", - }, - }, - }, - "es": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "events": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "firehose": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "glacier": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "health": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-iso-b-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-iso-b-global", - }: endpoint{ - Hostname: "iam.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - }, - }, - "kinesis": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "kms": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "ProdFips", - }: endpoint{ - Hostname: "kms-fips.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "kms-fips.us-isob-east-1.sc2s.sgov.gov", - }, - endpointKey{ - Region: "us-isob-east-1-fips", - }: endpoint{ - Hostname: "kms-fips.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "lambda": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "license-manager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "logs": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "medialive": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "mediapackage": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "metering.marketplace": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "metrics.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "monitoring": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "outposts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "ram": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "rbin": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-isob-east-1", - }: endpoint{ - Hostname: "rbin-fips.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rbin-fips.us-isob-east-1.sc2s.sgov.gov", - }, - }, - }, - "rds": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "rds.us-isob-east-1", - }: endpoint{ - Hostname: "rds.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "rds.us-isob-east-1.sc2s.sgov.gov", - }, - endpointKey{ - Region: "us-isob-east-1-fips", - }: endpoint{ - Hostname: "rds.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "redshift": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{ - Hostname: "redshift.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - }, - }, - "resource-groups": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-iso-b-global", - IsRegionalized: boxedFalse, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-iso-b-global", - }: endpoint{ - Hostname: "route53.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - }, - }, - "route53resolver": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "runtime.sagemaker": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "s3": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-isob-east-1", - }: endpoint{ - Hostname: "s3-fips.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-fips.us-isob-east-1.sc2s.sgov.gov", - }, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-fips.dualstack.us-isob-east-1.sc2s.sgov.gov", - }, - }, - }, - "s3-control": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"https"}, - SignatureVersions: []string{"s3v4"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{ - Hostname: "s3-control.us-isob-east-1.sc2s.sgov.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - endpointKey{ - Region: "us-isob-east-1", - Variant: dualStackVariant, - }: endpoint{ - Hostname: "s3-control.dualstack.us-isob-east-1.sc2s.sgov.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "s3-control-fips.us-isob-east-1.sc2s.sgov.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant | dualStackVariant, - }: endpoint{ - Hostname: "s3-control-fips.dualstack.us-isob-east-1.sc2s.sgov.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - endpointKey{ - Region: "us-isob-east-1-fips", - }: endpoint{ - Hostname: "s3-control-fips.us-isob-east-1.sc2s.sgov.gov", - SignatureVersions: []string{"s3v4"}, - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "s3-outposts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips-us-isob-east-1", - }: endpoint{ - - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{}, - }, - }, - "secretsmanager": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "snowball": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "sns": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "sqs": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "ssm": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "states": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "storagegateway": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - endpointKey{ - Region: "us-isob-east-1", - Variant: fipsVariant, - }: endpoint{ - Hostname: "storagegateway-fips.us-isob-east-1.sc2s.sgov.gov", - }, - endpointKey{ - Region: "us-isob-east-1-fips", - }: endpoint{ - Hostname: "storagegateway-fips.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - Deprecated: boxedTrue, - }, - }, - }, - "streams.dynamodb": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - }, - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "sts": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "support": service{ - PartitionEndpoint: "aws-iso-b-global", - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "aws-iso-b-global", - }: endpoint{ - Hostname: "support.us-isob-east-1.sc2s.sgov.gov", - CredentialScope: credentialScope{ - Region: "us-isob-east-1", - }, - }, - }, - }, - "swf": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "synthetics": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "tagging": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - "workspaces": service{ - Endpoints: serviceEndpoints{ - endpointKey{ - Region: "us-isob-east-1", - }: endpoint{}, - }, - }, - }, -} - -// AwsIsoEPartition returns the Resolver for AWS ISOE (Europe). -func AwsIsoEPartition() Partition { - return awsisoePartition.Partition() -} - -var awsisoePartition = partition{ - ID: "aws-iso-e", - Name: "AWS ISOE (Europe)", - DNSSuffix: "cloud.adc-e.uk", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^eu\\-isoe\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - Regions: regions{ - "eu-isoe-west-1": region{ - Description: "EU ISOE West", - }, - }, - Services: services{}, -} - -// AwsIsoFPartition returns the Resolver for AWS ISOF. -func AwsIsoFPartition() Partition { - return awsisofPartition.Partition() -} - -var awsisofPartition = partition{ - ID: "aws-iso-f", - Name: "AWS ISOF", - DNSSuffix: "csp.hci.ic.gov", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^us\\-isof\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - defaultKey{ - Variant: fipsVariant, - }: endpoint{ - Hostname: "{service}-fips.{region}.{dnsSuffix}", - DNSSuffix: "csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - Regions: regions{}, - Services: services{}, -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/dep_service_ids.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/dep_service_ids.go deleted file mode 100644 index ca8fc828e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/dep_service_ids.go +++ /dev/null @@ -1,141 +0,0 @@ -package endpoints - -// Service identifiers -// -// Deprecated: Use client package's EndpointsID value instead of these -// ServiceIDs. These IDs are not maintained, and are out of date. -const ( - A4bServiceID = "a4b" // A4b. - AcmServiceID = "acm" // Acm. - AcmPcaServiceID = "acm-pca" // AcmPca. - ApiMediatailorServiceID = "api.mediatailor" // ApiMediatailor. - ApiPricingServiceID = "api.pricing" // ApiPricing. - ApiSagemakerServiceID = "api.sagemaker" // ApiSagemaker. - ApigatewayServiceID = "apigateway" // Apigateway. - ApplicationAutoscalingServiceID = "application-autoscaling" // ApplicationAutoscaling. - Appstream2ServiceID = "appstream2" // Appstream2. - AppsyncServiceID = "appsync" // Appsync. - AthenaServiceID = "athena" // Athena. - AutoscalingServiceID = "autoscaling" // Autoscaling. - AutoscalingPlansServiceID = "autoscaling-plans" // AutoscalingPlans. - BatchServiceID = "batch" // Batch. - BudgetsServiceID = "budgets" // Budgets. - CeServiceID = "ce" // Ce. - ChimeServiceID = "chime" // Chime. - Cloud9ServiceID = "cloud9" // Cloud9. - ClouddirectoryServiceID = "clouddirectory" // Clouddirectory. - CloudformationServiceID = "cloudformation" // Cloudformation. - CloudfrontServiceID = "cloudfront" // Cloudfront. - CloudhsmServiceID = "cloudhsm" // Cloudhsm. - Cloudhsmv2ServiceID = "cloudhsmv2" // Cloudhsmv2. - CloudsearchServiceID = "cloudsearch" // Cloudsearch. - CloudtrailServiceID = "cloudtrail" // Cloudtrail. - CodebuildServiceID = "codebuild" // Codebuild. - CodecommitServiceID = "codecommit" // Codecommit. - CodedeployServiceID = "codedeploy" // Codedeploy. - CodepipelineServiceID = "codepipeline" // Codepipeline. - CodestarServiceID = "codestar" // Codestar. - CognitoIdentityServiceID = "cognito-identity" // CognitoIdentity. - CognitoIdpServiceID = "cognito-idp" // CognitoIdp. - CognitoSyncServiceID = "cognito-sync" // CognitoSync. - ComprehendServiceID = "comprehend" // Comprehend. - ConfigServiceID = "config" // Config. - CurServiceID = "cur" // Cur. - DatapipelineServiceID = "datapipeline" // Datapipeline. - DaxServiceID = "dax" // Dax. - DevicefarmServiceID = "devicefarm" // Devicefarm. - DirectconnectServiceID = "directconnect" // Directconnect. - DiscoveryServiceID = "discovery" // Discovery. - DmsServiceID = "dms" // Dms. - DsServiceID = "ds" // Ds. - DynamodbServiceID = "dynamodb" // Dynamodb. - Ec2ServiceID = "ec2" // Ec2. - Ec2metadataServiceID = "ec2metadata" // Ec2metadata. - EcrServiceID = "ecr" // Ecr. - EcsServiceID = "ecs" // Ecs. - ElasticacheServiceID = "elasticache" // Elasticache. - ElasticbeanstalkServiceID = "elasticbeanstalk" // Elasticbeanstalk. - ElasticfilesystemServiceID = "elasticfilesystem" // Elasticfilesystem. - ElasticloadbalancingServiceID = "elasticloadbalancing" // Elasticloadbalancing. - ElasticmapreduceServiceID = "elasticmapreduce" // Elasticmapreduce. - ElastictranscoderServiceID = "elastictranscoder" // Elastictranscoder. - EmailServiceID = "email" // Email. - EntitlementMarketplaceServiceID = "entitlement.marketplace" // EntitlementMarketplace. - EsServiceID = "es" // Es. - EventsServiceID = "events" // Events. - FirehoseServiceID = "firehose" // Firehose. - FmsServiceID = "fms" // Fms. - GameliftServiceID = "gamelift" // Gamelift. - GlacierServiceID = "glacier" // Glacier. - GlueServiceID = "glue" // Glue. - GreengrassServiceID = "greengrass" // Greengrass. - GuarddutyServiceID = "guardduty" // Guardduty. - HealthServiceID = "health" // Health. - IamServiceID = "iam" // Iam. - ImportexportServiceID = "importexport" // Importexport. - InspectorServiceID = "inspector" // Inspector. - IotServiceID = "iot" // Iot. - IotanalyticsServiceID = "iotanalytics" // Iotanalytics. - KinesisServiceID = "kinesis" // Kinesis. - KinesisanalyticsServiceID = "kinesisanalytics" // Kinesisanalytics. - KinesisvideoServiceID = "kinesisvideo" // Kinesisvideo. - KmsServiceID = "kms" // Kms. - LambdaServiceID = "lambda" // Lambda. - LightsailServiceID = "lightsail" // Lightsail. - LogsServiceID = "logs" // Logs. - MachinelearningServiceID = "machinelearning" // Machinelearning. - MarketplacecommerceanalyticsServiceID = "marketplacecommerceanalytics" // Marketplacecommerceanalytics. - MediaconvertServiceID = "mediaconvert" // Mediaconvert. - MedialiveServiceID = "medialive" // Medialive. - MediapackageServiceID = "mediapackage" // Mediapackage. - MediastoreServiceID = "mediastore" // Mediastore. - MeteringMarketplaceServiceID = "metering.marketplace" // MeteringMarketplace. - MghServiceID = "mgh" // Mgh. - MobileanalyticsServiceID = "mobileanalytics" // Mobileanalytics. - ModelsLexServiceID = "models.lex" // ModelsLex. - MonitoringServiceID = "monitoring" // Monitoring. - MturkRequesterServiceID = "mturk-requester" // MturkRequester. - NeptuneServiceID = "neptune" // Neptune. - OpsworksServiceID = "opsworks" // Opsworks. - OpsworksCmServiceID = "opsworks-cm" // OpsworksCm. - OrganizationsServiceID = "organizations" // Organizations. - PinpointServiceID = "pinpoint" // Pinpoint. - PollyServiceID = "polly" // Polly. - RdsServiceID = "rds" // Rds. - RedshiftServiceID = "redshift" // Redshift. - RekognitionServiceID = "rekognition" // Rekognition. - ResourceGroupsServiceID = "resource-groups" // ResourceGroups. - Route53ServiceID = "route53" // Route53. - Route53domainsServiceID = "route53domains" // Route53domains. - RuntimeLexServiceID = "runtime.lex" // RuntimeLex. - RuntimeSagemakerServiceID = "runtime.sagemaker" // RuntimeSagemaker. - S3ServiceID = "s3" // S3. - S3ControlServiceID = "s3-control" // S3Control. - SagemakerServiceID = "api.sagemaker" // Sagemaker. - SdbServiceID = "sdb" // Sdb. - SecretsmanagerServiceID = "secretsmanager" // Secretsmanager. - ServerlessrepoServiceID = "serverlessrepo" // Serverlessrepo. - ServicecatalogServiceID = "servicecatalog" // Servicecatalog. - ServicediscoveryServiceID = "servicediscovery" // Servicediscovery. - ShieldServiceID = "shield" // Shield. - SmsServiceID = "sms" // Sms. - SnowballServiceID = "snowball" // Snowball. - SnsServiceID = "sns" // Sns. - SqsServiceID = "sqs" // Sqs. - SsmServiceID = "ssm" // Ssm. - StatesServiceID = "states" // States. - StoragegatewayServiceID = "storagegateway" // Storagegateway. - StreamsDynamodbServiceID = "streams.dynamodb" // StreamsDynamodb. - StsServiceID = "sts" // Sts. - SupportServiceID = "support" // Support. - SwfServiceID = "swf" // Swf. - TaggingServiceID = "tagging" // Tagging. - TransferServiceID = "transfer" // Transfer. - TranslateServiceID = "translate" // Translate. - WafServiceID = "waf" // Waf. - WafRegionalServiceID = "waf-regional" // WafRegional. - WorkdocsServiceID = "workdocs" // Workdocs. - WorkmailServiceID = "workmail" // Workmail. - WorkspacesServiceID = "workspaces" // Workspaces. - XrayServiceID = "xray" // Xray. -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go deleted file mode 100644 index 66dec6beb..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go +++ /dev/null @@ -1,65 +0,0 @@ -// Package endpoints provides the types and functionality for defining regions -// and endpoints, as well as querying those definitions. -// -// The SDK's Regions and Endpoints metadata is code generated into the endpoints -// package, and is accessible via the DefaultResolver function. This function -// returns a endpoint Resolver will search the metadata and build an associated -// endpoint if one is found. The default resolver will search all partitions -// known by the SDK. e.g AWS Standard (aws), AWS China (aws-cn), and -// AWS GovCloud (US) (aws-us-gov). -// . -// -// # Enumerating Regions and Endpoint Metadata -// -// Casting the Resolver returned by DefaultResolver to a EnumPartitions interface -// will allow you to get access to the list of underlying Partitions with the -// Partitions method. This is helpful if you want to limit the SDK's endpoint -// resolving to a single partition, or enumerate regions, services, and endpoints -// in the partition. -// -// resolver := endpoints.DefaultResolver() -// partitions := resolver.(endpoints.EnumPartitions).Partitions() -// -// for _, p := range partitions { -// fmt.Println("Regions for", p.ID()) -// for id, _ := range p.Regions() { -// fmt.Println("*", id) -// } -// -// fmt.Println("Services for", p.ID()) -// for id, _ := range p.Services() { -// fmt.Println("*", id) -// } -// } -// -// # Using Custom Endpoints -// -// The endpoints package also gives you the ability to use your own logic how -// endpoints are resolved. This is a great way to define a custom endpoint -// for select services, without passing that logic down through your code. -// -// If a type implements the Resolver interface it can be used to resolve -// endpoints. To use this with the SDK's Session and Config set the value -// of the type to the EndpointsResolver field of aws.Config when initializing -// the session, or service client. -// -// In addition the ResolverFunc is a wrapper for a func matching the signature -// of Resolver.EndpointFor, converting it to a type that satisfies the -// Resolver interface. -// -// myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { -// if service == endpoints.S3ServiceID { -// return endpoints.ResolvedEndpoint{ -// URL: "s3.custom.endpoint.com", -// SigningRegion: "custom-signing-region", -// }, nil -// } -// -// return endpoints.DefaultResolver().EndpointFor(service, region, optFns...) -// } -// -// sess := session.Must(session.NewSession(&aws.Config{ -// Region: aws.String("us-west-2"), -// EndpointResolver: endpoints.ResolverFunc(myCustomResolver), -// })) -package endpoints diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go deleted file mode 100644 index a686a48fa..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go +++ /dev/null @@ -1,708 +0,0 @@ -package endpoints - -import ( - "fmt" - "regexp" - "strings" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// A Logger is a minimalistic interface for the SDK to log messages to. -type Logger interface { - Log(...interface{}) -} - -// DualStackEndpointState is a constant to describe the dual-stack endpoint resolution -// behavior. -type DualStackEndpointState uint - -const ( - // DualStackEndpointStateUnset is the default value behavior for dual-stack endpoint - // resolution. - DualStackEndpointStateUnset DualStackEndpointState = iota - - // DualStackEndpointStateEnabled enable dual-stack endpoint resolution for endpoints. - DualStackEndpointStateEnabled - - // DualStackEndpointStateDisabled disables dual-stack endpoint resolution for endpoints. - DualStackEndpointStateDisabled -) - -// FIPSEndpointState is a constant to describe the FIPS endpoint resolution behavior. -type FIPSEndpointState uint - -const ( - // FIPSEndpointStateUnset is the default value behavior for FIPS endpoint resolution. - FIPSEndpointStateUnset FIPSEndpointState = iota - - // FIPSEndpointStateEnabled enables FIPS endpoint resolution for service endpoints. - FIPSEndpointStateEnabled - - // FIPSEndpointStateDisabled disables FIPS endpoint resolution for endpoints. - FIPSEndpointStateDisabled -) - -// Options provide the configuration needed to direct how the -// endpoints will be resolved. -type Options struct { - // DisableSSL forces the endpoint to be resolved as HTTP. - // instead of HTTPS if the service supports it. - DisableSSL bool - - // Sets the resolver to resolve the endpoint as a dualstack endpoint - // for the service. If dualstack support for a service is not known and - // StrictMatching is not enabled a dualstack endpoint for the service will - // be returned. This endpoint may not be valid. If StrictMatching is - // enabled only services that are known to support dualstack will return - // dualstack endpoints. - // - // Deprecated: This option will continue to function for S3 and S3 Control for backwards compatibility. - // UseDualStackEndpoint should be used to enable usage of a service's dual-stack endpoint for all service clients - // moving forward. For S3 and S3 Control, when UseDualStackEndpoint is set to a non-zero value it takes higher - // precedence then this option. - UseDualStack bool - - // Sets the resolver to resolve a dual-stack endpoint for the service. - UseDualStackEndpoint DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint FIPSEndpointState - - // Enables strict matching of services and regions resolved endpoints. - // If the partition doesn't enumerate the exact service and region an - // error will be returned. This option will prevent returning endpoints - // that look valid, but may not resolve to any real endpoint. - StrictMatching bool - - // Enables resolving a service endpoint based on the region provided if the - // service does not exist. The service endpoint ID will be used as the service - // domain name prefix. By default the endpoint resolver requires the service - // to be known when resolving endpoints. - // - // If resolving an endpoint on the partition list the provided region will - // be used to determine which partition's domain name pattern to the service - // endpoint ID with. If both the service and region are unknown and resolving - // the endpoint on partition list an UnknownEndpointError error will be returned. - // - // If resolving and endpoint on a partition specific resolver that partition's - // domain name pattern will be used with the service endpoint ID. If both - // region and service do not exist when resolving an endpoint on a specific - // partition the partition's domain pattern will be used to combine the - // endpoint and region together. - // - // This option is ignored if StrictMatching is enabled. - ResolveUnknownService bool - - // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) - EC2MetadataEndpointMode EC2IMDSEndpointModeState - - // STS Regional Endpoint flag helps with resolving the STS endpoint - STSRegionalEndpoint STSRegionalEndpoint - - // S3 Regional Endpoint flag helps with resolving the S3 endpoint - S3UsEast1RegionalEndpoint S3UsEast1RegionalEndpoint - - // ResolvedRegion is the resolved region string. If provided (non-zero length) it takes priority - // over the region name passed to the ResolveEndpoint call. - ResolvedRegion string - - // Logger is the logger that will be used to log messages. - Logger Logger - - // Determines whether logging of deprecated endpoints usage is enabled. - LogDeprecated bool -} - -func (o Options) getEndpointVariant(service string) (v endpointVariant) { - const s3 = "s3" - const s3Control = "s3-control" - - if (o.UseDualStackEndpoint == DualStackEndpointStateEnabled) || - ((service == s3 || service == s3Control) && (o.UseDualStackEndpoint == DualStackEndpointStateUnset && o.UseDualStack)) { - v |= dualStackVariant - } - if o.UseFIPSEndpoint == FIPSEndpointStateEnabled { - v |= fipsVariant - } - return v -} - -// EC2IMDSEndpointModeState is an enum configuration variable describing the client endpoint mode. -type EC2IMDSEndpointModeState uint - -// Enumeration values for EC2IMDSEndpointModeState -const ( - EC2IMDSEndpointModeStateUnset EC2IMDSEndpointModeState = iota - EC2IMDSEndpointModeStateIPv4 - EC2IMDSEndpointModeStateIPv6 -) - -// SetFromString sets the EC2IMDSEndpointModeState based on the provided string value. Unknown values will default to EC2IMDSEndpointModeStateUnset -func (e *EC2IMDSEndpointModeState) SetFromString(v string) error { - v = strings.TrimSpace(v) - - switch { - case len(v) == 0: - *e = EC2IMDSEndpointModeStateUnset - case strings.EqualFold(v, "IPv6"): - *e = EC2IMDSEndpointModeStateIPv6 - case strings.EqualFold(v, "IPv4"): - *e = EC2IMDSEndpointModeStateIPv4 - default: - return fmt.Errorf("unknown EC2 IMDS endpoint mode, must be either IPv6 or IPv4") - } - return nil -} - -// STSRegionalEndpoint is an enum for the states of the STS Regional Endpoint -// options. -type STSRegionalEndpoint int - -func (e STSRegionalEndpoint) String() string { - switch e { - case LegacySTSEndpoint: - return "legacy" - case RegionalSTSEndpoint: - return "regional" - case UnsetSTSEndpoint: - return "" - default: - return "unknown" - } -} - -const ( - - // UnsetSTSEndpoint represents that STS Regional Endpoint flag is not specified. - UnsetSTSEndpoint STSRegionalEndpoint = iota - - // LegacySTSEndpoint represents when STS Regional Endpoint flag is specified - // to use legacy endpoints. - LegacySTSEndpoint - - // RegionalSTSEndpoint represents when STS Regional Endpoint flag is specified - // to use regional endpoints. - RegionalSTSEndpoint -) - -// GetSTSRegionalEndpoint function returns the STSRegionalEndpointFlag based -// on the input string provided in env config or shared config by the user. -// -// `legacy`, `regional` are the only case-insensitive valid strings for -// resolving the STS regional Endpoint flag. -func GetSTSRegionalEndpoint(s string) (STSRegionalEndpoint, error) { - switch { - case strings.EqualFold(s, "legacy"): - return LegacySTSEndpoint, nil - case strings.EqualFold(s, "regional"): - return RegionalSTSEndpoint, nil - default: - return UnsetSTSEndpoint, fmt.Errorf("unable to resolve the value of STSRegionalEndpoint for %v", s) - } -} - -// S3UsEast1RegionalEndpoint is an enum for the states of the S3 us-east-1 -// Regional Endpoint options. -type S3UsEast1RegionalEndpoint int - -func (e S3UsEast1RegionalEndpoint) String() string { - switch e { - case LegacyS3UsEast1Endpoint: - return "legacy" - case RegionalS3UsEast1Endpoint: - return "regional" - case UnsetS3UsEast1Endpoint: - return "" - default: - return "unknown" - } -} - -const ( - - // UnsetS3UsEast1Endpoint represents that S3 Regional Endpoint flag is not - // specified. - UnsetS3UsEast1Endpoint S3UsEast1RegionalEndpoint = iota - - // LegacyS3UsEast1Endpoint represents when S3 Regional Endpoint flag is - // specified to use legacy endpoints. - LegacyS3UsEast1Endpoint - - // RegionalS3UsEast1Endpoint represents when S3 Regional Endpoint flag is - // specified to use regional endpoints. - RegionalS3UsEast1Endpoint -) - -// GetS3UsEast1RegionalEndpoint function returns the S3UsEast1RegionalEndpointFlag based -// on the input string provided in env config or shared config by the user. -// -// `legacy`, `regional` are the only case-insensitive valid strings for -// resolving the S3 regional Endpoint flag. -func GetS3UsEast1RegionalEndpoint(s string) (S3UsEast1RegionalEndpoint, error) { - switch { - case strings.EqualFold(s, "legacy"): - return LegacyS3UsEast1Endpoint, nil - case strings.EqualFold(s, "regional"): - return RegionalS3UsEast1Endpoint, nil - default: - return UnsetS3UsEast1Endpoint, - fmt.Errorf("unable to resolve the value of S3UsEast1RegionalEndpoint for %v", s) - } -} - -// Set combines all of the option functions together. -func (o *Options) Set(optFns ...func(*Options)) { - for _, fn := range optFns { - fn(o) - } -} - -// DisableSSLOption sets the DisableSSL options. Can be used as a functional -// option when resolving endpoints. -func DisableSSLOption(o *Options) { - o.DisableSSL = true -} - -// UseDualStackOption sets the UseDualStack option. Can be used as a functional -// option when resolving endpoints. -// -// Deprecated: UseDualStackEndpointOption should be used to enable usage of a service's dual-stack endpoint. -// When DualStackEndpointState is set to a non-zero value it takes higher precedence then this option. -func UseDualStackOption(o *Options) { - o.UseDualStack = true -} - -// UseDualStackEndpointOption sets the UseDualStackEndpoint option to enabled. Can be used as a functional -// option when resolving endpoints. -func UseDualStackEndpointOption(o *Options) { - o.UseDualStackEndpoint = DualStackEndpointStateEnabled -} - -// UseFIPSEndpointOption sets the UseFIPSEndpoint option to enabled. Can be used as a functional -// option when resolving endpoints. -func UseFIPSEndpointOption(o *Options) { - o.UseFIPSEndpoint = FIPSEndpointStateEnabled -} - -// StrictMatchingOption sets the StrictMatching option. Can be used as a functional -// option when resolving endpoints. -func StrictMatchingOption(o *Options) { - o.StrictMatching = true -} - -// ResolveUnknownServiceOption sets the ResolveUnknownService option. Can be used -// as a functional option when resolving endpoints. -func ResolveUnknownServiceOption(o *Options) { - o.ResolveUnknownService = true -} - -// STSRegionalEndpointOption enables the STS endpoint resolver behavior to resolve -// STS endpoint to their regional endpoint, instead of the global endpoint. -func STSRegionalEndpointOption(o *Options) { - o.STSRegionalEndpoint = RegionalSTSEndpoint -} - -// A Resolver provides the interface for functionality to resolve endpoints. -// The build in Partition and DefaultResolver return value satisfy this interface. -type Resolver interface { - EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) -} - -// ResolverFunc is a helper utility that wraps a function so it satisfies the -// Resolver interface. This is useful when you want to add additional endpoint -// resolving logic, or stub out specific endpoints with custom values. -type ResolverFunc func(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) - -// EndpointFor wraps the ResolverFunc function to satisfy the Resolver interface. -func (fn ResolverFunc) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return fn(service, region, opts...) -} - -var schemeRE = regexp.MustCompile("^([^:]+)://") - -// AddScheme adds the HTTP or HTTPS schemes to a endpoint URL if there is no -// scheme. If disableSSL is true HTTP will set HTTP instead of the default HTTPS. -// -// If disableSSL is set, it will only set the URL's scheme if the URL does not -// contain a scheme. -func AddScheme(endpoint string, disableSSL bool) string { - if !schemeRE.MatchString(endpoint) { - scheme := "https" - if disableSSL { - scheme = "http" - } - endpoint = fmt.Sprintf("%s://%s", scheme, endpoint) - } - - return endpoint -} - -// EnumPartitions a provides a way to retrieve the underlying partitions that -// make up the SDK's default Resolver, or any resolver decoded from a model -// file. -// -// Use this interface with DefaultResolver and DecodeModels to get the list of -// Partitions. -type EnumPartitions interface { - Partitions() []Partition -} - -// RegionsForService returns a map of regions for the partition and service. -// If either the partition or service does not exist false will be returned -// as the second parameter. -// -// This example shows how to get the regions for DynamoDB in the AWS partition. -// -// rs, exists := endpoints.RegionsForService(endpoints.DefaultPartitions(), endpoints.AwsPartitionID, endpoints.DynamodbServiceID) -// -// This is equivalent to using the partition directly. -// -// rs := endpoints.AwsPartition().Services()[endpoints.DynamodbServiceID].Regions() -func RegionsForService(ps []Partition, partitionID, serviceID string) (map[string]Region, bool) { - for _, p := range ps { - if p.ID() != partitionID { - continue - } - if _, ok := p.p.Services[serviceID]; !(ok || serviceID == Ec2metadataServiceID) { - break - } - - s := Service{ - id: serviceID, - p: p.p, - } - return s.Regions(), true - } - - return map[string]Region{}, false -} - -// PartitionForRegion returns the first partition which includes the region -// passed in. This includes both known regions and regions which match -// a pattern supported by the partition which may include regions that are -// not explicitly known by the partition. Use the Regions method of the -// returned Partition if explicit support is needed. -func PartitionForRegion(ps []Partition, regionID string) (Partition, bool) { - for _, p := range ps { - if _, ok := p.p.Regions[regionID]; ok || p.p.RegionRegex.MatchString(regionID) { - return p, true - } - } - - return Partition{}, false -} - -// A Partition provides the ability to enumerate the partition's regions -// and services. -type Partition struct { - id, dnsSuffix string - p *partition -} - -// DNSSuffix returns the base domain name of the partition. -func (p Partition) DNSSuffix() string { return p.dnsSuffix } - -// ID returns the identifier of the partition. -func (p Partition) ID() string { return p.id } - -// EndpointFor attempts to resolve the endpoint based on service and region. -// See Options for information on configuring how the endpoint is resolved. -// -// If the service cannot be found in the metadata the UnknownServiceError -// error will be returned. This validation will occur regardless if -// StrictMatching is enabled. To enable resolving unknown services set the -// "ResolveUnknownService" option to true. When StrictMatching is disabled -// this option allows the partition resolver to resolve a endpoint based on -// the service endpoint ID provided. -// -// When resolving endpoints you can choose to enable StrictMatching. This will -// require the provided service and region to be known by the partition. -// If the endpoint cannot be strictly resolved an error will be returned. This -// mode is useful to ensure the endpoint resolved is valid. Without -// StrictMatching enabled the endpoint returned may look valid but may not work. -// StrictMatching requires the SDK to be updated if you want to take advantage -// of new regions and services expansions. -// -// Errors that can be returned. -// - UnknownServiceError -// - UnknownEndpointError -func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return p.p.EndpointFor(service, region, opts...) -} - -// Regions returns a map of Regions indexed by their ID. This is useful for -// enumerating over the regions in a partition. -func (p Partition) Regions() map[string]Region { - rs := make(map[string]Region, len(p.p.Regions)) - for id, r := range p.p.Regions { - rs[id] = Region{ - id: id, - desc: r.Description, - p: p.p, - } - } - - return rs -} - -// Services returns a map of Service indexed by their ID. This is useful for -// enumerating over the services in a partition. -func (p Partition) Services() map[string]Service { - ss := make(map[string]Service, len(p.p.Services)) - - for id := range p.p.Services { - ss[id] = Service{ - id: id, - p: p.p, - } - } - - // Since we have removed the customization that injected this into the model - // we still need to pretend that this is a modeled service. - if _, ok := ss[Ec2metadataServiceID]; !ok { - ss[Ec2metadataServiceID] = Service{ - id: Ec2metadataServiceID, - p: p.p, - } - } - - return ss -} - -// A Region provides information about a region, and ability to resolve an -// endpoint from the context of a region, given a service. -type Region struct { - id, desc string - p *partition -} - -// ID returns the region's identifier. -func (r Region) ID() string { return r.id } - -// Description returns the region's description. The region description -// is free text, it can be empty, and it may change between SDK releases. -func (r Region) Description() string { return r.desc } - -// ResolveEndpoint resolves an endpoint from the context of the region given -// a service. See Partition.EndpointFor for usage and errors that can be returned. -func (r Region) ResolveEndpoint(service string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return r.p.EndpointFor(service, r.id, opts...) -} - -// Services returns a list of all services that are known to be in this region. -func (r Region) Services() map[string]Service { - ss := map[string]Service{} - for id, s := range r.p.Services { - if _, ok := s.Endpoints[endpointKey{Region: r.id}]; ok { - ss[id] = Service{ - id: id, - p: r.p, - } - } - } - - return ss -} - -// A Service provides information about a service, and ability to resolve an -// endpoint from the context of a service, given a region. -type Service struct { - id string - p *partition -} - -// ID returns the identifier for the service. -func (s Service) ID() string { return s.id } - -// ResolveEndpoint resolves an endpoint from the context of a service given -// a region. See Partition.EndpointFor for usage and errors that can be returned. -func (s Service) ResolveEndpoint(region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return s.p.EndpointFor(s.id, region, opts...) -} - -// Regions returns a map of Regions that the service is present in. -// -// A region is the AWS region the service exists in. Whereas a Endpoint is -// an URL that can be resolved to a instance of a service. -func (s Service) Regions() map[string]Region { - rs := map[string]Region{} - - service, ok := s.p.Services[s.id] - - // Since ec2metadata customization has been removed we need to check - // if it was defined in non-standard endpoints.json file. If it's not - // then we can return the empty map as there is no regional-endpoints for IMDS. - // Otherwise, we iterate need to iterate the non-standard model. - if s.id == Ec2metadataServiceID && !ok { - return rs - } - - for id := range service.Endpoints { - if id.Variant != 0 { - continue - } - if r, ok := s.p.Regions[id.Region]; ok { - rs[id.Region] = Region{ - id: id.Region, - desc: r.Description, - p: s.p, - } - } - } - - return rs -} - -// Endpoints returns a map of Endpoints indexed by their ID for all known -// endpoints for a service. -// -// A region is the AWS region the service exists in. Whereas a Endpoint is -// an URL that can be resolved to a instance of a service. -func (s Service) Endpoints() map[string]Endpoint { - es := make(map[string]Endpoint, len(s.p.Services[s.id].Endpoints)) - for id := range s.p.Services[s.id].Endpoints { - if id.Variant != 0 { - continue - } - es[id.Region] = Endpoint{ - id: id.Region, - serviceID: s.id, - p: s.p, - } - } - - return es -} - -// A Endpoint provides information about endpoints, and provides the ability -// to resolve that endpoint for the service, and the region the endpoint -// represents. -type Endpoint struct { - id string - serviceID string - p *partition -} - -// ID returns the identifier for an endpoint. -func (e Endpoint) ID() string { return e.id } - -// ServiceID returns the identifier the endpoint belongs to. -func (e Endpoint) ServiceID() string { return e.serviceID } - -// ResolveEndpoint resolves an endpoint from the context of a service and -// region the endpoint represents. See Partition.EndpointFor for usage and -// errors that can be returned. -func (e Endpoint) ResolveEndpoint(opts ...func(*Options)) (ResolvedEndpoint, error) { - return e.p.EndpointFor(e.serviceID, e.id, opts...) -} - -// A ResolvedEndpoint is an endpoint that has been resolved based on a partition -// service, and region. -type ResolvedEndpoint struct { - // The endpoint URL - URL string - - // The endpoint partition - PartitionID string - - // The region that should be used for signing requests. - SigningRegion string - - // The service name that should be used for signing requests. - SigningName string - - // States that the signing name for this endpoint was derived from metadata - // passed in, but was not explicitly modeled. - SigningNameDerived bool - - // The signing method that should be used for signing requests. - SigningMethod string -} - -// So that the Error interface type can be included as an anonymous field -// in the requestError struct and not conflict with the error.Error() method. -type awsError awserr.Error - -// A EndpointNotFoundError is returned when in StrictMatching mode, and the -// endpoint for the service and region cannot be found in any of the partitions. -type EndpointNotFoundError struct { - awsError - Partition string - Service string - Region string -} - -// A UnknownServiceError is returned when the service does not resolve to an -// endpoint. Includes a list of all known services for the partition. Returned -// when a partition does not support the service. -type UnknownServiceError struct { - awsError - Partition string - Service string - Known []string -} - -// NewUnknownServiceError builds and returns UnknownServiceError. -func NewUnknownServiceError(p, s string, known []string) UnknownServiceError { - return UnknownServiceError{ - awsError: awserr.New("UnknownServiceError", - "could not resolve endpoint for unknown service", nil), - Partition: p, - Service: s, - Known: known, - } -} - -// String returns the string representation of the error. -func (e UnknownServiceError) Error() string { - extra := fmt.Sprintf("partition: %q, service: %q", - e.Partition, e.Service) - if len(e.Known) > 0 { - extra += fmt.Sprintf(", known: %v", e.Known) - } - return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -func (e UnknownServiceError) String() string { - return e.Error() -} - -// A UnknownEndpointError is returned when in StrictMatching mode and the -// service is valid, but the region does not resolve to an endpoint. Includes -// a list of all known endpoints for the service. -type UnknownEndpointError struct { - awsError - Partition string - Service string - Region string - Known []string -} - -// NewUnknownEndpointError builds and returns UnknownEndpointError. -func NewUnknownEndpointError(p, s, r string, known []string) UnknownEndpointError { - return UnknownEndpointError{ - awsError: awserr.New("UnknownEndpointError", - "could not resolve endpoint", nil), - Partition: p, - Service: s, - Region: r, - Known: known, - } -} - -// String returns the string representation of the error. -func (e UnknownEndpointError) Error() string { - extra := fmt.Sprintf("partition: %q, service: %q, region: %q", - e.Partition, e.Service, e.Region) - if len(e.Known) > 0 { - extra += fmt.Sprintf(", known: %v", e.Known) - } - return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -func (e UnknownEndpointError) String() string { - return e.Error() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/legacy_regions.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/legacy_regions.go deleted file mode 100644 index df75e899a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/legacy_regions.go +++ /dev/null @@ -1,24 +0,0 @@ -package endpoints - -var legacyGlobalRegions = map[string]map[string]struct{}{ - "sts": { - "ap-northeast-1": {}, - "ap-south-1": {}, - "ap-southeast-1": {}, - "ap-southeast-2": {}, - "ca-central-1": {}, - "eu-central-1": {}, - "eu-north-1": {}, - "eu-west-1": {}, - "eu-west-2": {}, - "eu-west-3": {}, - "sa-east-1": {}, - "us-east-1": {}, - "us-east-2": {}, - "us-west-1": {}, - "us-west-2": {}, - }, - "s3": { - "us-east-1": {}, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go deleted file mode 100644 index 89f6627dc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go +++ /dev/null @@ -1,594 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "fmt" - "regexp" - "strconv" - "strings" -) - -const ( - ec2MetadataEndpointIPv6 = "http://[fd00:ec2::254]/latest" - ec2MetadataEndpointIPv4 = "http://169.254.169.254/latest" -) - -const dnsSuffixTemplateKey = "{dnsSuffix}" - -// defaultKey is a compound map key of a variant and other values. -type defaultKey struct { - Variant endpointVariant - ServiceVariant serviceVariant -} - -// endpointKey is a compound map key of a region and associated variant value. -type endpointKey struct { - Region string - Variant endpointVariant -} - -// endpointVariant is a bit field to describe the endpoints attributes. -type endpointVariant uint64 - -// serviceVariant is a bit field to describe the service endpoint attributes. -type serviceVariant uint64 - -const ( - // fipsVariant indicates that the endpoint is FIPS capable. - fipsVariant endpointVariant = 1 << (64 - 1 - iota) - - // dualStackVariant indicates that the endpoint is DualStack capable. - dualStackVariant -) - -var regionValidationRegex = regexp.MustCompile(`^[[:alnum:]]([[:alnum:]\-]*[[:alnum:]])?$`) - -type partitions []partition - -func (ps partitions) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - var opt Options - opt.Set(opts...) - - if len(opt.ResolvedRegion) > 0 { - region = opt.ResolvedRegion - } - - for i := 0; i < len(ps); i++ { - if !ps[i].canResolveEndpoint(service, region, opt) { - continue - } - - return ps[i].EndpointFor(service, region, opts...) - } - - // If loose matching fallback to first partition format to use - // when resolving the endpoint. - if !opt.StrictMatching && len(ps) > 0 { - return ps[0].EndpointFor(service, region, opts...) - } - - return ResolvedEndpoint{}, NewUnknownEndpointError("all partitions", service, region, []string{}) -} - -// Partitions satisfies the EnumPartitions interface and returns a list -// of Partitions representing each partition represented in the SDK's -// endpoints model. -func (ps partitions) Partitions() []Partition { - parts := make([]Partition, 0, len(ps)) - for i := 0; i < len(ps); i++ { - parts = append(parts, ps[i].Partition()) - } - - return parts -} - -type endpointWithVariants struct { - endpoint - Variants []endpointWithTags `json:"variants"` -} - -type endpointWithTags struct { - endpoint - Tags []string `json:"tags"` -} - -type endpointDefaults map[defaultKey]endpoint - -func (p *endpointDefaults) UnmarshalJSON(data []byte) error { - if *p == nil { - *p = make(endpointDefaults) - } - - var e endpointWithVariants - if err := json.Unmarshal(data, &e); err != nil { - return err - } - - (*p)[defaultKey{Variant: 0}] = e.endpoint - - e.Hostname = "" - e.DNSSuffix = "" - - for _, variant := range e.Variants { - endpointVariant, unknown := parseVariantTags(variant.Tags) - if unknown { - continue - } - - var ve endpoint - ve.mergeIn(e.endpoint) - ve.mergeIn(variant.endpoint) - - (*p)[defaultKey{Variant: endpointVariant}] = ve - } - - return nil -} - -func parseVariantTags(tags []string) (ev endpointVariant, unknown bool) { - if len(tags) == 0 { - unknown = true - return - } - - for _, tag := range tags { - switch { - case strings.EqualFold("fips", tag): - ev |= fipsVariant - case strings.EqualFold("dualstack", tag): - ev |= dualStackVariant - default: - unknown = true - } - } - return ev, unknown -} - -type partition struct { - ID string `json:"partition"` - Name string `json:"partitionName"` - DNSSuffix string `json:"dnsSuffix"` - RegionRegex regionRegex `json:"regionRegex"` - Defaults endpointDefaults `json:"defaults"` - Regions regions `json:"regions"` - Services services `json:"services"` -} - -func (p partition) Partition() Partition { - return Partition{ - dnsSuffix: p.DNSSuffix, - id: p.ID, - p: &p, - } -} - -func (p partition) canResolveEndpoint(service, region string, options Options) bool { - s, hasService := p.Services[service] - _, hasEndpoint := s.Endpoints[endpointKey{ - Region: region, - Variant: options.getEndpointVariant(service), - }] - - if hasEndpoint && hasService { - return true - } - - if options.StrictMatching { - return false - } - - return p.RegionRegex.MatchString(region) -} - -func allowLegacyEmptyRegion(service string) bool { - legacy := map[string]struct{}{ - "budgets": {}, - "ce": {}, - "chime": {}, - "cloudfront": {}, - "ec2metadata": {}, - "iam": {}, - "importexport": {}, - "organizations": {}, - "route53": {}, - "sts": {}, - "support": {}, - "waf": {}, - } - - _, allowed := legacy[service] - return allowed -} - -func (p partition) EndpointFor(service, region string, opts ...func(*Options)) (resolved ResolvedEndpoint, err error) { - var opt Options - opt.Set(opts...) - - if len(opt.ResolvedRegion) > 0 { - region = opt.ResolvedRegion - } - - s, hasService := p.Services[service] - - if service == Ec2metadataServiceID && !hasService { - endpoint := getEC2MetadataEndpoint(p.ID, service, opt.EC2MetadataEndpointMode) - return endpoint, nil - } - - if len(service) == 0 || !(hasService || opt.ResolveUnknownService) { - // Only return error if the resolver will not fallback to creating - // endpoint based on service endpoint ID passed in. - return resolved, NewUnknownServiceError(p.ID, service, serviceList(p.Services)) - } - - if len(region) == 0 && allowLegacyEmptyRegion(service) && len(s.PartitionEndpoint) != 0 { - region = s.PartitionEndpoint - } - - if r, ok := isLegacyGlobalRegion(service, region, opt); ok { - region = r - } - - variant := opt.getEndpointVariant(service) - - endpoints := s.Endpoints - - serviceDefaults, hasServiceDefault := s.Defaults[defaultKey{Variant: variant}] - // If we searched for a variant which may have no explicit service defaults, - // then we need to inherit the standard service defaults except the hostname and dnsSuffix - if variant != 0 && !hasServiceDefault { - serviceDefaults = s.Defaults[defaultKey{}] - serviceDefaults.Hostname = "" - serviceDefaults.DNSSuffix = "" - } - - partitionDefaults, hasPartitionDefault := p.Defaults[defaultKey{Variant: variant}] - - var dnsSuffix string - if len(serviceDefaults.DNSSuffix) > 0 { - dnsSuffix = serviceDefaults.DNSSuffix - } else if variant == 0 { - // For legacy reasons the partition dnsSuffix is not in the defaults, so if we looked for - // a non-variant endpoint then we need to set the dnsSuffix. - dnsSuffix = p.DNSSuffix - } - - noDefaults := !hasServiceDefault && !hasPartitionDefault - - e, hasEndpoint := s.endpointForRegion(region, endpoints, variant) - if len(region) == 0 || (!hasEndpoint && (opt.StrictMatching || noDefaults)) { - return resolved, NewUnknownEndpointError(p.ID, service, region, endpointList(endpoints, variant)) - } - - defs := []endpoint{partitionDefaults, serviceDefaults} - - return e.resolve(service, p.ID, region, dnsSuffixTemplateKey, dnsSuffix, defs, opt) -} - -func getEC2MetadataEndpoint(partitionID, service string, mode EC2IMDSEndpointModeState) ResolvedEndpoint { - switch mode { - case EC2IMDSEndpointModeStateIPv6: - return ResolvedEndpoint{ - URL: ec2MetadataEndpointIPv6, - PartitionID: partitionID, - SigningRegion: "aws-global", - SigningName: service, - SigningNameDerived: true, - SigningMethod: "v4", - } - case EC2IMDSEndpointModeStateIPv4: - fallthrough - default: - return ResolvedEndpoint{ - URL: ec2MetadataEndpointIPv4, - PartitionID: partitionID, - SigningRegion: "aws-global", - SigningName: service, - SigningNameDerived: true, - SigningMethod: "v4", - } - } -} - -func isLegacyGlobalRegion(service string, region string, opt Options) (string, bool) { - if opt.getEndpointVariant(service) != 0 { - return "", false - } - - const ( - sts = "sts" - s3 = "s3" - awsGlobal = "aws-global" - ) - - switch { - case service == sts && opt.STSRegionalEndpoint == RegionalSTSEndpoint: - return region, false - case service == s3 && opt.S3UsEast1RegionalEndpoint == RegionalS3UsEast1Endpoint: - return region, false - default: - if _, ok := legacyGlobalRegions[service][region]; ok { - return awsGlobal, true - } - } - - return region, false -} - -func serviceList(ss services) []string { - list := make([]string, 0, len(ss)) - for k := range ss { - list = append(list, k) - } - return list -} -func endpointList(es serviceEndpoints, variant endpointVariant) []string { - list := make([]string, 0, len(es)) - for k := range es { - if k.Variant != variant { - continue - } - list = append(list, k.Region) - } - return list -} - -type regionRegex struct { - *regexp.Regexp -} - -func (rr *regionRegex) UnmarshalJSON(b []byte) (err error) { - // Strip leading and trailing quotes - regex, err := strconv.Unquote(string(b)) - if err != nil { - return fmt.Errorf("unable to strip quotes from regex, %v", err) - } - - rr.Regexp, err = regexp.Compile(regex) - if err != nil { - return fmt.Errorf("unable to unmarshal region regex, %v", err) - } - return nil -} - -type regions map[string]region - -type region struct { - Description string `json:"description"` -} - -type services map[string]service - -type service struct { - PartitionEndpoint string `json:"partitionEndpoint"` - IsRegionalized boxedBool `json:"isRegionalized,omitempty"` - Defaults endpointDefaults `json:"defaults"` - Endpoints serviceEndpoints `json:"endpoints"` -} - -func (s *service) endpointForRegion(region string, endpoints serviceEndpoints, variant endpointVariant) (endpoint, bool) { - if e, ok := endpoints[endpointKey{Region: region, Variant: variant}]; ok { - return e, true - } - - if s.IsRegionalized == boxedFalse { - return endpoints[endpointKey{Region: s.PartitionEndpoint, Variant: variant}], region == s.PartitionEndpoint - } - - // Unable to find any matching endpoint, return - // blank that will be used for generic endpoint creation. - return endpoint{}, false -} - -type serviceEndpoints map[endpointKey]endpoint - -func (s *serviceEndpoints) UnmarshalJSON(data []byte) error { - if *s == nil { - *s = make(serviceEndpoints) - } - - var regionToEndpoint map[string]endpointWithVariants - - if err := json.Unmarshal(data, ®ionToEndpoint); err != nil { - return err - } - - for region, e := range regionToEndpoint { - (*s)[endpointKey{Region: region}] = e.endpoint - - e.Hostname = "" - e.DNSSuffix = "" - - for _, variant := range e.Variants { - endpointVariant, unknown := parseVariantTags(variant.Tags) - if unknown { - continue - } - - var ve endpoint - ve.mergeIn(e.endpoint) - ve.mergeIn(variant.endpoint) - - (*s)[endpointKey{Region: region, Variant: endpointVariant}] = ve - } - } - - return nil -} - -type endpoint struct { - Hostname string `json:"hostname"` - Protocols []string `json:"protocols"` - CredentialScope credentialScope `json:"credentialScope"` - - DNSSuffix string `json:"dnsSuffix"` - - // Signature Version not used - SignatureVersions []string `json:"signatureVersions"` - - // SSLCommonName not used. - SSLCommonName string `json:"sslCommonName"` - - Deprecated boxedBool `json:"deprecated"` -} - -// isZero returns whether the endpoint structure is an empty (zero) value. -func (e endpoint) isZero() bool { - switch { - case len(e.Hostname) != 0: - return false - case len(e.Protocols) != 0: - return false - case e.CredentialScope != (credentialScope{}): - return false - case len(e.SignatureVersions) != 0: - return false - case len(e.SSLCommonName) != 0: - return false - } - return true -} - -const ( - defaultProtocol = "https" - defaultSigner = "v4" -) - -var ( - protocolPriority = []string{"https", "http"} - signerPriority = []string{"v4", "v2"} -) - -func getByPriority(s []string, p []string, def string) string { - if len(s) == 0 { - return def - } - - for i := 0; i < len(p); i++ { - for j := 0; j < len(s); j++ { - if s[j] == p[i] { - return s[j] - } - } - } - - return s[0] -} - -func (e endpoint) resolve(service, partitionID, region, dnsSuffixTemplateVariable, dnsSuffix string, defs []endpoint, opts Options) (ResolvedEndpoint, error) { - var merged endpoint - for _, def := range defs { - merged.mergeIn(def) - } - merged.mergeIn(e) - e = merged - - signingRegion := e.CredentialScope.Region - if len(signingRegion) == 0 { - signingRegion = region - } - - signingName := e.CredentialScope.Service - var signingNameDerived bool - if len(signingName) == 0 { - signingName = service - signingNameDerived = true - } - - hostname := e.Hostname - - if !validateInputRegion(region) { - return ResolvedEndpoint{}, fmt.Errorf("invalid region identifier format provided") - } - - if len(merged.DNSSuffix) > 0 { - dnsSuffix = merged.DNSSuffix - } - - u := strings.Replace(hostname, "{service}", service, 1) - u = strings.Replace(u, "{region}", region, 1) - u = strings.Replace(u, dnsSuffixTemplateVariable, dnsSuffix, 1) - - scheme := getEndpointScheme(e.Protocols, opts.DisableSSL) - u = fmt.Sprintf("%s://%s", scheme, u) - - if e.Deprecated == boxedTrue && opts.LogDeprecated && opts.Logger != nil { - opts.Logger.Log(fmt.Sprintf("endpoint identifier %q, url %q marked as deprecated", region, u)) - } - - return ResolvedEndpoint{ - URL: u, - PartitionID: partitionID, - SigningRegion: signingRegion, - SigningName: signingName, - SigningNameDerived: signingNameDerived, - SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - }, nil -} - -func getEndpointScheme(protocols []string, disableSSL bool) string { - if disableSSL { - return "http" - } - - return getByPriority(protocols, protocolPriority, defaultProtocol) -} - -func (e *endpoint) mergeIn(other endpoint) { - if len(other.Hostname) > 0 { - e.Hostname = other.Hostname - } - if len(other.Protocols) > 0 { - e.Protocols = other.Protocols - } - if len(other.SignatureVersions) > 0 { - e.SignatureVersions = other.SignatureVersions - } - if len(other.CredentialScope.Region) > 0 { - e.CredentialScope.Region = other.CredentialScope.Region - } - if len(other.CredentialScope.Service) > 0 { - e.CredentialScope.Service = other.CredentialScope.Service - } - if len(other.SSLCommonName) > 0 { - e.SSLCommonName = other.SSLCommonName - } - if len(other.DNSSuffix) > 0 { - e.DNSSuffix = other.DNSSuffix - } - if other.Deprecated != boxedBoolUnset { - e.Deprecated = other.Deprecated - } -} - -type credentialScope struct { - Region string `json:"region"` - Service string `json:"service"` -} - -type boxedBool int - -func (b *boxedBool) UnmarshalJSON(buf []byte) error { - v, err := strconv.ParseBool(string(buf)) - if err != nil { - return err - } - - if v { - *b = boxedTrue - } else { - *b = boxedFalse - } - - return nil -} - -const ( - boxedBoolUnset boxedBool = iota - boxedFalse - boxedTrue -) - -func validateInputRegion(region string) bool { - return regionValidationRegex.MatchString(region) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go deleted file mode 100644 index 84922bca8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go +++ /dev/null @@ -1,412 +0,0 @@ -//go:build codegen -// +build codegen - -package endpoints - -import ( - "fmt" - "io" - "reflect" - "strings" - "text/template" - "unicode" -) - -// A CodeGenOptions are the options for code generating the endpoints into -// Go code from the endpoints model definition. -type CodeGenOptions struct { - // Options for how the model will be decoded. - DecodeModelOptions DecodeModelOptions - - // Disables code generation of the service endpoint prefix IDs defined in - // the model. - DisableGenerateServiceIDs bool -} - -// Set combines all of the option functions together -func (d *CodeGenOptions) Set(optFns ...func(*CodeGenOptions)) { - for _, fn := range optFns { - fn(d) - } -} - -// CodeGenModel given a endpoints model file will decode it and attempt to -// generate Go code from the model definition. Error will be returned if -// the code is unable to be generated, or decoded. -func CodeGenModel(modelFile io.Reader, outFile io.Writer, optFns ...func(*CodeGenOptions)) error { - var opts CodeGenOptions - opts.Set(optFns...) - - resolver, err := DecodeModel(modelFile, func(d *DecodeModelOptions) { - *d = opts.DecodeModelOptions - }) - if err != nil { - return err - } - - v := struct { - Resolver - CodeGenOptions - }{ - Resolver: resolver, - CodeGenOptions: opts, - } - - tmpl := template.Must(template.New("tmpl").Funcs(funcMap).Parse(v3Tmpl)) - if err := tmpl.ExecuteTemplate(outFile, "defaults", v); err != nil { - return fmt.Errorf("failed to execute template, %v", err) - } - - return nil -} - -func toSymbol(v string) string { - out := []rune{} - for _, c := range strings.Title(v) { - if !(unicode.IsNumber(c) || unicode.IsLetter(c)) { - continue - } - - out = append(out, c) - } - - return string(out) -} - -func quoteString(v string) string { - return fmt.Sprintf("%q", v) -} - -func regionConstName(p, r string) string { - return toSymbol(p) + toSymbol(r) -} - -func partitionGetter(id string) string { - return fmt.Sprintf("%sPartition", toSymbol(id)) -} - -func partitionVarName(id string) string { - return fmt.Sprintf("%sPartition", strings.ToLower(toSymbol(id))) -} - -func listPartitionNames(ps partitions) string { - names := []string{} - switch len(ps) { - case 1: - return ps[0].Name - case 2: - return fmt.Sprintf("%s and %s", ps[0].Name, ps[1].Name) - default: - for i, p := range ps { - if i == len(ps)-1 { - names = append(names, "and "+p.Name) - } else { - names = append(names, p.Name) - } - } - return strings.Join(names, ", ") - } -} - -func boxedBoolIfSet(msg string, v boxedBool) string { - switch v { - case boxedTrue: - return fmt.Sprintf(msg, "boxedTrue") - case boxedFalse: - return fmt.Sprintf(msg, "boxedFalse") - default: - return "" - } -} - -func stringIfSet(msg, v string) string { - if len(v) == 0 { - return "" - } - - return fmt.Sprintf(msg, v) -} - -func stringSliceIfSet(msg string, vs []string) string { - if len(vs) == 0 { - return "" - } - - names := []string{} - for _, v := range vs { - names = append(names, `"`+v+`"`) - } - - return fmt.Sprintf(msg, strings.Join(names, ",")) -} - -func endpointIsSet(v endpoint) bool { - return !reflect.DeepEqual(v, endpoint{}) -} - -func serviceSet(ps partitions) map[string]struct{} { - set := map[string]struct{}{} - for _, p := range ps { - for id := range p.Services { - set[id] = struct{}{} - } - } - - return set -} - -func endpointVariantSetter(variant endpointVariant) (string, error) { - if variant == 0 { - return "0", nil - } - - if variant > (fipsVariant | dualStackVariant) { - return "", fmt.Errorf("unknown endpoint variant") - } - - var symbols []string - if variant&fipsVariant != 0 { - symbols = append(symbols, "fipsVariant") - } - if variant&dualStackVariant != 0 { - symbols = append(symbols, "dualStackVariant") - } - v := strings.Join(symbols, "|") - - return v, nil -} - -func endpointKeySetter(e endpointKey) (string, error) { - var sb strings.Builder - sb.WriteString("endpointKey{\n") - sb.WriteString(fmt.Sprintf("Region: %q,\n", e.Region)) - if e.Variant != 0 { - variantSetter, err := endpointVariantSetter(e.Variant) - if err != nil { - return "", err - } - sb.WriteString(fmt.Sprintf("Variant: %s,\n", variantSetter)) - } - sb.WriteString("}") - return sb.String(), nil -} - -func defaultKeySetter(e defaultKey) (string, error) { - var sb strings.Builder - sb.WriteString("defaultKey{\n") - if e.Variant != 0 { - variantSetter, err := endpointVariantSetter(e.Variant) - if err != nil { - return "", err - } - sb.WriteString(fmt.Sprintf("Variant: %s,\n", variantSetter)) - } - sb.WriteString("}") - return sb.String(), nil -} - -var funcMap = template.FuncMap{ - "ToSymbol": toSymbol, - "QuoteString": quoteString, - "RegionConst": regionConstName, - "PartitionGetter": partitionGetter, - "PartitionVarName": partitionVarName, - "ListPartitionNames": listPartitionNames, - "BoxedBoolIfSet": boxedBoolIfSet, - "StringIfSet": stringIfSet, - "StringSliceIfSet": stringSliceIfSet, - "EndpointIsSet": endpointIsSet, - "ServicesSet": serviceSet, - "EndpointVariantSetter": endpointVariantSetter, - "EndpointKeySetter": endpointKeySetter, - "DefaultKeySetter": defaultKeySetter, -} - -const v3Tmpl = ` -{{ define "defaults" -}} -// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. - -package endpoints - -import ( - "regexp" -) - - {{ template "partition consts" $.Resolver }} - - {{ range $_, $partition := $.Resolver }} - {{ template "partition region consts" $partition }} - {{ end }} - - {{ if not $.DisableGenerateServiceIDs -}} - {{ template "service consts" $.Resolver }} - {{- end }} - - {{ template "endpoint resolvers" $.Resolver }} -{{- end }} - -{{ define "partition consts" }} - // Partition identifiers - const ( - {{ range $_, $p := . -}} - {{ ToSymbol $p.ID }}PartitionID = {{ QuoteString $p.ID }} // {{ $p.Name }} partition. - {{ end -}} - ) -{{- end }} - -{{ define "partition region consts" }} - // {{ .Name }} partition's regions. - const ( - {{ range $id, $region := .Regions -}} - {{ ToSymbol $id }}RegionID = {{ QuoteString $id }} // {{ $region.Description }}. - {{ end -}} - ) -{{- end }} - -{{ define "service consts" }} - // Service identifiers - const ( - {{ $serviceSet := ServicesSet . -}} - {{ range $id, $_ := $serviceSet -}} - {{ ToSymbol $id }}ServiceID = {{ QuoteString $id }} // {{ ToSymbol $id }}. - {{ end -}} - ) -{{- end }} - -{{ define "endpoint resolvers" }} - // DefaultResolver returns an Endpoint resolver that will be able - // to resolve endpoints for: {{ ListPartitionNames . }}. - // - // Use DefaultPartitions() to get the list of the default partitions. - func DefaultResolver() Resolver { - return defaultPartitions - } - - // DefaultPartitions returns a list of the partitions the SDK is bundled - // with. The available partitions are: {{ ListPartitionNames . }}. - // - // partitions := endpoints.DefaultPartitions - // for _, p := range partitions { - // // ... inspect partitions - // } - func DefaultPartitions() []Partition { - return defaultPartitions.Partitions() - } - - var defaultPartitions = partitions{ - {{ range $_, $partition := . -}} - {{ PartitionVarName $partition.ID }}, - {{ end }} - } - - {{ range $_, $partition := . -}} - {{ $name := PartitionGetter $partition.ID -}} - // {{ $name }} returns the Resolver for {{ $partition.Name }}. - func {{ $name }}() Partition { - return {{ PartitionVarName $partition.ID }}.Partition() - } - var {{ PartitionVarName $partition.ID }} = {{ template "gocode Partition" $partition }} - {{ end }} -{{ end }} - -{{ define "default partitions" }} - func DefaultPartitions() []Partition { - return []partition{ - {{ range $_, $partition := . -}} - // {{ ToSymbol $partition.ID}}Partition(), - {{ end }} - } - } -{{ end }} - -{{ define "gocode Partition" -}} -partition{ - {{ StringIfSet "ID: %q,\n" .ID -}} - {{ StringIfSet "Name: %q,\n" .Name -}} - {{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}} - RegionRegex: {{ template "gocode RegionRegex" .RegionRegex }}, - {{ if (gt (len .Defaults) 0) -}} - Defaults: {{ template "gocode Defaults" .Defaults -}}, - {{ end -}} - Regions: {{ template "gocode Regions" .Regions }}, - Services: {{ template "gocode Services" .Services }}, -} -{{- end }} - -{{ define "gocode RegionRegex" -}} -regionRegex{ - Regexp: func() *regexp.Regexp{ - reg, _ := regexp.Compile({{ QuoteString .Regexp.String }}) - return reg - }(), -} -{{- end }} - -{{ define "gocode Regions" -}} -regions{ - {{ range $id, $region := . -}} - "{{ $id }}": {{ template "gocode Region" $region }}, - {{ end -}} -} -{{- end }} - -{{ define "gocode Region" -}} -region{ - {{ StringIfSet "Description: %q,\n" .Description -}} -} -{{- end }} - -{{ define "gocode Services" -}} -services{ - {{ range $id, $service := . -}} - "{{ $id }}": {{ template "gocode Service" $service }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Service" -}} -service{ - {{ StringIfSet "PartitionEndpoint: %q,\n" .PartitionEndpoint -}} - {{ BoxedBoolIfSet "IsRegionalized: %s,\n" .IsRegionalized -}} - {{ if (gt (len .Defaults) 0) -}} - Defaults: {{ template "gocode Defaults" .Defaults -}}, - {{ end -}} - {{ if .Endpoints -}} - Endpoints: {{ template "gocode Endpoints" .Endpoints }}, - {{- end }} -} -{{- end }} - -{{ define "gocode Defaults" -}} -endpointDefaults{ - {{ range $id, $endpoint := . -}} - {{ DefaultKeySetter $id }}: {{ template "gocode Endpoint" $endpoint }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Endpoints" -}} -serviceEndpoints{ - {{ range $id, $endpoint := . -}} - {{ EndpointKeySetter $id }}: {{ template "gocode Endpoint" $endpoint }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Endpoint" -}} -endpoint{ - {{ StringIfSet "Hostname: %q,\n" .Hostname -}} - {{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}} - {{ StringIfSet "SSLCommonName: %q,\n" .SSLCommonName -}} - {{ StringSliceIfSet "Protocols: []string{%s},\n" .Protocols -}} - {{ StringSliceIfSet "SignatureVersions: []string{%s},\n" .SignatureVersions -}} - {{ if or .CredentialScope.Region .CredentialScope.Service -}} - CredentialScope: credentialScope{ - {{ StringIfSet "Region: %q,\n" .CredentialScope.Region -}} - {{ StringIfSet "Service: %q,\n" .CredentialScope.Service -}} - }, - {{- end }} - {{ BoxedBoolIfSet "Deprecated: %s,\n" .Deprecated -}} -} -{{- end }} -` diff --git a/vendor/github.com/aws/aws-sdk-go/aws/errors.go b/vendor/github.com/aws/aws-sdk-go/aws/errors.go deleted file mode 100644 index fa06f7a8f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/errors.go +++ /dev/null @@ -1,13 +0,0 @@ -package aws - -import "github.com/aws/aws-sdk-go/aws/awserr" - -var ( - // ErrMissingRegion is an error that is returned if region configuration is - // not found. - ErrMissingRegion = awserr.New("MissingRegion", "could not find region configuration", nil) - - // ErrMissingEndpoint is an error that is returned if an endpoint cannot be - // resolved for a service. - ErrMissingEndpoint = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go deleted file mode 100644 index 91a6f277a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go +++ /dev/null @@ -1,12 +0,0 @@ -package aws - -// JSONValue is a representation of a grab bag type that will be marshaled -// into a json string. This type can be used just like any other map. -// -// Example: -// -// values := aws.JSONValue{ -// "Foo": "Bar", -// } -// values["Baz"] = "Qux" -type JSONValue map[string]interface{} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/logger.go deleted file mode 100644 index 49674cc79..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/logger.go +++ /dev/null @@ -1,121 +0,0 @@ -package aws - -import ( - "log" - "os" -) - -// A LogLevelType defines the level logging should be performed at. Used to instruct -// the SDK which statements should be logged. -type LogLevelType uint - -// LogLevel returns the pointer to a LogLevel. Should be used to workaround -// not being able to take the address of a non-composite literal. -func LogLevel(l LogLevelType) *LogLevelType { - return &l -} - -// Value returns the LogLevel value or the default value LogOff if the LogLevel -// is nil. Safe to use on nil value LogLevelTypes. -func (l *LogLevelType) Value() LogLevelType { - if l != nil { - return *l - } - return LogOff -} - -// Matches returns true if the v LogLevel is enabled by this LogLevel. Should be -// used with logging sub levels. Is safe to use on nil value LogLevelTypes. If -// LogLevel is nil, will default to LogOff comparison. -func (l *LogLevelType) Matches(v LogLevelType) bool { - c := l.Value() - return c&v == v -} - -// AtLeast returns true if this LogLevel is at least high enough to satisfies v. -// Is safe to use on nil value LogLevelTypes. If LogLevel is nil, will default -// to LogOff comparison. -func (l *LogLevelType) AtLeast(v LogLevelType) bool { - c := l.Value() - return c >= v -} - -const ( - // LogOff states that no logging should be performed by the SDK. This is the - // default state of the SDK, and should be use to disable all logging. - LogOff LogLevelType = iota * 0x1000 - - // LogDebug state that debug output should be logged by the SDK. This should - // be used to inspect request made and responses received. - LogDebug -) - -// Debug Logging Sub Levels -const ( - // LogDebugWithSigning states that the SDK should log request signing and - // presigning events. This should be used to log the signing details of - // requests for debugging. Will also enable LogDebug. - LogDebugWithSigning LogLevelType = LogDebug | (1 << iota) - - // LogDebugWithHTTPBody states the SDK should log HTTP request and response - // HTTP bodys in addition to the headers and path. This should be used to - // see the body content of requests and responses made while using the SDK - // Will also enable LogDebug. - LogDebugWithHTTPBody - - // LogDebugWithRequestRetries states the SDK should log when service requests will - // be retried. This should be used to log when you want to log when service - // requests are being retried. Will also enable LogDebug. - LogDebugWithRequestRetries - - // LogDebugWithRequestErrors states the SDK should log when service requests fail - // to build, send, validate, or unmarshal. - LogDebugWithRequestErrors - - // LogDebugWithEventStreamBody states the SDK should log EventStream - // request and response bodys. This should be used to log the EventStream - // wire unmarshaled message content of requests and responses made while - // using the SDK Will also enable LogDebug. - LogDebugWithEventStreamBody - - // LogDebugWithDeprecated states the SDK should log details about deprecated functionality. - LogDebugWithDeprecated -) - -// A Logger is a minimalistic interface for the SDK to log messages to. Should -// be used to provide custom logging writers for the SDK to use. -type Logger interface { - Log(...interface{}) -} - -// A LoggerFunc is a convenience type to convert a function taking a variadic -// list of arguments and wrap it so the Logger interface can be used. -// -// Example: -// s3.New(sess, &aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) { -// fmt.Fprintln(os.Stdout, args...) -// })}) -type LoggerFunc func(...interface{}) - -// Log calls the wrapped function with the arguments provided -func (f LoggerFunc) Log(args ...interface{}) { - f(args...) -} - -// NewDefaultLogger returns a Logger which will write log messages to stdout, and -// use same formatting runes as the stdlib log.Logger -func NewDefaultLogger() Logger { - return &defaultLogger{ - logger: log.New(os.Stdout, "", log.LstdFlags), - } -} - -// A defaultLogger provides a minimalistic logger satisfying the Logger interface. -type defaultLogger struct { - logger *log.Logger -} - -// Log logs the parameters to the stdlib logger. See log.Println. -func (l defaultLogger) Log(args ...interface{}) { - l.logger.Println(args...) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go deleted file mode 100644 index 2ba3c56c1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go +++ /dev/null @@ -1,19 +0,0 @@ -package request - -import ( - "strings" -) - -func isErrConnectionReset(err error) bool { - if strings.Contains(err.Error(), "read: connection reset") { - return false - } - - if strings.Contains(err.Error(), "use of closed network connection") || - strings.Contains(err.Error(), "connection reset") || - strings.Contains(err.Error(), "broken pipe") { - return true - } - - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go deleted file mode 100644 index 9556332b6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go +++ /dev/null @@ -1,346 +0,0 @@ -package request - -import ( - "fmt" - "strings" -) - -// A Handlers provides a collection of request handlers for various -// stages of handling requests. -type Handlers struct { - Validate HandlerList - Build HandlerList - BuildStream HandlerList - Sign HandlerList - Send HandlerList - ValidateResponse HandlerList - Unmarshal HandlerList - UnmarshalStream HandlerList - UnmarshalMeta HandlerList - UnmarshalError HandlerList - Retry HandlerList - AfterRetry HandlerList - CompleteAttempt HandlerList - Complete HandlerList -} - -// Copy returns a copy of this handler's lists. -func (h *Handlers) Copy() Handlers { - return Handlers{ - Validate: h.Validate.copy(), - Build: h.Build.copy(), - BuildStream: h.BuildStream.copy(), - Sign: h.Sign.copy(), - Send: h.Send.copy(), - ValidateResponse: h.ValidateResponse.copy(), - Unmarshal: h.Unmarshal.copy(), - UnmarshalStream: h.UnmarshalStream.copy(), - UnmarshalError: h.UnmarshalError.copy(), - UnmarshalMeta: h.UnmarshalMeta.copy(), - Retry: h.Retry.copy(), - AfterRetry: h.AfterRetry.copy(), - CompleteAttempt: h.CompleteAttempt.copy(), - Complete: h.Complete.copy(), - } -} - -// Clear removes callback functions for all handlers. -func (h *Handlers) Clear() { - h.Validate.Clear() - h.Build.Clear() - h.BuildStream.Clear() - h.Send.Clear() - h.Sign.Clear() - h.Unmarshal.Clear() - h.UnmarshalStream.Clear() - h.UnmarshalMeta.Clear() - h.UnmarshalError.Clear() - h.ValidateResponse.Clear() - h.Retry.Clear() - h.AfterRetry.Clear() - h.CompleteAttempt.Clear() - h.Complete.Clear() -} - -// IsEmpty returns if there are no handlers in any of the handlerlists. -func (h *Handlers) IsEmpty() bool { - if h.Validate.Len() != 0 { - return false - } - if h.Build.Len() != 0 { - return false - } - if h.BuildStream.Len() != 0 { - return false - } - if h.Send.Len() != 0 { - return false - } - if h.Sign.Len() != 0 { - return false - } - if h.Unmarshal.Len() != 0 { - return false - } - if h.UnmarshalStream.Len() != 0 { - return false - } - if h.UnmarshalMeta.Len() != 0 { - return false - } - if h.UnmarshalError.Len() != 0 { - return false - } - if h.ValidateResponse.Len() != 0 { - return false - } - if h.Retry.Len() != 0 { - return false - } - if h.AfterRetry.Len() != 0 { - return false - } - if h.CompleteAttempt.Len() != 0 { - return false - } - if h.Complete.Len() != 0 { - return false - } - - return true -} - -// A HandlerListRunItem represents an entry in the HandlerList which -// is being run. -type HandlerListRunItem struct { - Index int - Handler NamedHandler - Request *Request -} - -// A HandlerList manages zero or more handlers in a list. -type HandlerList struct { - list []NamedHandler - - // Called after each request handler in the list is called. If set - // and the func returns true the HandlerList will continue to iterate - // over the request handlers. If false is returned the HandlerList - // will stop iterating. - // - // Should be used if extra logic to be performed between each handler - // in the list. This can be used to terminate a list's iteration - // based on a condition such as error like, HandlerListStopOnError. - // Or for logging like HandlerListLogItem. - AfterEachFn func(item HandlerListRunItem) bool -} - -// A NamedHandler is a struct that contains a name and function callback. -type NamedHandler struct { - Name string - Fn func(*Request) -} - -// copy creates a copy of the handler list. -func (l *HandlerList) copy() HandlerList { - n := HandlerList{ - AfterEachFn: l.AfterEachFn, - } - if len(l.list) == 0 { - return n - } - - n.list = append(make([]NamedHandler, 0, len(l.list)), l.list...) - return n -} - -// Clear clears the handler list. -func (l *HandlerList) Clear() { - l.list = l.list[0:0] -} - -// Len returns the number of handlers in the list. -func (l *HandlerList) Len() int { - return len(l.list) -} - -// PushBack pushes handler f to the back of the handler list. -func (l *HandlerList) PushBack(f func(*Request)) { - l.PushBackNamed(NamedHandler{"__anonymous", f}) -} - -// PushBackNamed pushes named handler f to the back of the handler list. -func (l *HandlerList) PushBackNamed(n NamedHandler) { - if cap(l.list) == 0 { - l.list = make([]NamedHandler, 0, 5) - } - l.list = append(l.list, n) -} - -// PushFront pushes handler f to the front of the handler list. -func (l *HandlerList) PushFront(f func(*Request)) { - l.PushFrontNamed(NamedHandler{"__anonymous", f}) -} - -// PushFrontNamed pushes named handler f to the front of the handler list. -func (l *HandlerList) PushFrontNamed(n NamedHandler) { - if cap(l.list) == len(l.list) { - // Allocating new list required - l.list = append([]NamedHandler{n}, l.list...) - } else { - // Enough room to prepend into list. - l.list = append(l.list, NamedHandler{}) - copy(l.list[1:], l.list) - l.list[0] = n - } -} - -// Remove removes a NamedHandler n -func (l *HandlerList) Remove(n NamedHandler) { - l.RemoveByName(n.Name) -} - -// RemoveByName removes a NamedHandler by name. -func (l *HandlerList) RemoveByName(name string) { - for i := 0; i < len(l.list); i++ { - m := l.list[i] - if m.Name == name { - // Shift array preventing creating new arrays - copy(l.list[i:], l.list[i+1:]) - l.list[len(l.list)-1] = NamedHandler{} - l.list = l.list[:len(l.list)-1] - - // decrement list so next check to length is correct - i-- - } - } -} - -// SwapNamed will swap out any existing handlers with the same name as the -// passed in NamedHandler returning true if handlers were swapped. False is -// returned otherwise. -func (l *HandlerList) SwapNamed(n NamedHandler) (swapped bool) { - for i := 0; i < len(l.list); i++ { - if l.list[i].Name == n.Name { - l.list[i].Fn = n.Fn - swapped = true - } - } - - return swapped -} - -// Swap will swap out all handlers matching the name passed in. The matched -// handlers will be swapped in. True is returned if the handlers were swapped. -func (l *HandlerList) Swap(name string, replace NamedHandler) bool { - var swapped bool - - for i := 0; i < len(l.list); i++ { - if l.list[i].Name == name { - l.list[i] = replace - swapped = true - } - } - - return swapped -} - -// SetBackNamed will replace the named handler if it exists in the handler list. -// If the handler does not exist the handler will be added to the end of the list. -func (l *HandlerList) SetBackNamed(n NamedHandler) { - if !l.SwapNamed(n) { - l.PushBackNamed(n) - } -} - -// SetFrontNamed will replace the named handler if it exists in the handler list. -// If the handler does not exist the handler will be added to the beginning of -// the list. -func (l *HandlerList) SetFrontNamed(n NamedHandler) { - if !l.SwapNamed(n) { - l.PushFrontNamed(n) - } -} - -// Run executes all handlers in the list with a given request object. -func (l *HandlerList) Run(r *Request) { - for i, h := range l.list { - h.Fn(r) - item := HandlerListRunItem{ - Index: i, Handler: h, Request: r, - } - if l.AfterEachFn != nil && !l.AfterEachFn(item) { - return - } - } -} - -// HandlerListLogItem logs the request handler and the state of the -// request's Error value. Always returns true to continue iterating -// request handlers in a HandlerList. -func HandlerListLogItem(item HandlerListRunItem) bool { - if item.Request.Config.Logger == nil { - return true - } - item.Request.Config.Logger.Log("DEBUG: RequestHandler", - item.Index, item.Handler.Name, item.Request.Error) - - return true -} - -// HandlerListStopOnError returns false to stop the HandlerList iterating -// over request handlers if Request.Error is not nil. True otherwise -// to continue iterating. -func HandlerListStopOnError(item HandlerListRunItem) bool { - return item.Request.Error == nil -} - -// WithAppendUserAgent will add a string to the user agent prefixed with a -// single white space. -func WithAppendUserAgent(s string) Option { - return func(r *Request) { - r.Handlers.Build.PushBack(func(r2 *Request) { - AddToUserAgent(r, s) - }) - } -} - -// MakeAddToUserAgentHandler will add the name/version pair to the User-Agent request -// header. If the extra parameters are provided they will be added as metadata to the -// name/version pair resulting in the following format. -// "name/version (extra0; extra1; ...)" -// The user agent part will be concatenated with this current request's user agent string. -func MakeAddToUserAgentHandler(name, version string, extra ...string) func(*Request) { - ua := fmt.Sprintf("%s/%s", name, version) - if len(extra) > 0 { - ua += fmt.Sprintf(" (%s)", strings.Join(extra, "; ")) - } - return func(r *Request) { - AddToUserAgent(r, ua) - } -} - -// MakeAddToUserAgentFreeFormHandler adds the input to the User-Agent request header. -// The input string will be concatenated with the current request's user agent string. -func MakeAddToUserAgentFreeFormHandler(s string) func(*Request) { - return func(r *Request) { - AddToUserAgent(r, s) - } -} - -// WithSetRequestHeaders updates the operation request's HTTP header to contain -// the header key value pairs provided. If the header key already exists in the -// request's HTTP header set, the existing value(s) will be replaced. -// -// Header keys added will be added as canonical format with title casing -// applied via http.Header.Set method. -func WithSetRequestHeaders(h map[string]string) Option { - return withRequestHeader(h).SetRequestHeaders -} - -type withRequestHeader map[string]string - -func (h withRequestHeader) SetRequestHeaders(r *Request) { - for k, v := range h { - r.HTTPRequest.Header.Set(k, v) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go deleted file mode 100644 index 79f79602b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go +++ /dev/null @@ -1,24 +0,0 @@ -package request - -import ( - "io" - "net/http" - "net/url" -) - -func copyHTTPRequest(r *http.Request, body io.ReadCloser) *http.Request { - req := new(http.Request) - *req = *r - req.URL = &url.URL{} - *req.URL = *r.URL - req.Body = body - - req.Header = http.Header{} - for k, v := range r.Header { - for _, vv := range v { - req.Header.Add(k, vv) - } - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go deleted file mode 100644 index 9370fa50c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go +++ /dev/null @@ -1,65 +0,0 @@ -package request - -import ( - "io" - "sync" - - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -// offsetReader is a thread-safe io.ReadCloser to prevent racing -// with retrying requests -type offsetReader struct { - buf io.ReadSeeker - lock sync.Mutex - closed bool -} - -func newOffsetReader(buf io.ReadSeeker, offset int64) (*offsetReader, error) { - reader := &offsetReader{} - _, err := buf.Seek(offset, sdkio.SeekStart) - if err != nil { - return nil, err - } - - reader.buf = buf - return reader, nil -} - -// Close will close the instance of the offset reader's access to -// the underlying io.ReadSeeker. -func (o *offsetReader) Close() error { - o.lock.Lock() - defer o.lock.Unlock() - o.closed = true - return nil -} - -// Read is a thread-safe read of the underlying io.ReadSeeker -func (o *offsetReader) Read(p []byte) (int, error) { - o.lock.Lock() - defer o.lock.Unlock() - - if o.closed { - return 0, io.EOF - } - - return o.buf.Read(p) -} - -// Seek is a thread-safe seeking operation. -func (o *offsetReader) Seek(offset int64, whence int) (int64, error) { - o.lock.Lock() - defer o.lock.Unlock() - - return o.buf.Seek(offset, whence) -} - -// CloseAndCopy will return a new offsetReader with a copy of the old buffer -// and close the old buffer. -func (o *offsetReader) CloseAndCopy(offset int64) (*offsetReader, error) { - if err := o.Close(); err != nil { - return nil, err - } - return newOffsetReader(o.buf, offset) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go deleted file mode 100644 index 636d9ec94..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go +++ /dev/null @@ -1,722 +0,0 @@ -package request - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -const ( - // ErrCodeSerialization is the serialization error code that is received - // during protocol unmarshaling. - ErrCodeSerialization = "SerializationError" - - // ErrCodeRead is an error that is returned during HTTP reads. - ErrCodeRead = "ReadError" - - // ErrCodeResponseTimeout is the connection timeout error that is received - // during body reads. - ErrCodeResponseTimeout = "ResponseTimeout" - - // ErrCodeInvalidPresignExpire is returned when the expire time provided to - // presign is invalid - ErrCodeInvalidPresignExpire = "InvalidPresignExpireError" - - // CanceledErrorCode is the error code that will be returned by an - // API request that was canceled. Requests given a aws.Context may - // return this error when canceled. - CanceledErrorCode = "RequestCanceled" - - // ErrCodeRequestError is an error preventing the SDK from continuing to - // process the request. - ErrCodeRequestError = "RequestError" -) - -// A Request is the service request to be made. -type Request struct { - Config aws.Config - ClientInfo metadata.ClientInfo - Handlers Handlers - - Retryer - AttemptTime time.Time - Time time.Time - Operation *Operation - HTTPRequest *http.Request - HTTPResponse *http.Response - Body io.ReadSeeker - streamingBody io.ReadCloser - BodyStart int64 // offset from beginning of Body that the request body starts - Params interface{} - Error error - Data interface{} - RequestID string - RetryCount int - Retryable *bool - RetryDelay time.Duration - NotHoist bool - SignedHeaderVals http.Header - LastSignedAt time.Time - DisableFollowRedirects bool - - // Additional API error codes that should be retried. IsErrorRetryable - // will consider these codes in addition to its built in cases. - RetryErrorCodes []string - - // Additional API error codes that should be retried with throttle backoff - // delay. IsErrorThrottle will consider these codes in addition to its - // built in cases. - ThrottleErrorCodes []string - - // A value greater than 0 instructs the request to be signed as Presigned URL - // You should not set this field directly. Instead use Request's - // Presign or PresignRequest methods. - ExpireTime time.Duration - - context aws.Context - - built bool - - // Need to persist an intermediate body between the input Body and HTTP - // request body because the HTTP Client's transport can maintain a reference - // to the HTTP request's body after the client has returned. This value is - // safe to use concurrently and wrap the input Body for each HTTP request. - safeBody *offsetReader -} - -// An Operation is the service API operation to be made. -type Operation struct { - Name string - HTTPMethod string - HTTPPath string - *Paginator - - BeforePresignFn func(r *Request) error -} - -// New returns a new Request pointer for the service API operation and -// parameters. -// -// A Retryer should be provided to direct how the request is retried. If -// Retryer is nil, a default no retry value will be used. You can use -// NoOpRetryer in the Client package to disable retry behavior directly. -// -// Params is any value of input parameters to be the request payload. -// Data is pointer value to an object which the request's response -// payload will be deserialized to. -func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers, - retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { - - if retryer == nil { - retryer = noOpRetryer{} - } - - method := operation.HTTPMethod - if method == "" { - method = "POST" - } - - httpReq, _ := http.NewRequest(method, "", nil) - - var err error - httpReq.URL, err = url.Parse(clientInfo.Endpoint) - if err != nil { - httpReq.URL = &url.URL{} - err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err) - } - - if len(operation.HTTPPath) != 0 { - opHTTPPath := operation.HTTPPath - var opQueryString string - if idx := strings.Index(opHTTPPath, "?"); idx >= 0 { - opQueryString = opHTTPPath[idx+1:] - opHTTPPath = opHTTPPath[:idx] - } - - if strings.HasSuffix(httpReq.URL.Path, "/") && strings.HasPrefix(opHTTPPath, "/") { - opHTTPPath = opHTTPPath[1:] - } - httpReq.URL.Path += opHTTPPath - httpReq.URL.RawQuery = opQueryString - } - - r := &Request{ - Config: cfg, - ClientInfo: clientInfo, - Handlers: handlers.Copy(), - - Retryer: retryer, - Time: time.Now(), - ExpireTime: 0, - Operation: operation, - HTTPRequest: httpReq, - Body: nil, - Params: params, - Error: err, - Data: data, - } - r.SetBufferBody([]byte{}) - - return r -} - -// A Option is a functional option that can augment or modify a request when -// using a WithContext API operation method. -type Option func(*Request) - -// WithGetResponseHeader builds a request Option which will retrieve a single -// header value from the HTTP Response. If there are multiple values for the -// header key use WithGetResponseHeaders instead to access the http.Header -// map directly. The passed in val pointer must be non-nil. -// -// This Option can be used multiple times with a single API operation. -// -// var id2, versionID string -// svc.PutObjectWithContext(ctx, params, -// request.WithGetResponseHeader("x-amz-id-2", &id2), -// request.WithGetResponseHeader("x-amz-version-id", &versionID), -// ) -func WithGetResponseHeader(key string, val *string) Option { - return func(r *Request) { - r.Handlers.Complete.PushBack(func(req *Request) { - *val = req.HTTPResponse.Header.Get(key) - }) - } -} - -// WithGetResponseHeaders builds a request Option which will retrieve the -// headers from the HTTP response and assign them to the passed in headers -// variable. The passed in headers pointer must be non-nil. -// -// var headers http.Header -// svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers)) -func WithGetResponseHeaders(headers *http.Header) Option { - return func(r *Request) { - r.Handlers.Complete.PushBack(func(req *Request) { - *headers = req.HTTPResponse.Header - }) - } -} - -// WithLogLevel is a request option that will set the request to use a specific -// log level when the request is made. -// -// svc.PutObjectWithContext(ctx, params, request.WithLogLevel(aws.LogDebugWithHTTPBody) -func WithLogLevel(l aws.LogLevelType) Option { - return func(r *Request) { - r.Config.LogLevel = aws.LogLevel(l) - } -} - -// ApplyOptions will apply each option to the request calling them in the order -// the were provided. -func (r *Request) ApplyOptions(opts ...Option) { - for _, opt := range opts { - opt(r) - } -} - -// Context will always returns a non-nil context. If Request does not have a -// context aws.BackgroundContext will be returned. -func (r *Request) Context() aws.Context { - if r.context != nil { - return r.context - } - return aws.BackgroundContext() -} - -// SetContext adds a Context to the current request that can be used to cancel -// a in-flight request. The Context value must not be nil, or this method will -// panic. -// -// Unlike http.Request.WithContext, SetContext does not return a copy of the -// Request. It is not safe to use use a single Request value for multiple -// requests. A new Request should be created for each API operation request. -// -// Go 1.6 and below: -// The http.Request's Cancel field will be set to the Done() value of -// the context. This will overwrite the Cancel field's value. -// -// Go 1.7 and above: -// The http.Request.WithContext will be used to set the context on the underlying -// http.Request. This will create a shallow copy of the http.Request. The SDK -// may create sub contexts in the future for nested requests such as retries. -func (r *Request) SetContext(ctx aws.Context) { - if ctx == nil { - panic("context cannot be nil") - } - setRequestContext(r, ctx) -} - -// WillRetry returns if the request's can be retried. -func (r *Request) WillRetry() bool { - if !aws.IsReaderSeekable(r.Body) && r.HTTPRequest.Body != NoBody { - return false - } - return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() -} - -func fmtAttemptCount(retryCount, maxRetries int) string { - return fmt.Sprintf("attempt %v/%v", retryCount, maxRetries) -} - -// ParamsFilled returns if the request's parameters have been populated -// and the parameters are valid. False is returned if no parameters are -// provided or invalid. -func (r *Request) ParamsFilled() bool { - return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid() -} - -// DataFilled returns true if the request's data for response deserialization -// target has been set and is a valid. False is returned if data is not -// set, or is invalid. -func (r *Request) DataFilled() bool { - return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid() -} - -// SetBufferBody will set the request's body bytes that will be sent to -// the service API. -func (r *Request) SetBufferBody(buf []byte) { - r.SetReaderBody(bytes.NewReader(buf)) -} - -// SetStringBody sets the body of the request to be backed by a string. -func (r *Request) SetStringBody(s string) { - r.SetReaderBody(strings.NewReader(s)) -} - -// SetReaderBody will set the request's body reader. -func (r *Request) SetReaderBody(reader io.ReadSeeker) { - r.Body = reader - - if aws.IsReaderSeekable(reader) { - var err error - // Get the Bodies current offset so retries will start from the same - // initial position. - r.BodyStart, err = reader.Seek(0, sdkio.SeekCurrent) - if err != nil { - r.Error = awserr.New(ErrCodeSerialization, - "failed to determine start of request body", err) - return - } - } - r.ResetBody() -} - -// SetStreamingBody set the reader to be used for the request that will stream -// bytes to the server. Request's Body must not be set to any reader. -func (r *Request) SetStreamingBody(reader io.ReadCloser) { - r.streamingBody = reader - r.SetReaderBody(aws.ReadSeekCloser(reader)) -} - -// Presign returns the request's signed URL. Error will be returned -// if the signing fails. The expire parameter is only used for presigned Amazon -// S3 API requests. All other AWS services will use a fixed expiration -// time of 15 minutes. -// -// It is invalid to create a presigned URL with a expire duration 0 or less. An -// error is returned if expire duration is 0 or less. -func (r *Request) Presign(expire time.Duration) (string, error) { - r = r.copy() - - // Presign requires all headers be hoisted. There is no way to retrieve - // the signed headers not hoisted without this. Making the presigned URL - // useless. - r.NotHoist = false - - u, _, err := getPresignedURL(r, expire) - return u, err -} - -// PresignRequest behaves just like presign, with the addition of returning a -// set of headers that were signed. The expire parameter is only used for -// presigned Amazon S3 API requests. All other AWS services will use a fixed -// expiration time of 15 minutes. -// -// It is invalid to create a presigned URL with a expire duration 0 or less. An -// error is returned if expire duration is 0 or less. -// -// Returns the URL string for the API operation with signature in the query string, -// and the HTTP headers that were included in the signature. These headers must -// be included in any HTTP request made with the presigned URL. -// -// To prevent hoisting any headers to the query string set NotHoist to true on -// this Request value prior to calling PresignRequest. -func (r *Request) PresignRequest(expire time.Duration) (string, http.Header, error) { - r = r.copy() - return getPresignedURL(r, expire) -} - -// IsPresigned returns true if the request represents a presigned API url. -func (r *Request) IsPresigned() bool { - return r.ExpireTime != 0 -} - -func getPresignedURL(r *Request, expire time.Duration) (string, http.Header, error) { - if expire <= 0 { - return "", nil, awserr.New( - ErrCodeInvalidPresignExpire, - "presigned URL requires an expire duration greater than 0", - nil, - ) - } - - r.ExpireTime = expire - - if r.Operation.BeforePresignFn != nil { - if err := r.Operation.BeforePresignFn(r); err != nil { - return "", nil, err - } - } - - if err := r.Sign(); err != nil { - return "", nil, err - } - - return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil -} - -const ( - notRetrying = "not retrying" -) - -func debugLogReqError(r *Request, stage, retryStr string, err error) { - if !r.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) { - return - } - - r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v", - stage, r.ClientInfo.ServiceName, r.Operation.Name, retryStr, err)) -} - -// Build will build the request's object so it can be signed and sent -// to the service. Build will also validate all the request's parameters. -// Any additional build Handlers set on this request will be run -// in the order they were set. -// -// The request will only be built once. Multiple calls to build will have -// no effect. -// -// If any Validate or Build errors occur the build will stop and the error -// which occurred will be returned. -func (r *Request) Build() error { - if !r.built { - r.Handlers.Validate.Run(r) - if r.Error != nil { - debugLogReqError(r, "Validate Request", notRetrying, r.Error) - return r.Error - } - r.Handlers.Build.Run(r) - if r.Error != nil { - debugLogReqError(r, "Build Request", notRetrying, r.Error) - return r.Error - } - r.built = true - } - - return r.Error -} - -// Sign will sign the request, returning error if errors are encountered. -// -// Sign will build the request prior to signing. All Sign Handlers will -// be executed in the order they were set. -func (r *Request) Sign() error { - r.Build() - if r.Error != nil { - debugLogReqError(r, "Build Request", notRetrying, r.Error) - return r.Error - } - - SanitizeHostForHeader(r.HTTPRequest) - - r.Handlers.Sign.Run(r) - return r.Error -} - -func (r *Request) getNextRequestBody() (body io.ReadCloser, err error) { - if r.streamingBody != nil { - return r.streamingBody, nil - } - - if r.safeBody != nil { - r.safeBody.Close() - } - - r.safeBody, err = newOffsetReader(r.Body, r.BodyStart) - if err != nil { - return nil, awserr.New(ErrCodeSerialization, - "failed to get next request body reader", err) - } - - // Go 1.8 tightened and clarified the rules code needs to use when building - // requests with the http package. Go 1.8 removed the automatic detection - // of if the Request.Body was empty, or actually had bytes in it. The SDK - // always sets the Request.Body even if it is empty and should not actually - // be sent. This is incorrect. - // - // Go 1.8 did add a http.NoBody value that the SDK can use to tell the http - // client that the request really should be sent without a body. The - // Request.Body cannot be set to nil, which is preferable, because the - // field is exported and could introduce nil pointer dereferences for users - // of the SDK if they used that field. - // - // Related golang/go#18257 - l, err := aws.SeekerLen(r.Body) - if err != nil { - return nil, awserr.New(ErrCodeSerialization, - "failed to compute request body size", err) - } - - if l == 0 { - body = NoBody - } else if l > 0 { - body = r.safeBody - } else { - // Hack to prevent sending bodies for methods where the body - // should be ignored by the server. Sending bodies on these - // methods without an associated ContentLength will cause the - // request to socket timeout because the server does not handle - // Transfer-Encoding: chunked bodies for these methods. - // - // This would only happen if a aws.ReaderSeekerCloser was used with - // a io.Reader that was not also an io.Seeker, or did not implement - // Len() method. - switch r.Operation.HTTPMethod { - case "GET", "HEAD", "DELETE": - body = NoBody - default: - body = r.safeBody - } - } - - return body, nil -} - -// GetBody will return an io.ReadSeeker of the Request's underlying -// input body with a concurrency safe wrapper. -func (r *Request) GetBody() io.ReadSeeker { - return r.safeBody -} - -// Send will send the request, returning error if errors are encountered. -// -// Send will sign the request prior to sending. All Send Handlers will -// be executed in the order they were set. -// -// Canceling a request is non-deterministic. If a request has been canceled, -// then the transport will choose, randomly, one of the state channels during -// reads or getting the connection. -// -// readLoop() and getConn(req *Request, cm connectMethod) -// https://github.com/golang/go/blob/master/src/net/http/transport.go -// -// Send will not close the request.Request's body. -func (r *Request) Send() error { - defer func() { - // Ensure a non-nil HTTPResponse parameter is set to ensure handlers - // checking for HTTPResponse values, don't fail. - if r.HTTPResponse == nil { - r.HTTPResponse = &http.Response{ - Header: http.Header{}, - Body: ioutil.NopCloser(&bytes.Buffer{}), - } - } - // Regardless of success or failure of the request trigger the Complete - // request handlers. - r.Handlers.Complete.Run(r) - }() - - if err := r.Error; err != nil { - return err - } - - for { - r.Error = nil - r.AttemptTime = time.Now() - - if err := r.Sign(); err != nil { - debugLogReqError(r, "Sign Request", notRetrying, err) - return err - } - - if err := r.sendRequest(); err == nil { - return nil - } - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - - if r.Error != nil || !aws.BoolValue(r.Retryable) { - return r.Error - } - - if err := r.prepareRetry(); err != nil { - r.Error = err - return err - } - } -} - -func (r *Request) prepareRetry() error { - if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { - r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", - r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount)) - } - - // The previous http.Request will have a reference to the r.Body - // and the HTTP Client's Transport may still be reading from - // the request's body even though the Client's Do returned. - r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil) - r.ResetBody() - if err := r.Error; err != nil { - return awserr.New(ErrCodeSerialization, - "failed to prepare body for retry", err) - - } - - // Closing response body to ensure that no response body is leaked - // between retry attempts. - if r.HTTPResponse != nil && r.HTTPResponse.Body != nil { - r.HTTPResponse.Body.Close() - } - - return nil -} - -func (r *Request) sendRequest() (sendErr error) { - defer r.Handlers.CompleteAttempt.Run(r) - - r.Retryable = nil - r.Handlers.Send.Run(r) - if r.Error != nil { - debugLogReqError(r, "Send Request", - fmtAttemptCount(r.RetryCount, r.MaxRetries()), - r.Error) - return r.Error - } - - r.Handlers.UnmarshalMeta.Run(r) - r.Handlers.ValidateResponse.Run(r) - if r.Error != nil { - r.Handlers.UnmarshalError.Run(r) - debugLogReqError(r, "Validate Response", - fmtAttemptCount(r.RetryCount, r.MaxRetries()), - r.Error) - return r.Error - } - - r.Handlers.Unmarshal.Run(r) - if r.Error != nil { - debugLogReqError(r, "Unmarshal Response", - fmtAttemptCount(r.RetryCount, r.MaxRetries()), - r.Error) - return r.Error - } - - return nil -} - -// copy will copy a request which will allow for local manipulation of the -// request. -func (r *Request) copy() *Request { - req := &Request{} - *req = *r - req.Handlers = r.Handlers.Copy() - op := *r.Operation - req.Operation = &op - return req -} - -// AddToUserAgent adds the string to the end of the request's current user agent. -func AddToUserAgent(r *Request, s string) { - curUA := r.HTTPRequest.Header.Get("User-Agent") - if len(curUA) > 0 { - s = curUA + " " + s - } - r.HTTPRequest.Header.Set("User-Agent", s) -} - -// SanitizeHostForHeader removes default port from host and updates request.Host -func SanitizeHostForHeader(r *http.Request) { - host := getHost(r) - port := portOnly(host) - if port != "" && isDefaultPort(r.URL.Scheme, port) { - r.Host = stripPort(host) - } -} - -// Returns host from request -func getHost(r *http.Request) string { - if r.Host != "" { - return r.Host - } - - if r.URL == nil { - return "" - } - - return r.URL.Host -} - -// Hostname returns u.Host, without any port number. -// -// If Host is an IPv6 literal with a port number, Hostname returns the -// IPv6 literal without the square brackets. IPv6 literals may include -// a zone identifier. -// -// Copied from the Go 1.8 standard library (net/url) -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} - -// Port returns the port part of u.Host, without the leading colon. -// If u.Host doesn't contain a port, Port returns an empty string. -// -// Copied from the Go 1.8 standard library (net/url) -func portOnly(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return "" - } - if i := strings.Index(hostport, "]:"); i != -1 { - return hostport[i+len("]:"):] - } - if strings.Contains(hostport, "]") { - return "" - } - return hostport[colon+len(":"):] -} - -// Returns true if the specified URI is using the standard port -// (i.e. port 80 for HTTP URIs or 443 for HTTPS URIs) -func isDefaultPort(scheme, port string) bool { - if port == "" { - return true - } - - lowerCaseScheme := strings.ToLower(scheme) - if (lowerCaseScheme == "http" && port == "80") || (lowerCaseScheme == "https" && port == "443") { - return true - } - - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go deleted file mode 100644 index 5921b8ff2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go +++ /dev/null @@ -1,40 +0,0 @@ -//go:build !go1.8 -// +build !go1.8 - -package request - -import "io" - -// NoBody is an io.ReadCloser with no bytes. Read always returns EOF -// and Close always returns nil. It can be used in an outgoing client -// request to explicitly signal that a request has zero bytes. -// An alternative, however, is to simply set Request.Body to nil. -// -// Copy of Go 1.8 NoBody type from net/http/http.go -type noBody struct{} - -func (noBody) Read([]byte) (int, error) { return 0, io.EOF } -func (noBody) Close() error { return nil } -func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil } - -// NoBody is an empty reader that will trigger the Go HTTP client to not include -// and body in the HTTP request. -var NoBody = noBody{} - -// ResetBody rewinds the request body back to its starting position, and -// sets the HTTP Request body reference. When the body is read prior -// to being sent in the HTTP request it will need to be rewound. -// -// ResetBody will automatically be called by the SDK's build handler, but if -// the request is being used directly ResetBody must be called before the request -// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically -// call ResetBody. -func (r *Request) ResetBody() { - body, err := r.getNextRequestBody() - if err != nil { - r.Error = err - return - } - - r.HTTPRequest.Body = body -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go deleted file mode 100644 index ea643c9c4..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go +++ /dev/null @@ -1,37 +0,0 @@ -//go:build go1.8 -// +build go1.8 - -package request - -import ( - "net/http" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// NoBody is a http.NoBody reader instructing Go HTTP client to not include -// and body in the HTTP request. -var NoBody = http.NoBody - -// ResetBody rewinds the request body back to its starting position, and -// sets the HTTP Request body reference. When the body is read prior -// to being sent in the HTTP request it will need to be rewound. -// -// ResetBody will automatically be called by the SDK's build handler, but if -// the request is being used directly ResetBody must be called before the request -// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically -// call ResetBody. -// -// Will also set the Go 1.8's http.Request.GetBody member to allow retrying -// PUT/POST redirects. -func (r *Request) ResetBody() { - body, err := r.getNextRequestBody() - if err != nil { - r.Error = awserr.New(ErrCodeSerialization, - "failed to reset request body", err) - return - } - - r.HTTPRequest.Body = body - r.HTTPRequest.GetBody = r.getNextRequestBody -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go deleted file mode 100644 index d8c505302..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build go1.7 -// +build go1.7 - -package request - -import "github.com/aws/aws-sdk-go/aws" - -// setContext updates the Request to use the passed in context for cancellation. -// Context will also be used for request retry delay. -// -// Creates shallow copy of the http.Request with the WithContext method. -func setRequestContext(r *Request, ctx aws.Context) { - r.context = ctx - r.HTTPRequest = r.HTTPRequest.WithContext(ctx) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go deleted file mode 100644 index 49a243ef2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build !go1.7 -// +build !go1.7 - -package request - -import "github.com/aws/aws-sdk-go/aws" - -// setContext updates the Request to use the passed in context for cancellation. -// Context will also be used for request retry delay. -// -// Creates shallow copy of the http.Request with the WithContext method. -func setRequestContext(r *Request, ctx aws.Context) { - r.context = ctx - r.HTTPRequest.Cancel = ctx.Done() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go deleted file mode 100644 index 64784e16f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go +++ /dev/null @@ -1,266 +0,0 @@ -package request - -import ( - "reflect" - "sync/atomic" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -// A Pagination provides paginating of SDK API operations which are paginatable. -// Generally you should not use this type directly, but use the "Pages" API -// operations method to automatically perform pagination for you. Such as, -// "S3.ListObjectsPages", and "S3.ListObjectsPagesWithContext" methods. -// -// Pagination differs from a Paginator type in that pagination is the type that -// does the pagination between API operations, and Paginator defines the -// configuration that will be used per page request. -// -// for p.Next() { -// data := p.Page().(*s3.ListObjectsOutput) -// // process the page's data -// // ... -// // break out of loop to stop fetching additional pages -// } -// -// return p.Err() -// -// See service client API operation Pages methods for examples how the SDK will -// use the Pagination type. -type Pagination struct { - // Function to return a Request value for each pagination request. - // Any configuration or handlers that need to be applied to the request - // prior to getting the next page should be done here before the request - // returned. - // - // NewRequest should always be built from the same API operations. It is - // undefined if different API operations are returned on subsequent calls. - NewRequest func() (*Request, error) - // EndPageOnSameToken, when enabled, will allow the paginator to stop on - // token that are the same as its previous tokens. - EndPageOnSameToken bool - - started bool - prevTokens []interface{} - nextTokens []interface{} - - err error - curPage interface{} -} - -// HasNextPage will return true if Pagination is able to determine that the API -// operation has additional pages. False will be returned if there are no more -// pages remaining. -// -// Will always return true if Next has not been called yet. -func (p *Pagination) HasNextPage() bool { - if !p.started { - return true - } - - hasNextPage := len(p.nextTokens) != 0 - if p.EndPageOnSameToken { - return hasNextPage && !awsutil.DeepEqual(p.nextTokens, p.prevTokens) - } - return hasNextPage -} - -// Err returns the error Pagination encountered when retrieving the next page. -func (p *Pagination) Err() error { - return p.err -} - -// Page returns the current page. Page should only be called after a successful -// call to Next. It is undefined what Page will return if Page is called after -// Next returns false. -func (p *Pagination) Page() interface{} { - return p.curPage -} - -// Next will attempt to retrieve the next page for the API operation. When a page -// is retrieved true will be returned. If the page cannot be retrieved, or there -// are no more pages false will be returned. -// -// Use the Page method to retrieve the current page data. The data will need -// to be cast to the API operation's output type. -// -// Use the Err method to determine if an error occurred if Page returns false. -func (p *Pagination) Next() bool { - if !p.HasNextPage() { - return false - } - - req, err := p.NewRequest() - if err != nil { - p.err = err - return false - } - - if p.started { - for i, intok := range req.Operation.InputTokens { - awsutil.SetValueAtPath(req.Params, intok, p.nextTokens[i]) - } - } - p.started = true - - err = req.Send() - if err != nil { - p.err = err - return false - } - - p.prevTokens = p.nextTokens - p.nextTokens = req.nextPageTokens() - p.curPage = req.Data - - return true -} - -// A Paginator is the configuration data that defines how an API operation -// should be paginated. This type is used by the API service models to define -// the generated pagination config for service APIs. -// -// The Pagination type is what provides iterating between pages of an API. It -// is only used to store the token metadata the SDK should use for performing -// pagination. -type Paginator struct { - InputTokens []string - OutputTokens []string - LimitToken string - TruncationToken string -} - -// nextPageTokens returns the tokens to use when asking for the next page of data. -func (r *Request) nextPageTokens() []interface{} { - if r.Operation.Paginator == nil { - return nil - } - if r.Operation.TruncationToken != "" { - tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken) - if len(tr) == 0 { - return nil - } - - switch v := tr[0].(type) { - case *bool: - if !aws.BoolValue(v) { - return nil - } - case bool: - if !v { - return nil - } - } - } - - tokens := []interface{}{} - tokenAdded := false - for _, outToken := range r.Operation.OutputTokens { - vs, _ := awsutil.ValuesAtPath(r.Data, outToken) - if len(vs) == 0 { - tokens = append(tokens, nil) - continue - } - v := vs[0] - - switch tv := v.(type) { - case *string: - if len(aws.StringValue(tv)) == 0 { - tokens = append(tokens, nil) - continue - } - case string: - if len(tv) == 0 { - tokens = append(tokens, nil) - continue - } - } - - tokenAdded = true - tokens = append(tokens, v) - } - if !tokenAdded { - return nil - } - - return tokens -} - -// Ensure a deprecated item is only logged once instead of each time its used. -func logDeprecatedf(logger aws.Logger, flag *int32, msg string) { - if logger == nil { - return - } - if atomic.CompareAndSwapInt32(flag, 0, 1) { - logger.Log(msg) - } -} - -var ( - logDeprecatedHasNextPage int32 - logDeprecatedNextPage int32 - logDeprecatedEachPage int32 -) - -// HasNextPage returns true if this request has more pages of data available. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) HasNextPage() bool { - logDeprecatedf(r.Config.Logger, &logDeprecatedHasNextPage, - "Request.HasNextPage deprecated. Use Pagination type for configurable pagination of API operations") - - return len(r.nextPageTokens()) > 0 -} - -// NextPage returns a new Request that can be executed to return the next -// page of result data. Call .Send() on this request to execute it. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) NextPage() *Request { - logDeprecatedf(r.Config.Logger, &logDeprecatedNextPage, - "Request.NextPage deprecated. Use Pagination type for configurable pagination of API operations") - - tokens := r.nextPageTokens() - if len(tokens) == 0 { - return nil - } - - data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface() - nr := New(r.Config, r.ClientInfo, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data) - for i, intok := range nr.Operation.InputTokens { - awsutil.SetValueAtPath(nr.Params, intok, tokens[i]) - } - return nr -} - -// EachPage iterates over each page of a paginated request object. The fn -// parameter should be a function with the following sample signature: -// -// func(page *T, lastPage bool) bool { -// return true // return false to stop iterating -// } -// -// Where "T" is the structure type matching the output structure of the given -// operation. For example, a request object generated by -// DynamoDB.ListTablesRequest() would expect to see dynamodb.ListTablesOutput -// as the structure "T". The lastPage value represents whether the page is -// the last page of data or not. The return value of this function should -// return true to keep iterating or false to stop. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error { - logDeprecatedf(r.Config.Logger, &logDeprecatedEachPage, - "Request.EachPage deprecated. Use Pagination type for configurable pagination of API operations") - - for page := r; page != nil; page = page.NextPage() { - if err := page.Send(); err != nil { - return err - } - if getNextPage := fn(page.Data, !page.HasNextPage()); !getNextPage { - return page.Error - } - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go deleted file mode 100644 index 3f0001f91..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go +++ /dev/null @@ -1,309 +0,0 @@ -package request - -import ( - "net" - "net/url" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// Retryer provides the interface drive the SDK's request retry behavior. The -// Retryer implementation is responsible for implementing exponential backoff, -// and determine if a request API error should be retried. -// -// client.DefaultRetryer is the SDK's default implementation of the Retryer. It -// uses the Request.IsErrorRetryable and Request.IsErrorThrottle methods to -// determine if the request is retried. -type Retryer interface { - // RetryRules return the retry delay that should be used by the SDK before - // making another request attempt for the failed request. - RetryRules(*Request) time.Duration - - // ShouldRetry returns if the failed request is retryable. - // - // Implementations may consider request attempt count when determining if a - // request is retryable, but the SDK will use MaxRetries to limit the - // number of attempts a request are made. - ShouldRetry(*Request) bool - - // MaxRetries is the number of times a request may be retried before - // failing. - MaxRetries() int -} - -// WithRetryer sets a Retryer value to the given Config returning the Config -// value for chaining. The value must not be nil. -func WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config { - if retryer == nil { - if cfg.Logger != nil { - cfg.Logger.Log("ERROR: Request.WithRetryer called with nil retryer. Replacing with retry disabled Retryer.") - } - retryer = noOpRetryer{} - } - cfg.Retryer = retryer - return cfg - -} - -// noOpRetryer is a internal no op retryer used when a request is created -// without a retryer. -// -// Provides a retryer that performs no retries. -// It should be used when we do not want retries to be performed. -type noOpRetryer struct{} - -// MaxRetries returns the number of maximum returns the service will use to make -// an individual API; For NoOpRetryer the MaxRetries will always be zero. -func (d noOpRetryer) MaxRetries() int { - return 0 -} - -// ShouldRetry will always return false for NoOpRetryer, as it should never retry. -func (d noOpRetryer) ShouldRetry(_ *Request) bool { - return false -} - -// RetryRules returns the delay duration before retrying this request again; -// since NoOpRetryer does not retry, RetryRules always returns 0. -func (d noOpRetryer) RetryRules(_ *Request) time.Duration { - return 0 -} - -// retryableCodes is a collection of service response codes which are retry-able -// without any further action. -var retryableCodes = map[string]struct{}{ - ErrCodeRequestError: {}, - "RequestTimeout": {}, - ErrCodeResponseTimeout: {}, - "RequestTimeoutException": {}, // Glacier's flavor of RequestTimeout -} - -var throttleCodes = map[string]struct{}{ - "ProvisionedThroughputExceededException": {}, - "ThrottledException": {}, // SNS, XRay, ResourceGroupsTagging API - "Throttling": {}, - "ThrottlingException": {}, - "RequestLimitExceeded": {}, - "RequestThrottled": {}, - "RequestThrottledException": {}, - "TooManyRequestsException": {}, // Lambda functions - "PriorRequestNotComplete": {}, // Route53 - "TransactionInProgressException": {}, - "EC2ThrottledException": {}, // EC2 -} - -// credsExpiredCodes is a collection of error codes which signify the credentials -// need to be refreshed. Expired tokens require refreshing of credentials, and -// resigning before the request can be retried. -var credsExpiredCodes = map[string]struct{}{ - "ExpiredToken": {}, - "ExpiredTokenException": {}, - "RequestExpired": {}, // EC2 Only -} - -func isCodeThrottle(code string) bool { - _, ok := throttleCodes[code] - return ok -} - -func isCodeRetryable(code string) bool { - if _, ok := retryableCodes[code]; ok { - return true - } - - return isCodeExpiredCreds(code) -} - -func isCodeExpiredCreds(code string) bool { - _, ok := credsExpiredCodes[code] - return ok -} - -var validParentCodes = map[string]struct{}{ - ErrCodeSerialization: {}, - ErrCodeRead: {}, -} - -func isNestedErrorRetryable(parentErr awserr.Error) bool { - if parentErr == nil { - return false - } - - if _, ok := validParentCodes[parentErr.Code()]; !ok { - return false - } - - err := parentErr.OrigErr() - if err == nil { - return false - } - - if aerr, ok := err.(awserr.Error); ok { - return isCodeRetryable(aerr.Code()) - } - - if t, ok := err.(temporary); ok { - return t.Temporary() || isErrConnectionReset(err) - } - - return isErrConnectionReset(err) -} - -// IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if error is nil. -func IsErrorRetryable(err error) bool { - if err == nil { - return false - } - return shouldRetryError(err) -} - -type temporary interface { - Temporary() bool -} - -func shouldRetryError(origErr error) bool { - switch err := origErr.(type) { - case awserr.Error: - if err.Code() == CanceledErrorCode { - return false - } - if isNestedErrorRetryable(err) { - return true - } - - origErr := err.OrigErr() - var shouldRetry bool - if origErr != nil { - shouldRetry = shouldRetryError(origErr) - if err.Code() == ErrCodeRequestError && !shouldRetry { - return false - } - } - if isCodeRetryable(err.Code()) { - return true - } - return shouldRetry - - case *url.Error: - if strings.Contains(err.Error(), "connection refused") { - // Refused connections should be retried as the service may not yet - // be running on the port. Go TCP dial considers refused - // connections as not temporary. - return true - } - // *url.Error only implements Temporary after golang 1.6 but since - // url.Error only wraps the error: - return shouldRetryError(err.Err) - - case temporary: - if netErr, ok := err.(*net.OpError); ok && netErr.Op == "dial" { - return true - } - // If the error is temporary, we want to allow continuation of the - // retry process - return err.Temporary() || isErrConnectionReset(origErr) - - case nil: - // `awserr.Error.OrigErr()` can be nil, meaning there was an error but - // because we don't know the cause, it is marked as retryable. See - // TestRequest4xxUnretryable for an example. - return true - - default: - switch err.Error() { - case "net/http: request canceled", - "net/http: request canceled while waiting for connection": - // known 1.5 error case when an http request is cancelled - return false - } - // here we don't know the error; so we allow a retry. - return true - } -} - -// IsErrorThrottle returns whether the error is to be throttled based on its code. -// Returns false if error is nil. -func IsErrorThrottle(err error) bool { - if aerr, ok := err.(awserr.Error); ok && aerr != nil { - return isCodeThrottle(aerr.Code()) - } - return false -} - -// IsErrorExpiredCreds returns whether the error code is a credential expiry -// error. Returns false if error is nil. -func IsErrorExpiredCreds(err error) bool { - if aerr, ok := err.(awserr.Error); ok && aerr != nil { - return isCodeExpiredCreds(aerr.Code()) - } - return false -} - -// IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorRetryable -func (r *Request) IsErrorRetryable() bool { - if isErrCode(r.Error, r.RetryErrorCodes) { - return true - } - - // HTTP response status code 501 should not be retried. - // 501 represents Not Implemented which means the request method is not - // supported by the server and cannot be handled. - if r.HTTPResponse != nil { - // HTTP response status code 500 represents internal server error and - // should be retried without any throttle. - if r.HTTPResponse.StatusCode == 500 { - return true - } - } - return IsErrorRetryable(r.Error) -} - -// IsErrorThrottle returns whether the error is to be throttled based on its -// code. Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorThrottle -func (r *Request) IsErrorThrottle() bool { - if isErrCode(r.Error, r.ThrottleErrorCodes) { - return true - } - - if r.HTTPResponse != nil { - switch r.HTTPResponse.StatusCode { - case - 429, // error caused due to too many requests - 502, // Bad Gateway error should be throttled - 503, // caused when service is unavailable - 504: // error occurred due to gateway timeout - return true - } - } - - return IsErrorThrottle(r.Error) -} - -func isErrCode(err error, codes []string) bool { - if aerr, ok := err.(awserr.Error); ok && aerr != nil { - for _, code := range codes { - if code == aerr.Code() { - return true - } - } - } - - return false -} - -// IsErrorExpired returns whether the error code is a credential expiry error. -// Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorExpiredCreds -func (r *Request) IsErrorExpired() bool { - return IsErrorExpiredCreds(r.Error) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go deleted file mode 100644 index 09a44eb98..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go +++ /dev/null @@ -1,94 +0,0 @@ -package request - -import ( - "io" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var timeoutErr = awserr.New( - ErrCodeResponseTimeout, - "read on body has reached the timeout limit", - nil, -) - -type readResult struct { - n int - err error -} - -// timeoutReadCloser will handle body reads that take too long. -// We will return a ErrReadTimeout error if a timeout occurs. -type timeoutReadCloser struct { - reader io.ReadCloser - duration time.Duration -} - -// Read will spin off a goroutine to call the reader's Read method. We will -// select on the timer's channel or the read's channel. Whoever completes first -// will be returned. -func (r *timeoutReadCloser) Read(b []byte) (int, error) { - timer := time.NewTimer(r.duration) - c := make(chan readResult, 1) - - go func() { - n, err := r.reader.Read(b) - timer.Stop() - c <- readResult{n: n, err: err} - }() - - select { - case data := <-c: - return data.n, data.err - case <-timer.C: - return 0, timeoutErr - } -} - -func (r *timeoutReadCloser) Close() error { - return r.reader.Close() -} - -const ( - // HandlerResponseTimeout is what we use to signify the name of the - // response timeout handler. - HandlerResponseTimeout = "ResponseTimeoutHandler" -) - -// adaptToResponseTimeoutError is a handler that will replace any top level error -// to a ErrCodeResponseTimeout, if its child is that. -func adaptToResponseTimeoutError(req *Request) { - if err, ok := req.Error.(awserr.Error); ok { - aerr, ok := err.OrigErr().(awserr.Error) - if ok && aerr.Code() == ErrCodeResponseTimeout { - req.Error = aerr - } - } -} - -// WithResponseReadTimeout is a request option that will wrap the body in a timeout read closer. -// This will allow for per read timeouts. If a timeout occurred, we will return the -// ErrCodeResponseTimeout. -// -// svc.PutObjectWithContext(ctx, params, request.WithTimeoutReadCloser(30 * time.Second) -func WithResponseReadTimeout(duration time.Duration) Option { - return func(r *Request) { - - var timeoutHandler = NamedHandler{ - HandlerResponseTimeout, - func(req *Request) { - req.HTTPResponse.Body = &timeoutReadCloser{ - reader: req.HTTPResponse.Body, - duration: duration, - } - }} - - // remove the handler so we are not stomping over any new durations. - r.Handlers.Send.RemoveByName(HandlerResponseTimeout) - r.Handlers.Send.PushBackNamed(timeoutHandler) - - r.Handlers.Unmarshal.PushBack(adaptToResponseTimeoutError) - r.Handlers.UnmarshalError.PushBack(adaptToResponseTimeoutError) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go b/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go deleted file mode 100644 index 8630683f3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go +++ /dev/null @@ -1,286 +0,0 @@ -package request - -import ( - "bytes" - "fmt" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -const ( - // InvalidParameterErrCode is the error code for invalid parameters errors - InvalidParameterErrCode = "InvalidParameter" - // ParamRequiredErrCode is the error code for required parameter errors - ParamRequiredErrCode = "ParamRequiredError" - // ParamMinValueErrCode is the error code for fields with too low of a - // number value. - ParamMinValueErrCode = "ParamMinValueError" - // ParamMinLenErrCode is the error code for fields without enough elements. - ParamMinLenErrCode = "ParamMinLenError" - // ParamMaxLenErrCode is the error code for value being too long. - ParamMaxLenErrCode = "ParamMaxLenError" - - // ParamFormatErrCode is the error code for a field with invalid - // format or characters. - ParamFormatErrCode = "ParamFormatInvalidError" -) - -// Validator provides a way for types to perform validation logic on their -// input values that external code can use to determine if a type's values -// are valid. -type Validator interface { - Validate() error -} - -// An ErrInvalidParams provides wrapping of invalid parameter errors found when -// validating API operation input parameters. -type ErrInvalidParams struct { - // Context is the base context of the invalid parameter group. - Context string - errs []ErrInvalidParam -} - -// Add adds a new invalid parameter error to the collection of invalid -// parameters. The context of the invalid parameter will be updated to reflect -// this collection. -func (e *ErrInvalidParams) Add(err ErrInvalidParam) { - err.SetContext(e.Context) - e.errs = append(e.errs, err) -} - -// AddNested adds the invalid parameter errors from another ErrInvalidParams -// value into this collection. The nested errors will have their nested context -// updated and base context to reflect the merging. -// -// Use for nested validations errors. -func (e *ErrInvalidParams) AddNested(nestedCtx string, nested ErrInvalidParams) { - for _, err := range nested.errs { - err.SetContext(e.Context) - err.AddNestedContext(nestedCtx) - e.errs = append(e.errs, err) - } -} - -// Len returns the number of invalid parameter errors -func (e ErrInvalidParams) Len() int { - return len(e.errs) -} - -// Code returns the code of the error -func (e ErrInvalidParams) Code() string { - return InvalidParameterErrCode -} - -// Message returns the message of the error -func (e ErrInvalidParams) Message() string { - return fmt.Sprintf("%d validation error(s) found.", len(e.errs)) -} - -// Error returns the string formatted form of the invalid parameters. -func (e ErrInvalidParams) Error() string { - w := &bytes.Buffer{} - fmt.Fprintf(w, "%s: %s\n", e.Code(), e.Message()) - - for _, err := range e.errs { - fmt.Fprintf(w, "- %s\n", err.Message()) - } - - return w.String() -} - -// OrigErr returns the invalid parameters as a awserr.BatchedErrors value -func (e ErrInvalidParams) OrigErr() error { - return awserr.NewBatchError( - InvalidParameterErrCode, e.Message(), e.OrigErrs()) -} - -// OrigErrs returns a slice of the invalid parameters -func (e ErrInvalidParams) OrigErrs() []error { - errs := make([]error, len(e.errs)) - for i := 0; i < len(errs); i++ { - errs[i] = e.errs[i] - } - - return errs -} - -// An ErrInvalidParam represents an invalid parameter error type. -type ErrInvalidParam interface { - awserr.Error - - // Field name the error occurred on. - Field() string - - // SetContext updates the context of the error. - SetContext(string) - - // AddNestedContext updates the error's context to include a nested level. - AddNestedContext(string) -} - -type errInvalidParam struct { - context string - nestedContext string - field string - code string - msg string -} - -// Code returns the error code for the type of invalid parameter. -func (e *errInvalidParam) Code() string { - return e.code -} - -// Message returns the reason the parameter was invalid, and its context. -func (e *errInvalidParam) Message() string { - return fmt.Sprintf("%s, %s.", e.msg, e.Field()) -} - -// Error returns the string version of the invalid parameter error. -func (e *errInvalidParam) Error() string { - return fmt.Sprintf("%s: %s", e.code, e.Message()) -} - -// OrigErr returns nil, Implemented for awserr.Error interface. -func (e *errInvalidParam) OrigErr() error { - return nil -} - -// Field Returns the field and context the error occurred. -func (e *errInvalidParam) Field() string { - field := e.context - if len(field) > 0 { - field += "." - } - if len(e.nestedContext) > 0 { - field += fmt.Sprintf("%s.", e.nestedContext) - } - field += e.field - - return field -} - -// SetContext updates the base context of the error. -func (e *errInvalidParam) SetContext(ctx string) { - e.context = ctx -} - -// AddNestedContext prepends a context to the field's path. -func (e *errInvalidParam) AddNestedContext(ctx string) { - if len(e.nestedContext) == 0 { - e.nestedContext = ctx - } else { - e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext) - } - -} - -// An ErrParamRequired represents an required parameter error. -type ErrParamRequired struct { - errInvalidParam -} - -// NewErrParamRequired creates a new required parameter error. -func NewErrParamRequired(field string) *ErrParamRequired { - return &ErrParamRequired{ - errInvalidParam{ - code: ParamRequiredErrCode, - field: field, - msg: fmt.Sprintf("missing required field"), - }, - } -} - -// An ErrParamMinValue represents a minimum value parameter error. -type ErrParamMinValue struct { - errInvalidParam - min float64 -} - -// NewErrParamMinValue creates a new minimum value parameter error. -func NewErrParamMinValue(field string, min float64) *ErrParamMinValue { - return &ErrParamMinValue{ - errInvalidParam: errInvalidParam{ - code: ParamMinValueErrCode, - field: field, - msg: fmt.Sprintf("minimum field value of %v", min), - }, - min: min, - } -} - -// MinValue returns the field's require minimum value. -// -// float64 is returned for both int and float min values. -func (e *ErrParamMinValue) MinValue() float64 { - return e.min -} - -// An ErrParamMinLen represents a minimum length parameter error. -type ErrParamMinLen struct { - errInvalidParam - min int -} - -// NewErrParamMinLen creates a new minimum length parameter error. -func NewErrParamMinLen(field string, min int) *ErrParamMinLen { - return &ErrParamMinLen{ - errInvalidParam: errInvalidParam{ - code: ParamMinLenErrCode, - field: field, - msg: fmt.Sprintf("minimum field size of %v", min), - }, - min: min, - } -} - -// MinLen returns the field's required minimum length. -func (e *ErrParamMinLen) MinLen() int { - return e.min -} - -// An ErrParamMaxLen represents a maximum length parameter error. -type ErrParamMaxLen struct { - errInvalidParam - max int -} - -// NewErrParamMaxLen creates a new maximum length parameter error. -func NewErrParamMaxLen(field string, max int, value string) *ErrParamMaxLen { - return &ErrParamMaxLen{ - errInvalidParam: errInvalidParam{ - code: ParamMaxLenErrCode, - field: field, - msg: fmt.Sprintf("maximum size of %v, %v", max, value), - }, - max: max, - } -} - -// MaxLen returns the field's required minimum length. -func (e *ErrParamMaxLen) MaxLen() int { - return e.max -} - -// An ErrParamFormat represents a invalid format parameter error. -type ErrParamFormat struct { - errInvalidParam - format string -} - -// NewErrParamFormat creates a new invalid format parameter error. -func NewErrParamFormat(field string, format, value string) *ErrParamFormat { - return &ErrParamFormat{ - errInvalidParam: errInvalidParam{ - code: ParamFormatErrCode, - field: field, - msg: fmt.Sprintf("format %v, %v", format, value), - }, - format: format, - } -} - -// Format returns the field's required format. -func (e *ErrParamFormat) Format() string { - return e.format -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go deleted file mode 100644 index 992ed0464..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go +++ /dev/null @@ -1,304 +0,0 @@ -package request - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -// WaiterResourceNotReadyErrorCode is the error code returned by a waiter when -// the waiter's max attempts have been exhausted. -const WaiterResourceNotReadyErrorCode = "ResourceNotReady" - -// A WaiterOption is a function that will update the Waiter value's fields to -// configure the waiter. -type WaiterOption func(*Waiter) - -// WithWaiterMaxAttempts returns the maximum number of times the waiter should -// attempt to check the resource for the target state. -func WithWaiterMaxAttempts(max int) WaiterOption { - return func(w *Waiter) { - w.MaxAttempts = max - } -} - -// WaiterDelay will return a delay the waiter should pause between attempts to -// check the resource state. The passed in attempt is the number of times the -// Waiter has checked the resource state. -// -// Attempt is the number of attempts the Waiter has made checking the resource -// state. -type WaiterDelay func(attempt int) time.Duration - -// ConstantWaiterDelay returns a WaiterDelay that will always return a constant -// delay the waiter should use between attempts. It ignores the number of -// attempts made. -func ConstantWaiterDelay(delay time.Duration) WaiterDelay { - return func(attempt int) time.Duration { - return delay - } -} - -// WithWaiterDelay will set the Waiter to use the WaiterDelay passed in. -func WithWaiterDelay(delayer WaiterDelay) WaiterOption { - return func(w *Waiter) { - w.Delay = delayer - } -} - -// WithWaiterLogger returns a waiter option to set the logger a waiter -// should use to log warnings and errors to. -func WithWaiterLogger(logger aws.Logger) WaiterOption { - return func(w *Waiter) { - w.Logger = logger - } -} - -// WithWaiterRequestOptions returns a waiter option setting the request -// options for each request the waiter makes. Appends to waiter's request -// options already set. -func WithWaiterRequestOptions(opts ...Option) WaiterOption { - return func(w *Waiter) { - w.RequestOptions = append(w.RequestOptions, opts...) - } -} - -// A Waiter provides the functionality to perform a blocking call which will -// wait for a resource state to be satisfied by a service. -// -// This type should not be used directly. The API operations provided in the -// service packages prefixed with "WaitUntil" should be used instead. -type Waiter struct { - Name string - Acceptors []WaiterAcceptor - Logger aws.Logger - - MaxAttempts int - Delay WaiterDelay - - RequestOptions []Option - NewRequest func([]Option) (*Request, error) - SleepWithContext func(aws.Context, time.Duration) error -} - -// ApplyOptions updates the waiter with the list of waiter options provided. -func (w *Waiter) ApplyOptions(opts ...WaiterOption) { - for _, fn := range opts { - fn(w) - } -} - -// WaiterState are states the waiter uses based on WaiterAcceptor definitions -// to identify if the resource state the waiter is waiting on has occurred. -type WaiterState int - -// String returns the string representation of the waiter state. -func (s WaiterState) String() string { - switch s { - case SuccessWaiterState: - return "success" - case FailureWaiterState: - return "failure" - case RetryWaiterState: - return "retry" - default: - return "unknown waiter state" - } -} - -// States the waiter acceptors will use to identify target resource states. -const ( - SuccessWaiterState WaiterState = iota // waiter successful - FailureWaiterState // waiter failed - RetryWaiterState // waiter needs to be retried -) - -// WaiterMatchMode is the mode that the waiter will use to match the WaiterAcceptor -// definition's Expected attribute. -type WaiterMatchMode int - -// Modes the waiter will use when inspecting API response to identify target -// resource states. -const ( - PathAllWaiterMatch WaiterMatchMode = iota // match on all paths - PathWaiterMatch // match on specific path - PathAnyWaiterMatch // match on any path - PathListWaiterMatch // match on list of paths - StatusWaiterMatch // match on status code - ErrorWaiterMatch // match on error -) - -// String returns the string representation of the waiter match mode. -func (m WaiterMatchMode) String() string { - switch m { - case PathAllWaiterMatch: - return "pathAll" - case PathWaiterMatch: - return "path" - case PathAnyWaiterMatch: - return "pathAny" - case PathListWaiterMatch: - return "pathList" - case StatusWaiterMatch: - return "status" - case ErrorWaiterMatch: - return "error" - default: - return "unknown waiter match mode" - } -} - -// WaitWithContext will make requests for the API operation using NewRequest to -// build API requests. The request's response will be compared against the -// Waiter's Acceptors to determine the successful state of the resource the -// waiter is inspecting. -// -// The passed in context must not be nil. If it is nil a panic will occur. The -// Context will be used to cancel the waiter's pending requests and retry delays. -// Use aws.BackgroundContext if no context is available. -// -// The waiter will continue until the target state defined by the Acceptors, -// or the max attempts expires. -// -// Will return the WaiterResourceNotReadyErrorCode error code if the waiter's -// retryer ShouldRetry returns false. This normally will happen when the max -// wait attempts expires. -func (w Waiter) WaitWithContext(ctx aws.Context) error { - - for attempt := 1; ; attempt++ { - req, err := w.NewRequest(w.RequestOptions) - if err != nil { - waiterLogf(w.Logger, "unable to create request %v", err) - return err - } - req.Handlers.Build.PushBack(MakeAddToUserAgentFreeFormHandler("Waiter")) - err = req.Send() - - // See if any of the acceptors match the request's response, or error - for _, a := range w.Acceptors { - if matched, matchErr := a.match(w.Name, w.Logger, req, err); matched { - return matchErr - } - } - - // The Waiter should only check the resource state MaxAttempts times - // This is here instead of in the for loop above to prevent delaying - // unnecessary when the waiter will not retry. - if attempt == w.MaxAttempts { - break - } - - // Delay to wait before inspecting the resource again - delay := w.Delay(attempt) - if sleepFn := req.Config.SleepDelay; sleepFn != nil { - // Support SleepDelay for backwards compatibility and testing - sleepFn(delay) - } else { - sleepCtxFn := w.SleepWithContext - if sleepCtxFn == nil { - sleepCtxFn = aws.SleepWithContext - } - - if err := sleepCtxFn(ctx, delay); err != nil { - return awserr.New(CanceledErrorCode, "waiter context canceled", err) - } - } - } - - return awserr.New(WaiterResourceNotReadyErrorCode, "exceeded wait attempts", nil) -} - -// A WaiterAcceptor provides the information needed to wait for an API operation -// to complete. -type WaiterAcceptor struct { - State WaiterState - Matcher WaiterMatchMode - Argument string - Expected interface{} -} - -// match returns if the acceptor found a match with the passed in request -// or error. True is returned if the acceptor made a match, error is returned -// if there was an error attempting to perform the match. -func (a *WaiterAcceptor) match(name string, l aws.Logger, req *Request, err error) (bool, error) { - result := false - var vals []interface{} - - switch a.Matcher { - case PathAllWaiterMatch, PathWaiterMatch: - // Require all matches to be equal for result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - if len(vals) == 0 { - break - } - result = true - for _, val := range vals { - if !awsutil.DeepEqual(val, a.Expected) { - result = false - break - } - } - case PathAnyWaiterMatch: - // Only a single match needs to equal for the result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - for _, val := range vals { - if awsutil.DeepEqual(val, a.Expected) { - result = true - break - } - } - case PathListWaiterMatch: - // ignored matcher - case StatusWaiterMatch: - s := a.Expected.(int) - result = s == req.HTTPResponse.StatusCode - case ErrorWaiterMatch: - switch ex := a.Expected.(type) { - case string: - if aerr, ok := err.(awserr.Error); ok { - result = aerr.Code() == ex - } - case bool: - if ex { - result = err != nil - } else { - result = err == nil - } - } - default: - waiterLogf(l, "WARNING: Waiter %s encountered unexpected matcher: %s", - name, a.Matcher) - } - - if !result { - // If there was no matching result found there is nothing more to do - // for this response, retry the request. - return false, nil - } - - switch a.State { - case SuccessWaiterState: - // waiter completed - return true, nil - case FailureWaiterState: - // Waiter failure state triggered - return true, awserr.New(WaiterResourceNotReadyErrorCode, - "failed waiting for successful resource state", err) - case RetryWaiterState: - // clear the error and retry the operation - return false, nil - default: - waiterLogf(l, "WARNING: Waiter %s encountered unexpected state: %s", - name, a.State) - return false, nil - } -} - -func waiterLogf(logger aws.Logger, msg string, args ...interface{}) { - if logger != nil { - logger.Log(fmt.Sprintf(msg, args...)) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/session/credentials.go deleted file mode 100644 index ea8e35376..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/credentials.go +++ /dev/null @@ -1,333 +0,0 @@ -package session - -import ( - "fmt" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/processcreds" - "github.com/aws/aws-sdk-go/aws/credentials/ssocreds" - "github.com/aws/aws-sdk-go/aws/credentials/stscreds" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/shareddefaults" - "github.com/aws/aws-sdk-go/service/ssooidc" - "github.com/aws/aws-sdk-go/service/sts" -) - -// CredentialsProviderOptions specifies additional options for configuring -// credentials providers. -type CredentialsProviderOptions struct { - // WebIdentityRoleProviderOptions configures a WebIdentityRoleProvider, - // such as setting its ExpiryWindow. - WebIdentityRoleProviderOptions func(*stscreds.WebIdentityRoleProvider) - - // ProcessProviderOptions configures a ProcessProvider, - // such as setting its Timeout. - ProcessProviderOptions func(*processcreds.ProcessProvider) -} - -func resolveCredentials(cfg *aws.Config, - envCfg envConfig, sharedCfg sharedConfig, - handlers request.Handlers, - sessOpts Options, -) (*credentials.Credentials, error) { - - switch { - case len(sessOpts.Profile) != 0: - // User explicitly provided a Profile in the session's configuration - // so load that profile from shared config first. - // Github(aws/aws-sdk-go#2727) - return resolveCredsFromProfile(cfg, envCfg, sharedCfg, handlers, sessOpts) - - case envCfg.Creds.HasKeys(): - // Environment credentials - return credentials.NewStaticCredentialsFromCreds(envCfg.Creds), nil - - case len(envCfg.WebIdentityTokenFilePath) != 0: - // Web identity token from environment, RoleARN required to also be - // set. - return assumeWebIdentity(cfg, handlers, - envCfg.WebIdentityTokenFilePath, - envCfg.RoleARN, - envCfg.RoleSessionName, - sessOpts.CredentialsProviderOptions, - ) - - default: - // Fallback to the "default" credential resolution chain. - return resolveCredsFromProfile(cfg, envCfg, sharedCfg, handlers, sessOpts) - } -} - -// WebIdentityEmptyRoleARNErr will occur if 'AWS_WEB_IDENTITY_TOKEN_FILE' was set but -// 'AWS_ROLE_ARN' was not set. -var WebIdentityEmptyRoleARNErr = awserr.New(stscreds.ErrCodeWebIdentity, "role ARN is not set", nil) - -// WebIdentityEmptyTokenFilePathErr will occur if 'AWS_ROLE_ARN' was set but -// 'AWS_WEB_IDENTITY_TOKEN_FILE' was not set. -var WebIdentityEmptyTokenFilePathErr = awserr.New(stscreds.ErrCodeWebIdentity, "token file path is not set", nil) - -func assumeWebIdentity(cfg *aws.Config, handlers request.Handlers, - filepath string, - roleARN, sessionName string, - credOptions *CredentialsProviderOptions, -) (*credentials.Credentials, error) { - - if len(filepath) == 0 { - return nil, WebIdentityEmptyTokenFilePathErr - } - - if len(roleARN) == 0 { - return nil, WebIdentityEmptyRoleARNErr - } - - svc := sts.New(&Session{ - Config: cfg, - Handlers: handlers.Copy(), - }) - - var optFns []func(*stscreds.WebIdentityRoleProvider) - if credOptions != nil && credOptions.WebIdentityRoleProviderOptions != nil { - optFns = append(optFns, credOptions.WebIdentityRoleProviderOptions) - } - - p := stscreds.NewWebIdentityRoleProviderWithOptions(svc, roleARN, sessionName, stscreds.FetchTokenPath(filepath), optFns...) - return credentials.NewCredentials(p), nil -} - -func resolveCredsFromProfile(cfg *aws.Config, - envCfg envConfig, sharedCfg sharedConfig, - handlers request.Handlers, - sessOpts Options, -) (creds *credentials.Credentials, err error) { - - switch { - case sharedCfg.SourceProfile != nil: - // Assume IAM role with credentials source from a different profile. - creds, err = resolveCredsFromProfile(cfg, envCfg, - *sharedCfg.SourceProfile, handlers, sessOpts, - ) - - case sharedCfg.Creds.HasKeys(): - // Static Credentials from Shared Config/Credentials file. - creds = credentials.NewStaticCredentialsFromCreds( - sharedCfg.Creds, - ) - - case len(sharedCfg.CredentialSource) != 0: - creds, err = resolveCredsFromSource(cfg, envCfg, - sharedCfg, handlers, sessOpts, - ) - - case len(sharedCfg.WebIdentityTokenFile) != 0: - // Credentials from Assume Web Identity token require an IAM Role, and - // that roll will be assumed. May be wrapped with another assume role - // via SourceProfile. - return assumeWebIdentity(cfg, handlers, - sharedCfg.WebIdentityTokenFile, - sharedCfg.RoleARN, - sharedCfg.RoleSessionName, - sessOpts.CredentialsProviderOptions, - ) - - case sharedCfg.hasSSOConfiguration(): - creds, err = resolveSSOCredentials(cfg, sharedCfg, handlers) - - case len(sharedCfg.CredentialProcess) != 0: - // Get credentials from CredentialProcess - var optFns []func(*processcreds.ProcessProvider) - if sessOpts.CredentialsProviderOptions != nil && sessOpts.CredentialsProviderOptions.ProcessProviderOptions != nil { - optFns = append(optFns, sessOpts.CredentialsProviderOptions.ProcessProviderOptions) - } - creds = processcreds.NewCredentials(sharedCfg.CredentialProcess, optFns...) - - default: - // Fallback to default credentials provider, include mock errors for - // the credential chain so user can identify why credentials failed to - // be retrieved. - creds = credentials.NewCredentials(&credentials.ChainProvider{ - VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: []credentials.Provider{ - &credProviderError{ - Err: awserr.New("EnvAccessKeyNotFound", - "failed to find credentials in the environment.", nil), - }, - &credProviderError{ - Err: awserr.New("SharedCredsLoad", - fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil), - }, - defaults.RemoteCredProvider(*cfg, handlers), - }, - }) - } - if err != nil { - return nil, err - } - - if len(sharedCfg.RoleARN) > 0 { - cfgCp := *cfg - cfgCp.Credentials = creds - return credsFromAssumeRole(cfgCp, handlers, sharedCfg, sessOpts) - } - - return creds, nil -} - -func resolveSSOCredentials(cfg *aws.Config, sharedCfg sharedConfig, handlers request.Handlers) (*credentials.Credentials, error) { - if err := sharedCfg.validateSSOConfiguration(); err != nil { - return nil, err - } - - var optFns []func(provider *ssocreds.Provider) - cfgCopy := cfg.Copy() - - if sharedCfg.SSOSession != nil { - cfgCopy.Region = &sharedCfg.SSOSession.SSORegion - cachedPath, err := ssocreds.StandardCachedTokenFilepath(sharedCfg.SSOSession.Name) - if err != nil { - return nil, err - } - // create oidcClient with AnonymousCredentials to avoid recursively resolving credentials - mySession := Must(NewSession(&aws.Config{ - Credentials: credentials.AnonymousCredentials, - })) - oidcClient := ssooidc.New(mySession, cfgCopy) - tokenProvider := ssocreds.NewSSOTokenProvider(oidcClient, cachedPath) - optFns = append(optFns, func(p *ssocreds.Provider) { - p.TokenProvider = tokenProvider - p.CachedTokenFilepath = cachedPath - }) - } else { - cfgCopy.Region = &sharedCfg.SSORegion - } - - return ssocreds.NewCredentials( - &Session{ - Config: cfgCopy, - Handlers: handlers.Copy(), - }, - sharedCfg.SSOAccountID, - sharedCfg.SSORoleName, - sharedCfg.SSOStartURL, - optFns..., - ), nil -} - -// valid credential source values -const ( - credSourceEc2Metadata = "Ec2InstanceMetadata" - credSourceEnvironment = "Environment" - credSourceECSContainer = "EcsContainer" -) - -func resolveCredsFromSource(cfg *aws.Config, - envCfg envConfig, sharedCfg sharedConfig, - handlers request.Handlers, - sessOpts Options, -) (creds *credentials.Credentials, err error) { - - switch sharedCfg.CredentialSource { - case credSourceEc2Metadata: - p := defaults.RemoteCredProvider(*cfg, handlers) - creds = credentials.NewCredentials(p) - - case credSourceEnvironment: - creds = credentials.NewStaticCredentialsFromCreds(envCfg.Creds) - - case credSourceECSContainer: - if len(os.Getenv(shareddefaults.ECSCredsProviderEnvVar)) == 0 { - return nil, ErrSharedConfigECSContainerEnvVarEmpty - } - - p := defaults.RemoteCredProvider(*cfg, handlers) - creds = credentials.NewCredentials(p) - - default: - return nil, ErrSharedConfigInvalidCredSource - } - - return creds, nil -} - -func credsFromAssumeRole(cfg aws.Config, - handlers request.Handlers, - sharedCfg sharedConfig, - sessOpts Options, -) (*credentials.Credentials, error) { - - if len(sharedCfg.MFASerial) != 0 && sessOpts.AssumeRoleTokenProvider == nil { - // AssumeRole Token provider is required if doing Assume Role - // with MFA. - return nil, AssumeRoleTokenProviderNotSetError{} - } - - return stscreds.NewCredentials( - &Session{ - Config: &cfg, - Handlers: handlers.Copy(), - }, - sharedCfg.RoleARN, - func(opt *stscreds.AssumeRoleProvider) { - opt.RoleSessionName = sharedCfg.RoleSessionName - - if sessOpts.AssumeRoleDuration == 0 && - sharedCfg.AssumeRoleDuration != nil && - *sharedCfg.AssumeRoleDuration/time.Minute > 15 { - opt.Duration = *sharedCfg.AssumeRoleDuration - } else if sessOpts.AssumeRoleDuration != 0 { - opt.Duration = sessOpts.AssumeRoleDuration - } - - // Assume role with external ID - if len(sharedCfg.ExternalID) > 0 { - opt.ExternalID = aws.String(sharedCfg.ExternalID) - } - - // Assume role with MFA - if len(sharedCfg.MFASerial) > 0 { - opt.SerialNumber = aws.String(sharedCfg.MFASerial) - opt.TokenProvider = sessOpts.AssumeRoleTokenProvider - } - }, - ), nil -} - -// AssumeRoleTokenProviderNotSetError is an error returned when creating a -// session when the MFAToken option is not set when shared config is configured -// load assume a role with an MFA token. -type AssumeRoleTokenProviderNotSetError struct{} - -// Code is the short id of the error. -func (e AssumeRoleTokenProviderNotSetError) Code() string { - return "AssumeRoleTokenProviderNotSetError" -} - -// Message is the description of the error -func (e AssumeRoleTokenProviderNotSetError) Message() string { - return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.") -} - -// OrigErr is the underlying error that caused the failure. -func (e AssumeRoleTokenProviderNotSetError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e AssumeRoleTokenProviderNotSetError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} - -type credProviderError struct { - Err error -} - -func (c credProviderError) Retrieve() (credentials.Value, error) { - return credentials.Value{}, c.Err -} -func (c credProviderError) IsExpired() bool { - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport.go b/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport.go deleted file mode 100644 index 4390ad52f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build go1.13 -// +build go1.13 - -package session - -import ( - "net" - "net/http" - "time" -) - -// Transport that should be used when a custom CA bundle is specified with the -// SDK. -func getCustomTransport() *http.Transport { - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, - ForceAttemptHTTP2: true, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.12.go b/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.12.go deleted file mode 100644 index 668565bea..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.12.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build !go1.13 && go1.7 -// +build !go1.13,go1.7 - -package session - -import ( - "net" - "net/http" - "time" -) - -// Transport that should be used when a custom CA bundle is specified with the -// SDK. -func getCustomTransport() *http.Transport { - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.5.go b/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.5.go deleted file mode 100644 index e101aa6b6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.5.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build !go1.6 && go1.5 -// +build !go1.6,go1.5 - -package session - -import ( - "net" - "net/http" - "time" -) - -// Transport that should be used when a custom CA bundle is specified with the -// SDK. -func getCustomTransport() *http.Transport { - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.6.go b/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.6.go deleted file mode 100644 index b5fcbe0d1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/custom_transport_go1.6.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !go1.7 && go1.6 -// +build !go1.7,go1.6 - -package session - -import ( - "net" - "net/http" - "time" -) - -// Transport that should be used when a custom CA bundle is specified with the -// SDK. -func getCustomTransport() *http.Transport { - return &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go deleted file mode 100644 index ff3cc012a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go +++ /dev/null @@ -1,367 +0,0 @@ -/* -Package session provides configuration for the SDK's service clients. Sessions -can be shared across service clients that share the same base configuration. - -Sessions are safe to use concurrently as long as the Session is not being -modified. Sessions should be cached when possible, because creating a new -Session will load all configuration values from the environment, and config -files each time the Session is created. Sharing the Session value across all of -your service clients will ensure the configuration is loaded the fewest number -of times possible. - -Sessions options from Shared Config - -By default NewSession will only load credentials from the shared credentials -file (~/.aws/credentials). If the AWS_SDK_LOAD_CONFIG environment variable is -set to a truthy value the Session will be created from the configuration -values from the shared config (~/.aws/config) and shared credentials -(~/.aws/credentials) files. Using the NewSessionWithOptions with -SharedConfigState set to SharedConfigEnable will create the session as if the -AWS_SDK_LOAD_CONFIG environment variable was set. - -Credential and config loading order - -The Session will attempt to load configuration and credentials from the -environment, configuration files, and other credential sources. The order -configuration is loaded in is: - - * Environment Variables - * Shared Credentials file - * Shared Configuration file (if SharedConfig is enabled) - * EC2 Instance Metadata (credentials only) - -The Environment variables for credentials will have precedence over shared -config even if SharedConfig is enabled. To override this behavior, and use -shared config credentials instead specify the session.Options.Profile, (e.g. -when using credential_source=Environment to assume a role). - - sess, err := session.NewSessionWithOptions(session.Options{ - Profile: "myProfile", - }) - -Creating Sessions - -Creating a Session without additional options will load credentials region, and -profile loaded from the environment and shared config automatically. See, -"Environment Variables" section for information on environment variables used -by Session. - - // Create Session - sess, err := session.NewSession() - - -When creating Sessions optional aws.Config values can be passed in that will -override the default, or loaded, config values the Session is being created -with. This allows you to provide additional, or case based, configuration -as needed. - - // Create a Session with a custom region - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2"), - }) - -Use NewSessionWithOptions to provide additional configuration driving how the -Session's configuration will be loaded. Such as, specifying shared config -profile, or override the shared config state, (AWS_SDK_LOAD_CONFIG). - - // Equivalent to session.NewSession() - sess, err := session.NewSessionWithOptions(session.Options{ - // Options - }) - - sess, err := session.NewSessionWithOptions(session.Options{ - // Specify profile to load for the session's config - Profile: "profile_name", - - // Provide SDK Config options, such as Region. - Config: aws.Config{ - Region: aws.String("us-west-2"), - }, - - // Force enable Shared Config support - SharedConfigState: session.SharedConfigEnable, - }) - -Adding Handlers - -You can add handlers to a session to decorate API operation, (e.g. adding HTTP -headers). All clients that use the Session receive a copy of the Session's -handlers. For example, the following request handler added to the Session logs -every requests made. - - // Create a session, and add additional handlers for all service - // clients created with the Session to inherit. Adds logging handler. - sess := session.Must(session.NewSession()) - - sess.Handlers.Send.PushFront(func(r *request.Request) { - // Log every request made and its payload - logger.Printf("Request: %s/%s, Params: %s", - r.ClientInfo.ServiceName, r.Operation, r.Params) - }) - -Shared Config Fields - -By default the SDK will only load the shared credentials file's -(~/.aws/credentials) credentials values, and all other config is provided by -the environment variables, SDK defaults, and user provided aws.Config values. - -If the AWS_SDK_LOAD_CONFIG environment variable is set, or SharedConfigEnable -option is used to create the Session the full shared config values will be -loaded. This includes credentials, region, and support for assume role. In -addition the Session will load its configuration from both the shared config -file (~/.aws/config) and shared credentials file (~/.aws/credentials). Both -files have the same format. - -If both config files are present the configuration from both files will be -read. The Session will be created from configuration values from the shared -credentials file (~/.aws/credentials) over those in the shared config file -(~/.aws/config). - -Credentials are the values the SDK uses to authenticating requests with AWS -Services. When specified in a file, both aws_access_key_id and -aws_secret_access_key must be provided together in the same file to be -considered valid. They will be ignored if both are not present. -aws_session_token is an optional field that can be provided in addition to the -other two fields. - - aws_access_key_id = AKID - aws_secret_access_key = SECRET - aws_session_token = TOKEN - - ; region only supported if SharedConfigEnabled. - region = us-east-1 - -Assume Role configuration - -The role_arn field allows you to configure the SDK to assume an IAM role using -a set of credentials from another source. Such as when paired with static -credentials, "profile_source", "credential_process", or "credential_source" -fields. If "role_arn" is provided, a source of credentials must also be -specified, such as "source_profile", "credential_source", or -"credential_process". - - role_arn = arn:aws:iam:::role/ - source_profile = profile_with_creds - external_id = 1234 - mfa_serial = - role_session_name = session_name - - -The SDK supports assuming a role with MFA token. If "mfa_serial" is set, you -must also set the Session Option.AssumeRoleTokenProvider. The Session will fail -to load if the AssumeRoleTokenProvider is not specified. - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - AssumeRoleTokenProvider: stscreds.StdinTokenProvider, - })) - -To setup Assume Role outside of a session see the stscreds.AssumeRoleProvider -documentation. - -Environment Variables - -When a Session is created several environment variables can be set to adjust -how the SDK functions, and what configuration data it loads when creating -Sessions. All environment values are optional, but some values like credentials -require multiple of the values to set or the partial values will be ignored. -All environment variable values are strings unless otherwise noted. - -Environment configuration values. If set both Access Key ID and Secret Access -Key must be provided. Session Token and optionally also be provided, but is -not required. - - # Access Key ID - AWS_ACCESS_KEY_ID=AKID - AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. - - # Secret Access Key - AWS_SECRET_ACCESS_KEY=SECRET - AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - - # Session Token - AWS_SESSION_TOKEN=TOKEN - -Region value will instruct the SDK where to make service API requests to. If is -not provided in the environment the region must be provided before a service -client request is made. - - AWS_REGION=us-east-1 - - # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, - # and AWS_REGION is not also set. - AWS_DEFAULT_REGION=us-east-1 - -Profile name the SDK should load use when loading shared config from the -configuration files. If not provided "default" will be used as the profile name. - - AWS_PROFILE=my_profile - - # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, - # and AWS_PROFILE is not also set. - AWS_DEFAULT_PROFILE=my_profile - -SDK load config instructs the SDK to load the shared config in addition to -shared credentials. This also expands the configuration loaded so the shared -credentials will have parity with the shared config file. This also enables -Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE -env values as well. - - AWS_SDK_LOAD_CONFIG=1 - -Custom Shared Config and Credential Files - -Shared credentials file path can be set to instruct the SDK to use an alternative -file for the shared credentials. If not set the file will be loaded from -$HOME/.aws/credentials on Linux/Unix based systems, and -%USERPROFILE%\.aws\credentials on Windows. - - AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials - -Shared config file path can be set to instruct the SDK to use an alternative -file for the shared config. If not set the file will be loaded from -$HOME/.aws/config on Linux/Unix based systems, and -%USERPROFILE%\.aws\config on Windows. - - AWS_CONFIG_FILE=$HOME/my_shared_config - -Custom CA Bundle - -Path to a custom Credentials Authority (CA) bundle PEM file that the SDK -will use instead of the default system's root CA bundle. Use this only -if you want to replace the CA bundle the SDK uses for TLS requests. - - AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - -Enabling this option will attempt to merge the Transport into the SDK's HTTP -client. If the client's Transport is not a http.Transport an error will be -returned. If the Transport's TLS config is set this option will cause the SDK -to overwrite the Transport's TLS config's RootCAs value. If the CA bundle file -contains multiple certificates all of them will be loaded. - -The Session option CustomCABundle is also available when creating sessions -to also enable this feature. CustomCABundle session option field has priority -over the AWS_CA_BUNDLE environment variable, and will be used if both are set. - -Setting a custom HTTPClient in the aws.Config options will override this setting. -To use this option and custom HTTP client, the HTTP client needs to be provided -when creating the session. Not the service client. - -Custom Client TLS Certificate - -The SDK supports the environment and session option being configured with -Client TLS certificates that are sent as a part of the client's TLS handshake -for client authentication. If used, both Cert and Key values are required. If -one is missing, or either fail to load the contents of the file an error will -be returned. - -HTTP Client's Transport concrete implementation must be a http.Transport -or creating the session will fail. - - AWS_SDK_GO_CLIENT_TLS_KEY=$HOME/my_client_key - AWS_SDK_GO_CLIENT_TLS_CERT=$HOME/my_client_cert - -This can also be configured via the session.Options ClientTLSCert and ClientTLSKey. - - sess, err := session.NewSessionWithOptions(session.Options{ - ClientTLSCert: myCertFile, - ClientTLSKey: myKeyFile, - }) - -Custom EC2 IMDS Endpoint - -The endpoint of the EC2 IMDS client can be configured via the environment -variable, AWS_EC2_METADATA_SERVICE_ENDPOINT when creating the client with a -Session. See Options.EC2IMDSEndpoint for more details. - - AWS_EC2_METADATA_SERVICE_ENDPOINT=http://169.254.169.254 - -If using an URL with an IPv6 address literal, the IPv6 address -component must be enclosed in square brackets. - - AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] - -The custom EC2 IMDS endpoint can also be specified via the Session options. - - sess, err := session.NewSessionWithOptions(session.Options{ - EC2MetadataEndpoint: "http://[::1]", - }) - -FIPS and DualStack Endpoints - -The SDK can be configured to resolve an endpoint with certain capabilities such as FIPS and DualStack. - -You can configure a FIPS endpoint using an environment variable, shared config ($HOME/.aws/config), -or programmatically. - -To configure a FIPS endpoint set the environment variable set the AWS_USE_FIPS_ENDPOINT to true or false to enable -or disable FIPS endpoint resolution. - - AWS_USE_FIPS_ENDPOINT=true - -To configure a FIPS endpoint using shared config, set use_fips_endpoint to true or false to enable -or disable FIPS endpoint resolution. - - [profile myprofile] - region=us-west-2 - use_fips_endpoint=true - -To configure a FIPS endpoint programmatically - - // Option 1: Configure it on a session for all clients - sess, err := session.NewSessionWithOptions(session.Options{ - UseFIPSEndpoint: endpoints.FIPSEndpointStateEnabled, - }) - if err != nil { - // handle error - } - - client := s3.New(sess) - - // Option 2: Configure it per client - sess, err := session.NewSession() - if err != nil { - // handle error - } - - client := s3.New(sess, &aws.Config{ - UseFIPSEndpoint: endpoints.FIPSEndpointStateEnabled, - }) - -You can configure a DualStack endpoint using an environment variable, shared config ($HOME/.aws/config), -or programmatically. - -To configure a DualStack endpoint set the environment variable set the AWS_USE_DUALSTACK_ENDPOINT to true or false to -enable or disable DualStack endpoint resolution. - - AWS_USE_DUALSTACK_ENDPOINT=true - -To configure a DualStack endpoint using shared config, set use_dualstack_endpoint to true or false to enable -or disable DualStack endpoint resolution. - - [profile myprofile] - region=us-west-2 - use_dualstack_endpoint=true - -To configure a DualStack endpoint programmatically - - // Option 1: Configure it on a session for all clients - sess, err := session.NewSessionWithOptions(session.Options{ - UseDualStackEndpoint: endpoints.DualStackEndpointStateEnabled, - }) - if err != nil { - // handle error - } - - client := s3.New(sess) - - // Option 2: Configure it per client - sess, err := session.NewSession() - if err != nil { - // handle error - } - - client := s3.New(sess, &aws.Config{ - UseDualStackEndpoint: endpoints.DualStackEndpointStateEnabled, - }) -*/ -package session diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go deleted file mode 100644 index 93bb5de64..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go +++ /dev/null @@ -1,499 +0,0 @@ -package session - -import ( - "fmt" - "os" - "strconv" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/endpoints" -) - -// EnvProviderName provides a name of the provider when config is loaded from environment. -const EnvProviderName = "EnvConfigCredentials" - -// envConfig is a collection of environment values the SDK will read -// setup config from. All environment values are optional. But some values -// such as credentials require multiple values to be complete or the values -// will be ignored. -type envConfig struct { - // Environment configuration values. If set both Access Key ID and Secret Access - // Key must be provided. Session Token and optionally also be provided, but is - // not required. - // - // # Access Key ID - // AWS_ACCESS_KEY_ID=AKID - // AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. - // - // # Secret Access Key - // AWS_SECRET_ACCESS_KEY=SECRET - // AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - // - // # Session Token - // AWS_SESSION_TOKEN=TOKEN - Creds credentials.Value - - // Region value will instruct the SDK where to make service API requests to. If is - // not provided in the environment the region must be provided before a service - // client request is made. - // - // AWS_REGION=us-east-1 - // - // # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, - // # and AWS_REGION is not also set. - // AWS_DEFAULT_REGION=us-east-1 - Region string - - // Profile name the SDK should load use when loading shared configuration from the - // shared configuration files. If not provided "default" will be used as the - // profile name. - // - // AWS_PROFILE=my_profile - // - // # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, - // # and AWS_PROFILE is not also set. - // AWS_DEFAULT_PROFILE=my_profile - Profile string - - // SDK load config instructs the SDK to load the shared config in addition to - // shared credentials. This also expands the configuration loaded from the shared - // credentials to have parity with the shared config file. This also enables - // Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE - // env values as well. - // - // AWS_SDK_LOAD_CONFIG=1 - EnableSharedConfig bool - - // Shared credentials file path can be set to instruct the SDK to use an alternate - // file for the shared credentials. If not set the file will be loaded from - // $HOME/.aws/credentials on Linux/Unix based systems, and - // %USERPROFILE%\.aws\credentials on Windows. - // - // AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials - SharedCredentialsFile string - - // Shared config file path can be set to instruct the SDK to use an alternate - // file for the shared config. If not set the file will be loaded from - // $HOME/.aws/config on Linux/Unix based systems, and - // %USERPROFILE%\.aws\config on Windows. - // - // AWS_CONFIG_FILE=$HOME/my_shared_config - SharedConfigFile string - - // Sets the path to a custom Credentials Authority (CA) Bundle PEM file - // that the SDK will use instead of the system's root CA bundle. - // Only use this if you want to configure the SDK to use a custom set - // of CAs. - // - // Enabling this option will attempt to merge the Transport - // into the SDK's HTTP client. If the client's Transport is - // not a http.Transport an error will be returned. If the - // Transport's TLS config is set this option will cause the - // SDK to overwrite the Transport's TLS config's RootCAs value. - // - // Setting a custom HTTPClient in the aws.Config options will override this setting. - // To use this option and custom HTTP client, the HTTP client needs to be provided - // when creating the session. Not the service client. - // - // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - CustomCABundle string - - // Sets the TLC client certificate that should be used by the SDK's HTTP transport - // when making requests. The certificate must be paired with a TLS client key file. - // - // AWS_SDK_GO_CLIENT_TLS_CERT=$HOME/my_client_cert - ClientTLSCert string - - // Sets the TLC client key that should be used by the SDK's HTTP transport - // when making requests. The key must be paired with a TLS client certificate file. - // - // AWS_SDK_GO_CLIENT_TLS_KEY=$HOME/my_client_key - ClientTLSKey string - - csmEnabled string - CSMEnabled *bool - CSMPort string - CSMHost string - CSMClientID string - - // Enables endpoint discovery via environment variables. - // - // AWS_ENABLE_ENDPOINT_DISCOVERY=true - EnableEndpointDiscovery *bool - enableEndpointDiscovery string - - // Specifies the WebIdentity token the SDK should use to assume a role - // with. - // - // AWS_WEB_IDENTITY_TOKEN_FILE=file_path - WebIdentityTokenFilePath string - - // Specifies the IAM role arn to use when assuming an role. - // - // AWS_ROLE_ARN=role_arn - RoleARN string - - // Specifies the IAM role session name to use when assuming a role. - // - // AWS_ROLE_SESSION_NAME=session_name - RoleSessionName string - - // Specifies the STS Regional Endpoint flag for the SDK to resolve the endpoint - // for a service. - // - // AWS_STS_REGIONAL_ENDPOINTS=regional - // This can take value as `regional` or `legacy` - STSRegionalEndpoint endpoints.STSRegionalEndpoint - - // Specifies the S3 Regional Endpoint flag for the SDK to resolve the - // endpoint for a service. - // - // AWS_S3_US_EAST_1_REGIONAL_ENDPOINT=regional - // This can take value as `regional` or `legacy` - S3UsEast1RegionalEndpoint endpoints.S3UsEast1RegionalEndpoint - - // Specifies if the S3 service should allow ARNs to direct the region - // the client's requests are sent to. - // - // AWS_S3_USE_ARN_REGION=true - S3UseARNRegion bool - - // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EC2IMDSEndpointMode. - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] - EC2IMDSEndpoint string - - // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6 - EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState - - // Specifies that IMDS clients should not fallback to IMDSv1 if token - // requests fail. - // - // AWS_EC2_METADATA_V1_DISABLED=true - EC2IMDSv1Disabled *bool - - // Specifies that SDK clients must resolve a dual-stack endpoint for - // services. - // - // AWS_USE_DUALSTACK_ENDPOINT=true - UseDualStackEndpoint endpoints.DualStackEndpointState - - // Specifies that SDK clients must resolve a FIPS endpoint for - // services. - // - // AWS_USE_FIPS_ENDPOINT=true - UseFIPSEndpoint endpoints.FIPSEndpointState -} - -var ( - csmEnabledEnvKey = []string{ - "AWS_CSM_ENABLED", - } - csmHostEnvKey = []string{ - "AWS_CSM_HOST", - } - csmPortEnvKey = []string{ - "AWS_CSM_PORT", - } - csmClientIDEnvKey = []string{ - "AWS_CSM_CLIENT_ID", - } - credAccessEnvKey = []string{ - "AWS_ACCESS_KEY_ID", - "AWS_ACCESS_KEY", - } - credSecretEnvKey = []string{ - "AWS_SECRET_ACCESS_KEY", - "AWS_SECRET_KEY", - } - credSessionEnvKey = []string{ - "AWS_SESSION_TOKEN", - } - - enableEndpointDiscoveryEnvKey = []string{ - "AWS_ENABLE_ENDPOINT_DISCOVERY", - } - - regionEnvKeys = []string{ - "AWS_REGION", - "AWS_DEFAULT_REGION", // Only read if AWS_SDK_LOAD_CONFIG is also set - } - profileEnvKeys = []string{ - "AWS_PROFILE", - "AWS_DEFAULT_PROFILE", // Only read if AWS_SDK_LOAD_CONFIG is also set - } - sharedCredsFileEnvKey = []string{ - "AWS_SHARED_CREDENTIALS_FILE", - } - sharedConfigFileEnvKey = []string{ - "AWS_CONFIG_FILE", - } - webIdentityTokenFilePathEnvKey = []string{ - "AWS_WEB_IDENTITY_TOKEN_FILE", - } - roleARNEnvKey = []string{ - "AWS_ROLE_ARN", - } - roleSessionNameEnvKey = []string{ - "AWS_ROLE_SESSION_NAME", - } - stsRegionalEndpointKey = []string{ - "AWS_STS_REGIONAL_ENDPOINTS", - } - s3UsEast1RegionalEndpoint = []string{ - "AWS_S3_US_EAST_1_REGIONAL_ENDPOINT", - } - s3UseARNRegionEnvKey = []string{ - "AWS_S3_USE_ARN_REGION", - } - ec2IMDSEndpointEnvKey = []string{ - "AWS_EC2_METADATA_SERVICE_ENDPOINT", - } - ec2IMDSEndpointModeEnvKey = []string{ - "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE", - } - ec2MetadataV1DisabledEnvKey = []string{ - "AWS_EC2_METADATA_V1_DISABLED", - } - useCABundleKey = []string{ - "AWS_CA_BUNDLE", - } - useClientTLSCert = []string{ - "AWS_SDK_GO_CLIENT_TLS_CERT", - } - useClientTLSKey = []string{ - "AWS_SDK_GO_CLIENT_TLS_KEY", - } - awsUseDualStackEndpoint = []string{ - "AWS_USE_DUALSTACK_ENDPOINT", - } - awsUseFIPSEndpoint = []string{ - "AWS_USE_FIPS_ENDPOINT", - } -) - -// loadEnvConfig retrieves the SDK's environment configuration. -// See `envConfig` for the values that will be retrieved. -// -// If the environment variable `AWS_SDK_LOAD_CONFIG` is set to a truthy value -// the shared SDK config will be loaded in addition to the SDK's specific -// configuration values. -func loadEnvConfig() (envConfig, error) { - enableSharedConfig, _ := strconv.ParseBool(os.Getenv("AWS_SDK_LOAD_CONFIG")) - return envConfigLoad(enableSharedConfig) -} - -// loadEnvSharedConfig retrieves the SDK's environment configuration, and the -// SDK shared config. See `envConfig` for the values that will be retrieved. -// -// Loads the shared configuration in addition to the SDK's specific configuration. -// This will load the same values as `loadEnvConfig` if the `AWS_SDK_LOAD_CONFIG` -// environment variable is set. -func loadSharedEnvConfig() (envConfig, error) { - return envConfigLoad(true) -} - -func envConfigLoad(enableSharedConfig bool) (envConfig, error) { - cfg := envConfig{} - - cfg.EnableSharedConfig = enableSharedConfig - - // Static environment credentials - var creds credentials.Value - setFromEnvVal(&creds.AccessKeyID, credAccessEnvKey) - setFromEnvVal(&creds.SecretAccessKey, credSecretEnvKey) - setFromEnvVal(&creds.SessionToken, credSessionEnvKey) - if creds.HasKeys() { - // Require logical grouping of credentials - creds.ProviderName = EnvProviderName - cfg.Creds = creds - } - - // Role Metadata - setFromEnvVal(&cfg.RoleARN, roleARNEnvKey) - setFromEnvVal(&cfg.RoleSessionName, roleSessionNameEnvKey) - - // Web identity environment variables - setFromEnvVal(&cfg.WebIdentityTokenFilePath, webIdentityTokenFilePathEnvKey) - - // CSM environment variables - setFromEnvVal(&cfg.csmEnabled, csmEnabledEnvKey) - setFromEnvVal(&cfg.CSMHost, csmHostEnvKey) - setFromEnvVal(&cfg.CSMPort, csmPortEnvKey) - setFromEnvVal(&cfg.CSMClientID, csmClientIDEnvKey) - - if len(cfg.csmEnabled) != 0 { - v, _ := strconv.ParseBool(cfg.csmEnabled) - cfg.CSMEnabled = &v - } - - regionKeys := regionEnvKeys - profileKeys := profileEnvKeys - if !cfg.EnableSharedConfig { - regionKeys = regionKeys[:1] - profileKeys = profileKeys[:1] - } - - setFromEnvVal(&cfg.Region, regionKeys) - setFromEnvVal(&cfg.Profile, profileKeys) - - // endpoint discovery is in reference to it being enabled. - setFromEnvVal(&cfg.enableEndpointDiscovery, enableEndpointDiscoveryEnvKey) - if len(cfg.enableEndpointDiscovery) > 0 { - cfg.EnableEndpointDiscovery = aws.Bool(cfg.enableEndpointDiscovery != "false") - } - - setFromEnvVal(&cfg.SharedCredentialsFile, sharedCredsFileEnvKey) - setFromEnvVal(&cfg.SharedConfigFile, sharedConfigFileEnvKey) - - if len(cfg.SharedCredentialsFile) == 0 { - cfg.SharedCredentialsFile = defaults.SharedCredentialsFilename() - } - if len(cfg.SharedConfigFile) == 0 { - cfg.SharedConfigFile = defaults.SharedConfigFilename() - } - - setFromEnvVal(&cfg.CustomCABundle, useCABundleKey) - setFromEnvVal(&cfg.ClientTLSCert, useClientTLSCert) - setFromEnvVal(&cfg.ClientTLSKey, useClientTLSKey) - - var err error - // STS Regional Endpoint variable - for _, k := range stsRegionalEndpointKey { - if v := os.Getenv(k); len(v) != 0 { - cfg.STSRegionalEndpoint, err = endpoints.GetSTSRegionalEndpoint(v) - if err != nil { - return cfg, fmt.Errorf("failed to load, %v from env config, %v", k, err) - } - } - } - - // S3 Regional Endpoint variable - for _, k := range s3UsEast1RegionalEndpoint { - if v := os.Getenv(k); len(v) != 0 { - cfg.S3UsEast1RegionalEndpoint, err = endpoints.GetS3UsEast1RegionalEndpoint(v) - if err != nil { - return cfg, fmt.Errorf("failed to load, %v from env config, %v", k, err) - } - } - } - - var s3UseARNRegion string - setFromEnvVal(&s3UseARNRegion, s3UseARNRegionEnvKey) - if len(s3UseARNRegion) != 0 { - switch { - case strings.EqualFold(s3UseARNRegion, "false"): - cfg.S3UseARNRegion = false - case strings.EqualFold(s3UseARNRegion, "true"): - cfg.S3UseARNRegion = true - default: - return envConfig{}, fmt.Errorf( - "invalid value for environment variable, %s=%s, need true or false", - s3UseARNRegionEnvKey[0], s3UseARNRegion) - } - } - - setFromEnvVal(&cfg.EC2IMDSEndpoint, ec2IMDSEndpointEnvKey) - if err := setEC2IMDSEndpointMode(&cfg.EC2IMDSEndpointMode, ec2IMDSEndpointModeEnvKey); err != nil { - return envConfig{}, err - } - setBoolPtrFromEnvVal(&cfg.EC2IMDSv1Disabled, ec2MetadataV1DisabledEnvKey) - - if err := setUseDualStackEndpointFromEnvVal(&cfg.UseDualStackEndpoint, awsUseDualStackEndpoint); err != nil { - return cfg, err - } - - if err := setUseFIPSEndpointFromEnvVal(&cfg.UseFIPSEndpoint, awsUseFIPSEndpoint); err != nil { - return cfg, err - } - - return cfg, nil -} - -func setFromEnvVal(dst *string, keys []string) { - for _, k := range keys { - if v := os.Getenv(k); len(v) != 0 { - *dst = v - break - } - } -} - -func setBoolPtrFromEnvVal(dst **bool, keys []string) { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - - switch { - case strings.EqualFold(value, "false"): - *dst = new(bool) - **dst = false - case strings.EqualFold(value, "true"): - *dst = new(bool) - **dst = true - } - } -} - -func setEC2IMDSEndpointMode(mode *endpoints.EC2IMDSEndpointModeState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - if err := mode.SetFromString(value); err != nil { - return fmt.Errorf("invalid value for environment variable, %s=%s, %v", k, value, err) - } - return nil - } - return nil -} - -func setUseDualStackEndpointFromEnvVal(dst *endpoints.DualStackEndpointState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue // skip if empty - } - - switch { - case strings.EqualFold(value, "true"): - *dst = endpoints.DualStackEndpointStateEnabled - case strings.EqualFold(value, "false"): - *dst = endpoints.DualStackEndpointStateDisabled - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true, false", - k, value) - } - } - return nil -} - -func setUseFIPSEndpointFromEnvVal(dst *endpoints.FIPSEndpointState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue // skip if empty - } - - switch { - case strings.EqualFold(value, "true"): - *dst = endpoints.FIPSEndpointStateEnabled - case strings.EqualFold(value, "false"): - *dst = endpoints.FIPSEndpointStateDisabled - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true, false", - k, value) - } - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go deleted file mode 100644 index 3c88dee52..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go +++ /dev/null @@ -1,1005 +0,0 @@ -package session - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/csm" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/request" -) - -const ( - // ErrCodeSharedConfig represents an error that occurs in the shared - // configuration logic - ErrCodeSharedConfig = "SharedConfigErr" - - // ErrCodeLoadCustomCABundle error code for unable to load custom CA bundle. - ErrCodeLoadCustomCABundle = "LoadCustomCABundleError" - - // ErrCodeLoadClientTLSCert error code for unable to load client TLS - // certificate or key - ErrCodeLoadClientTLSCert = "LoadClientTLSCertError" -) - -// ErrSharedConfigSourceCollision will be returned if a section contains both -// source_profile and credential_source -var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only one credential type may be specified per profile: source profile, credential source, credential process, web identity token", nil) - -// ErrSharedConfigECSContainerEnvVarEmpty will be returned if the environment -// variables are empty and Environment was set as the credential source -var ErrSharedConfigECSContainerEnvVarEmpty = awserr.New(ErrCodeSharedConfig, "EcsContainer was specified as the credential_source, but 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' was not set", nil) - -// ErrSharedConfigInvalidCredSource will be returned if an invalid credential source was provided -var ErrSharedConfigInvalidCredSource = awserr.New(ErrCodeSharedConfig, "credential source values must be EcsContainer, Ec2InstanceMetadata, or Environment", nil) - -// A Session provides a central location to create service clients from and -// store configurations and request handlers for those services. -// -// Sessions are safe to create service clients concurrently, but it is not safe -// to mutate the Session concurrently. -// -// The Session satisfies the service client's client.ConfigProvider. -type Session struct { - Config *aws.Config - Handlers request.Handlers - - options Options -} - -// New creates a new instance of the handlers merging in the provided configs -// on top of the SDK's default configurations. Once the Session is created it -// can be mutated to modify the Config or Handlers. The Session is safe to be -// read concurrently, but it should not be written to concurrently. -// -// If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New -// method could now encounter an error when loading the configuration. When -// The environment variable is set, and an error occurs, New will return a -// session that will fail all requests reporting the error that occurred while -// loading the session. Use NewSession to get the error when creating the -// session. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded, in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. -// -// Deprecated: Use NewSession functions to create sessions instead. NewSession -// has the same functionality as New except an error can be returned when the -// func is called instead of waiting to receive an error until a request is made. -func New(cfgs ...*aws.Config) *Session { - // load initial config from environment - envCfg, envErr := loadEnvConfig() - - if envCfg.EnableSharedConfig { - var cfg aws.Config - cfg.MergeIn(cfgs...) - s, err := NewSessionWithOptions(Options{ - Config: cfg, - SharedConfigState: SharedConfigEnable, - }) - if err != nil { - // Old session.New expected all errors to be discovered when - // a request is made, and would report the errors then. This - // needs to be replicated if an error occurs while creating - // the session. - msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " + - "Use session.NewSession to handle errors occurring during session creation." - - // Session creation failed, need to report the error and prevent - // any requests from succeeding. - s = &Session{Config: defaults.Config()} - s.logDeprecatedNewSessionError(msg, err, cfgs) - } - - return s - } - - s := deprecatedNewSession(envCfg, cfgs...) - if envErr != nil { - msg := "failed to load env config" - s.logDeprecatedNewSessionError(msg, envErr, cfgs) - } - - if csmCfg, err := loadCSMConfig(envCfg, []string{}); err != nil { - if l := s.Config.Logger; l != nil { - l.Log(fmt.Sprintf("ERROR: failed to load CSM configuration, %v", err)) - } - } else if csmCfg.Enabled { - err := enableCSM(&s.Handlers, csmCfg, s.Config.Logger) - if err != nil { - msg := "failed to enable CSM" - s.logDeprecatedNewSessionError(msg, err, cfgs) - } - } - - return s -} - -// NewSession returns a new Session created from SDK defaults, config files, -// environment, and user provided config files. Once the Session is created -// it can be mutated to modify the Config or Handlers. The Session is safe to -// be read concurrently, but it should not be written to concurrently. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. Enabling the Shared Config will also allow the Session -// to be built with retrieving credentials with AssumeRole set in the config. -// -// See the NewSessionWithOptions func for information on how to override or -// control through code how the Session will be created, such as specifying the -// config profile, and controlling if shared config is enabled or not. -func NewSession(cfgs ...*aws.Config) (*Session, error) { - opts := Options{} - opts.Config.MergeIn(cfgs...) - - return NewSessionWithOptions(opts) -} - -// SharedConfigState provides the ability to optionally override the state -// of the session's creation based on the shared config being enabled or -// disabled. -type SharedConfigState int - -const ( - // SharedConfigStateFromEnv does not override any state of the - // AWS_SDK_LOAD_CONFIG env var. It is the default value of the - // SharedConfigState type. - SharedConfigStateFromEnv SharedConfigState = iota - - // SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value - // and disables the shared config functionality. - SharedConfigDisable - - // SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value - // and enables the shared config functionality. - SharedConfigEnable -) - -// Options provides the means to control how a Session is created and what -// configuration values will be loaded. -type Options struct { - // Provides config values for the SDK to use when creating service clients - // and making API requests to services. Any value set in with this field - // will override the associated value provided by the SDK defaults, - // environment or config files where relevant. - // - // If not set, configuration values from from SDK defaults, environment, - // config will be used. - Config aws.Config - - // Overrides the config profile the Session should be created from. If not - // set the value of the environment variable will be loaded (AWS_PROFILE, - // or AWS_DEFAULT_PROFILE if the Shared Config is enabled). - // - // If not set and environment variables are not set the "default" - // (DefaultSharedConfigProfile) will be used as the profile to load the - // session config from. - Profile string - - // Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG - // environment variable. By default a Session will be created using the - // value provided by the AWS_SDK_LOAD_CONFIG environment variable. - // - // Setting this value to SharedConfigEnable or SharedConfigDisable - // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable - // and enable or disable the shared config functionality. - SharedConfigState SharedConfigState - - // Ordered list of files the session will load configuration from. - // It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE. - SharedConfigFiles []string - - // When the SDK's shared config is configured to assume a role with MFA - // this option is required in order to provide the mechanism that will - // retrieve the MFA token. There is no default value for this field. If - // it is not set an error will be returned when creating the session. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed. Within the context of service clients - // all sharing the same session the SDK will ensure calls to the token - // provider are atomic. When sharing a token provider across multiple - // sessions additional synchronization logic is needed to ensure the - // token providers do not introduce race conditions. It is recommend to - // share the session where possible. - // - // stscreds.StdinTokenProvider is a basic implementation that will prompt - // from stdin for the MFA token code. - // - // This field is only used if the shared configuration is enabled, and - // the config enables assume role with MFA via the mfa_serial field. - AssumeRoleTokenProvider func() (string, error) - - // When the SDK's shared config is configured to assume a role this option - // may be provided to set the expiry duration of the STS credentials. - // Defaults to 15 minutes if not set as documented in the - // stscreds.AssumeRoleProvider. - AssumeRoleDuration time.Duration - - // Reader for a custom Credentials Authority (CA) bundle in PEM format that - // the SDK will use instead of the default system's root CA bundle. Use this - // only if you want to replace the CA bundle the SDK uses for TLS requests. - // - // HTTP Client's Transport concrete implementation must be a http.Transport - // or creating the session will fail. - // - // If the Transport's TLS config is set this option will cause the SDK - // to overwrite the Transport's TLS config's RootCAs value. If the CA - // bundle reader contains multiple certificates all of them will be loaded. - // - // Can also be specified via the environment variable: - // - // AWS_CA_BUNDLE=$HOME/ca_bundle - // - // Can also be specified via the shared config field: - // - // ca_bundle = $HOME/ca_bundle - CustomCABundle io.Reader - - // Reader for the TLC client certificate that should be used by the SDK's - // HTTP transport when making requests. The certificate must be paired with - // a TLS client key file. Will be ignored if both are not provided. - // - // HTTP Client's Transport concrete implementation must be a http.Transport - // or creating the session will fail. - // - // Can also be specified via the environment variable: - // - // AWS_SDK_GO_CLIENT_TLS_CERT=$HOME/my_client_cert - ClientTLSCert io.Reader - - // Reader for the TLC client key that should be used by the SDK's HTTP - // transport when making requests. The key must be paired with a TLS client - // certificate file. Will be ignored if both are not provided. - // - // HTTP Client's Transport concrete implementation must be a http.Transport - // or creating the session will fail. - // - // Can also be specified via the environment variable: - // - // AWS_SDK_GO_CLIENT_TLS_KEY=$HOME/my_client_key - ClientTLSKey io.Reader - - // The handlers that the session and all API clients will be created with. - // This must be a complete set of handlers. Use the defaults.Handlers() - // function to initialize this value before changing the handlers to be - // used by the SDK. - Handlers request.Handlers - - // Allows specifying a custom endpoint to be used by the EC2 IMDS client - // when making requests to the EC2 IMDS API. The endpoint value should - // include the URI scheme. If the scheme is not present it will be defaulted to http. - // - // If unset, will the EC2 IMDS client will use its default endpoint. - // - // Can also be specified via the environment variable, - // AWS_EC2_METADATA_SERVICE_ENDPOINT. - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://169.254.169.254 - // - // If using an URL with an IPv6 address literal, the IPv6 address - // component must be enclosed in square brackets. - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] - EC2IMDSEndpoint string - - // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6 - EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState - - // Specifies options for creating credential providers. - // These are only used if the aws.Config does not already - // include credentials. - CredentialsProviderOptions *CredentialsProviderOptions -} - -// NewSessionWithOptions returns a new Session created from SDK defaults, config files, -// environment, and user provided config files. This func uses the Options -// values to configure how the Session is created. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. Enabling the Shared Config will also allow the Session -// to be built with retrieving credentials with AssumeRole set in the config. -// -// // Equivalent to session.New -// sess := session.Must(session.NewSessionWithOptions(session.Options{})) -// -// // Specify profile to load for the session's config -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// Profile: "profile_name", -// })) -// -// // Specify profile for config and region for requests -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// Config: aws.Config{Region: aws.String("us-east-1")}, -// Profile: "profile_name", -// })) -// -// // Force enable Shared Config support -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// })) -func NewSessionWithOptions(opts Options) (*Session, error) { - var envCfg envConfig - var err error - if opts.SharedConfigState == SharedConfigEnable { - envCfg, err = loadSharedEnvConfig() - if err != nil { - return nil, fmt.Errorf("failed to load shared config, %v", err) - } - } else { - envCfg, err = loadEnvConfig() - if err != nil { - return nil, fmt.Errorf("failed to load environment config, %v", err) - } - } - - if len(opts.Profile) != 0 { - envCfg.Profile = opts.Profile - } - - switch opts.SharedConfigState { - case SharedConfigDisable: - envCfg.EnableSharedConfig = false - case SharedConfigEnable: - envCfg.EnableSharedConfig = true - } - - return newSession(opts, envCfg, &opts.Config) -} - -// Must is a helper function to ensure the Session is valid and there was no -// error when calling a NewSession function. -// -// This helper is intended to be used in variable initialization to load the -// Session and configuration at startup. Such as: -// -// var sess = session.Must(session.NewSession()) -func Must(sess *Session, err error) *Session { - if err != nil { - panic(err) - } - - return sess -} - -// Wraps the endpoint resolver with a resolver that will return a custom -// endpoint for EC2 IMDS. -func wrapEC2IMDSEndpoint(resolver endpoints.Resolver, endpoint string, mode endpoints.EC2IMDSEndpointModeState) endpoints.Resolver { - return endpoints.ResolverFunc( - func(service, region string, opts ...func(*endpoints.Options)) ( - endpoints.ResolvedEndpoint, error, - ) { - if service == ec2MetadataServiceID && len(endpoint) > 0 { - return endpoints.ResolvedEndpoint{ - URL: endpoint, - SigningName: ec2MetadataServiceID, - SigningRegion: region, - }, nil - } else if service == ec2MetadataServiceID { - opts = append(opts, func(o *endpoints.Options) { - o.EC2MetadataEndpointMode = mode - }) - } - return resolver.EndpointFor(service, region, opts...) - }) -} - -func deprecatedNewSession(envCfg envConfig, cfgs ...*aws.Config) *Session { - cfg := defaults.Config() - handlers := defaults.Handlers() - - // Apply the passed in configs so the configuration can be applied to the - // default credential chain - cfg.MergeIn(cfgs...) - if cfg.EndpointResolver == nil { - // An endpoint resolver is required for a session to be able to provide - // endpoints for service client configurations. - cfg.EndpointResolver = endpoints.DefaultResolver() - } - - if !(len(envCfg.EC2IMDSEndpoint) == 0 && envCfg.EC2IMDSEndpointMode == endpoints.EC2IMDSEndpointModeStateUnset) { - cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, envCfg.EC2IMDSEndpoint, envCfg.EC2IMDSEndpointMode) - } - - cfg.Credentials = defaults.CredChain(cfg, handlers) - - // Reapply any passed in configs to override credentials if set - cfg.MergeIn(cfgs...) - - s := &Session{ - Config: cfg, - Handlers: handlers, - options: Options{ - EC2IMDSEndpoint: envCfg.EC2IMDSEndpoint, - }, - } - - initHandlers(s) - return s -} - -func enableCSM(handlers *request.Handlers, cfg csmConfig, logger aws.Logger) error { - if logger != nil { - logger.Log("Enabling CSM") - } - - r, err := csm.Start(cfg.ClientID, csm.AddressWithDefaults(cfg.Host, cfg.Port)) - if err != nil { - return err - } - r.InjectHandlers(handlers) - - return nil -} - -func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { - cfg := defaults.Config() - - handlers := opts.Handlers - if handlers.IsEmpty() { - handlers = defaults.Handlers() - } - - // Get a merged version of the user provided config to determine if - // credentials were. - userCfg := &aws.Config{} - userCfg.MergeIn(cfgs...) - cfg.MergeIn(userCfg) - - // Ordered config files will be loaded in with later files overwriting - // previous config file values. - var cfgFiles []string - if opts.SharedConfigFiles != nil { - cfgFiles = opts.SharedConfigFiles - } else { - cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile} - if !envCfg.EnableSharedConfig { - // The shared config file (~/.aws/config) is only loaded if instructed - // to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG). - cfgFiles = cfgFiles[1:] - } - } - - // Load additional config from file(s) - sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles, envCfg.EnableSharedConfig) - if err != nil { - if len(envCfg.Profile) == 0 && !envCfg.EnableSharedConfig && (envCfg.Creds.HasKeys() || userCfg.Credentials != nil) { - // Special case where the user has not explicitly specified an AWS_PROFILE, - // or session.Options.profile, shared config is not enabled, and the - // environment has credentials, allow the shared config file to fail to - // load since the user has already provided credentials, and nothing else - // is required to be read file. Github(aws/aws-sdk-go#2455) - } else if _, ok := err.(SharedConfigProfileNotExistsError); !ok { - return nil, err - } - } - - if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil { - return nil, err - } - - if err := setTLSOptions(&opts, cfg, envCfg, sharedCfg); err != nil { - return nil, err - } - - s := &Session{ - Config: cfg, - Handlers: handlers, - options: opts, - } - - initHandlers(s) - - if csmCfg, err := loadCSMConfig(envCfg, cfgFiles); err != nil { - if l := s.Config.Logger; l != nil { - l.Log(fmt.Sprintf("ERROR: failed to load CSM configuration, %v", err)) - } - } else if csmCfg.Enabled { - err = enableCSM(&s.Handlers, csmCfg, s.Config.Logger) - if err != nil { - return nil, err - } - } - - return s, nil -} - -type csmConfig struct { - Enabled bool - Host string - Port string - ClientID string -} - -var csmProfileName = "aws_csm" - -func loadCSMConfig(envCfg envConfig, cfgFiles []string) (csmConfig, error) { - if envCfg.CSMEnabled != nil { - if *envCfg.CSMEnabled { - return csmConfig{ - Enabled: true, - ClientID: envCfg.CSMClientID, - Host: envCfg.CSMHost, - Port: envCfg.CSMPort, - }, nil - } - return csmConfig{}, nil - } - - sharedCfg, err := loadSharedConfig(csmProfileName, cfgFiles, false) - if err != nil { - if _, ok := err.(SharedConfigProfileNotExistsError); !ok { - return csmConfig{}, err - } - } - if sharedCfg.CSMEnabled != nil && *sharedCfg.CSMEnabled == true { - return csmConfig{ - Enabled: true, - ClientID: sharedCfg.CSMClientID, - Host: sharedCfg.CSMHost, - Port: sharedCfg.CSMPort, - }, nil - } - - return csmConfig{}, nil -} - -func setTLSOptions(opts *Options, cfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig) error { - // CA Bundle can be specified in both environment variable shared config file. - var caBundleFilename = envCfg.CustomCABundle - if len(caBundleFilename) == 0 { - caBundleFilename = sharedCfg.CustomCABundle - } - - // Only use environment value if session option is not provided. - customTLSOptions := map[string]struct { - filename string - field *io.Reader - errCode string - }{ - "custom CA bundle PEM": {filename: caBundleFilename, field: &opts.CustomCABundle, errCode: ErrCodeLoadCustomCABundle}, - "custom client TLS cert": {filename: envCfg.ClientTLSCert, field: &opts.ClientTLSCert, errCode: ErrCodeLoadClientTLSCert}, - "custom client TLS key": {filename: envCfg.ClientTLSKey, field: &opts.ClientTLSKey, errCode: ErrCodeLoadClientTLSCert}, - } - for name, v := range customTLSOptions { - if len(v.filename) != 0 && *v.field == nil { - f, err := os.Open(v.filename) - if err != nil { - return awserr.New(v.errCode, fmt.Sprintf("failed to open %s file", name), err) - } - defer f.Close() - *v.field = f - } - } - - // Setup HTTP client with custom cert bundle if enabled - if opts.CustomCABundle != nil { - if err := loadCustomCABundle(cfg.HTTPClient, opts.CustomCABundle); err != nil { - return err - } - } - - // Setup HTTP client TLS certificate and key for client TLS authentication. - if opts.ClientTLSCert != nil && opts.ClientTLSKey != nil { - if err := loadClientTLSCert(cfg.HTTPClient, opts.ClientTLSCert, opts.ClientTLSKey); err != nil { - return err - } - } else if opts.ClientTLSCert == nil && opts.ClientTLSKey == nil { - // Do nothing if neither values are available. - - } else { - return awserr.New(ErrCodeLoadClientTLSCert, - fmt.Sprintf("client TLS cert(%t) and key(%t) must both be provided", - opts.ClientTLSCert != nil, opts.ClientTLSKey != nil), nil) - } - - return nil -} - -func getHTTPTransport(client *http.Client) (*http.Transport, error) { - var t *http.Transport - switch v := client.Transport.(type) { - case *http.Transport: - t = v - default: - if client.Transport != nil { - return nil, fmt.Errorf("unsupported transport, %T", client.Transport) - } - } - if t == nil { - // Nil transport implies `http.DefaultTransport` should be used. Since - // the SDK cannot modify, nor copy the `DefaultTransport` specifying - // the values the next closest behavior. - t = getCustomTransport() - } - - return t, nil -} - -func loadCustomCABundle(client *http.Client, bundle io.Reader) error { - t, err := getHTTPTransport(client) - if err != nil { - return awserr.New(ErrCodeLoadCustomCABundle, - "unable to load custom CA bundle, HTTPClient's transport unsupported type", err) - } - - p, err := loadCertPool(bundle) - if err != nil { - return err - } - if t.TLSClientConfig == nil { - t.TLSClientConfig = &tls.Config{} - } - t.TLSClientConfig.RootCAs = p - - client.Transport = t - - return nil -} - -func loadCertPool(r io.Reader) (*x509.CertPool, error) { - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, awserr.New(ErrCodeLoadCustomCABundle, - "failed to read custom CA bundle PEM file", err) - } - - p := x509.NewCertPool() - if !p.AppendCertsFromPEM(b) { - return nil, awserr.New(ErrCodeLoadCustomCABundle, - "failed to load custom CA bundle PEM file", err) - } - - return p, nil -} - -func loadClientTLSCert(client *http.Client, certFile, keyFile io.Reader) error { - t, err := getHTTPTransport(client) - if err != nil { - return awserr.New(ErrCodeLoadClientTLSCert, - "unable to get usable HTTP transport from client", err) - } - - cert, err := ioutil.ReadAll(certFile) - if err != nil { - return awserr.New(ErrCodeLoadClientTLSCert, - "unable to get read client TLS cert file", err) - } - - key, err := ioutil.ReadAll(keyFile) - if err != nil { - return awserr.New(ErrCodeLoadClientTLSCert, - "unable to get read client TLS key file", err) - } - - clientCert, err := tls.X509KeyPair(cert, key) - if err != nil { - return awserr.New(ErrCodeLoadClientTLSCert, - "unable to load x509 key pair from client cert", err) - } - - tlsCfg := t.TLSClientConfig - if tlsCfg == nil { - tlsCfg = &tls.Config{} - } - - tlsCfg.Certificates = append(tlsCfg.Certificates, clientCert) - - t.TLSClientConfig = tlsCfg - client.Transport = t - - return nil -} - -func mergeConfigSrcs(cfg, userCfg *aws.Config, - envCfg envConfig, sharedCfg sharedConfig, - handlers request.Handlers, - sessOpts Options, -) error { - - // Region if not already set by user - if len(aws.StringValue(cfg.Region)) == 0 { - if len(envCfg.Region) > 0 { - cfg.WithRegion(envCfg.Region) - } else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 { - cfg.WithRegion(sharedCfg.Region) - } - } - - if cfg.EnableEndpointDiscovery == nil { - if envCfg.EnableEndpointDiscovery != nil { - cfg.WithEndpointDiscovery(*envCfg.EnableEndpointDiscovery) - } else if envCfg.EnableSharedConfig && sharedCfg.EnableEndpointDiscovery != nil { - cfg.WithEndpointDiscovery(*sharedCfg.EnableEndpointDiscovery) - } - } - - // Regional Endpoint flag for STS endpoint resolving - mergeSTSRegionalEndpointConfig(cfg, []endpoints.STSRegionalEndpoint{ - userCfg.STSRegionalEndpoint, - envCfg.STSRegionalEndpoint, - sharedCfg.STSRegionalEndpoint, - endpoints.LegacySTSEndpoint, - }) - - // Regional Endpoint flag for S3 endpoint resolving - mergeS3UsEast1RegionalEndpointConfig(cfg, []endpoints.S3UsEast1RegionalEndpoint{ - userCfg.S3UsEast1RegionalEndpoint, - envCfg.S3UsEast1RegionalEndpoint, - sharedCfg.S3UsEast1RegionalEndpoint, - endpoints.LegacyS3UsEast1Endpoint, - }) - - var ec2IMDSEndpoint string - for _, v := range []string{ - sessOpts.EC2IMDSEndpoint, - envCfg.EC2IMDSEndpoint, - sharedCfg.EC2IMDSEndpoint, - } { - if len(v) != 0 { - ec2IMDSEndpoint = v - break - } - } - - var endpointMode endpoints.EC2IMDSEndpointModeState - for _, v := range []endpoints.EC2IMDSEndpointModeState{ - sessOpts.EC2IMDSEndpointMode, - envCfg.EC2IMDSEndpointMode, - sharedCfg.EC2IMDSEndpointMode, - } { - if v != endpoints.EC2IMDSEndpointModeStateUnset { - endpointMode = v - break - } - } - - if len(ec2IMDSEndpoint) != 0 || endpointMode != endpoints.EC2IMDSEndpointModeStateUnset { - cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, ec2IMDSEndpoint, endpointMode) - } - - cfg.EC2MetadataEnableFallback = userCfg.EC2MetadataEnableFallback - if cfg.EC2MetadataEnableFallback == nil && envCfg.EC2IMDSv1Disabled != nil { - cfg.EC2MetadataEnableFallback = aws.Bool(!*envCfg.EC2IMDSv1Disabled) - } - if cfg.EC2MetadataEnableFallback == nil && sharedCfg.EC2IMDSv1Disabled != nil { - cfg.EC2MetadataEnableFallback = aws.Bool(!*sharedCfg.EC2IMDSv1Disabled) - } - - cfg.S3UseARNRegion = userCfg.S3UseARNRegion - if cfg.S3UseARNRegion == nil { - cfg.S3UseARNRegion = &envCfg.S3UseARNRegion - } - if cfg.S3UseARNRegion == nil { - cfg.S3UseARNRegion = &sharedCfg.S3UseARNRegion - } - - for _, v := range []endpoints.DualStackEndpointState{userCfg.UseDualStackEndpoint, envCfg.UseDualStackEndpoint, sharedCfg.UseDualStackEndpoint} { - if v != endpoints.DualStackEndpointStateUnset { - cfg.UseDualStackEndpoint = v - break - } - } - - for _, v := range []endpoints.FIPSEndpointState{userCfg.UseFIPSEndpoint, envCfg.UseFIPSEndpoint, sharedCfg.UseFIPSEndpoint} { - if v != endpoints.FIPSEndpointStateUnset { - cfg.UseFIPSEndpoint = v - break - } - } - - // Configure credentials if not already set by the user when creating the Session. - // Credentials are resolved last such that all _resolved_ config values are propagated to credential providers. - // ticket: P83606045 - if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { - creds, err := resolveCredentials(cfg, envCfg, sharedCfg, handlers, sessOpts) - if err != nil { - return err - } - cfg.Credentials = creds - } - - return nil -} - -func mergeSTSRegionalEndpointConfig(cfg *aws.Config, values []endpoints.STSRegionalEndpoint) { - for _, v := range values { - if v != endpoints.UnsetSTSEndpoint { - cfg.STSRegionalEndpoint = v - break - } - } -} - -func mergeS3UsEast1RegionalEndpointConfig(cfg *aws.Config, values []endpoints.S3UsEast1RegionalEndpoint) { - for _, v := range values { - if v != endpoints.UnsetS3UsEast1Endpoint { - cfg.S3UsEast1RegionalEndpoint = v - break - } - } -} - -func initHandlers(s *Session) { - // Add the Validate parameter handler if it is not disabled. - s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler) - if !aws.BoolValue(s.Config.DisableParamValidation) { - s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) - } -} - -// Copy creates and returns a copy of the current Session, copying the config -// and handlers. If any additional configs are provided they will be merged -// on top of the Session's copied config. -// -// // Create a copy of the current Session, configured for the us-west-2 region. -// sess.Copy(&aws.Config{Region: aws.String("us-west-2")}) -func (s *Session) Copy(cfgs ...*aws.Config) *Session { - newSession := &Session{ - Config: s.Config.Copy(cfgs...), - Handlers: s.Handlers.Copy(), - options: s.options, - } - - initHandlers(newSession) - - return newSession -} - -// ClientConfig satisfies the client.ConfigProvider interface and is used to -// configure the service client instances. Passing the Session to the service -// client's constructor (New) will use this method to configure the client. -func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Config { - s = s.Copy(cfgs...) - - resolvedRegion := normalizeRegion(s.Config) - - region := aws.StringValue(s.Config.Region) - resolved, err := s.resolveEndpoint(service, region, resolvedRegion, s.Config) - if err != nil { - s.Handlers.Validate.PushBack(func(r *request.Request) { - if len(r.ClientInfo.Endpoint) != 0 { - // Error occurred while resolving endpoint, but the request - // being invoked has had an endpoint specified after the client - // was created. - return - } - r.Error = err - }) - } - - return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - PartitionID: resolved.PartitionID, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningNameDerived: resolved.SigningNameDerived, - SigningName: resolved.SigningName, - ResolvedRegion: resolvedRegion, - } -} - -const ec2MetadataServiceID = "ec2metadata" - -func (s *Session) resolveEndpoint(service, region, resolvedRegion string, cfg *aws.Config) (endpoints.ResolvedEndpoint, error) { - - if ep := aws.StringValue(cfg.Endpoint); len(ep) != 0 { - return endpoints.ResolvedEndpoint{ - URL: endpoints.AddScheme(ep, aws.BoolValue(cfg.DisableSSL)), - SigningRegion: region, - }, nil - } - - resolved, err := cfg.EndpointResolver.EndpointFor(service, region, - func(opt *endpoints.Options) { - opt.DisableSSL = aws.BoolValue(cfg.DisableSSL) - - opt.UseDualStack = aws.BoolValue(cfg.UseDualStack) - opt.UseDualStackEndpoint = cfg.UseDualStackEndpoint - - opt.UseFIPSEndpoint = cfg.UseFIPSEndpoint - - // Support for STSRegionalEndpoint where the STSRegionalEndpoint is - // provided in envConfig or sharedConfig with envConfig getting - // precedence. - opt.STSRegionalEndpoint = cfg.STSRegionalEndpoint - - // Support for S3UsEast1RegionalEndpoint where the S3UsEast1RegionalEndpoint is - // provided in envConfig or sharedConfig with envConfig getting - // precedence. - opt.S3UsEast1RegionalEndpoint = cfg.S3UsEast1RegionalEndpoint - - // Support the condition where the service is modeled but its - // endpoint metadata is not available. - opt.ResolveUnknownService = true - - opt.ResolvedRegion = resolvedRegion - - opt.Logger = cfg.Logger - opt.LogDeprecated = cfg.LogLevel.Matches(aws.LogDebugWithDeprecated) - }, - ) - if err != nil { - return endpoints.ResolvedEndpoint{}, err - } - - return resolved, nil -} - -// ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception -// that the EndpointResolver will not be used to resolve the endpoint. The only -// endpoint set must come from the aws.Config.Endpoint field. -func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config { - s = s.Copy(cfgs...) - - resolvedRegion := normalizeRegion(s.Config) - - var resolved endpoints.ResolvedEndpoint - if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 { - resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL)) - resolved.SigningRegion = aws.StringValue(s.Config.Region) - } - - return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningNameDerived: resolved.SigningNameDerived, - SigningName: resolved.SigningName, - ResolvedRegion: resolvedRegion, - } -} - -// logDeprecatedNewSessionError function enables error handling for session -func (s *Session) logDeprecatedNewSessionError(msg string, err error, cfgs []*aws.Config) { - // Session creation failed, need to report the error and prevent - // any requests from succeeding. - s.Config.MergeIn(cfgs...) - s.Config.Logger.Log("ERROR:", msg, "Error:", err) - s.Handlers.Validate.PushBack(func(r *request.Request) { - r.Error = err - }) -} - -// normalizeRegion resolves / normalizes the configured region (converts pseudo fips regions), and modifies the provided -// config to have the equivalent options for resolution and returns the resolved region name. -func normalizeRegion(cfg *aws.Config) (resolved string) { - const fipsInfix = "-fips-" - const fipsPrefix = "-fips" - const fipsSuffix = "fips-" - - region := aws.StringValue(cfg.Region) - - if strings.Contains(region, fipsInfix) || - strings.Contains(region, fipsPrefix) || - strings.Contains(region, fipsSuffix) { - resolved = strings.Replace(strings.Replace(strings.Replace( - region, fipsInfix, "-", -1), fipsPrefix, "", -1), fipsSuffix, "", -1) - cfg.UseFIPSEndpoint = endpoints.FIPSEndpointStateEnabled - } - - return resolved -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go deleted file mode 100644 index f3ce8183d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go +++ /dev/null @@ -1,856 +0,0 @@ -package session - -import ( - "fmt" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/internal/ini" -) - -const ( - // Static Credentials group - accessKeyIDKey = `aws_access_key_id` // group required - secretAccessKey = `aws_secret_access_key` // group required - sessionTokenKey = `aws_session_token` // optional - - // Assume Role Credentials group - roleArnKey = `role_arn` // group required - sourceProfileKey = `source_profile` // group required (or credential_source) - credentialSourceKey = `credential_source` // group required (or source_profile) - externalIDKey = `external_id` // optional - mfaSerialKey = `mfa_serial` // optional - roleSessionNameKey = `role_session_name` // optional - roleDurationSecondsKey = "duration_seconds" // optional - - // Prefix to be used for SSO sections. These are supposed to only exist in - // the shared config file, not the credentials file. - ssoSectionPrefix = `sso-session ` - - // AWS Single Sign-On (AWS SSO) group - ssoSessionNameKey = "sso_session" - - // AWS Single Sign-On (AWS SSO) group - ssoAccountIDKey = "sso_account_id" - ssoRegionKey = "sso_region" - ssoRoleNameKey = "sso_role_name" - ssoStartURL = "sso_start_url" - - // CSM options - csmEnabledKey = `csm_enabled` - csmHostKey = `csm_host` - csmPortKey = `csm_port` - csmClientIDKey = `csm_client_id` - - // Additional Config fields - regionKey = `region` - - // custom CA Bundle filename - customCABundleKey = `ca_bundle` - - // endpoint discovery group - enableEndpointDiscoveryKey = `endpoint_discovery_enabled` // optional - - // External Credential Process - credentialProcessKey = `credential_process` // optional - - // Web Identity Token File - webIdentityTokenFileKey = `web_identity_token_file` // optional - - // Additional config fields for regional or legacy endpoints - stsRegionalEndpointSharedKey = `sts_regional_endpoints` - - // Additional config fields for regional or legacy endpoints - s3UsEast1RegionalSharedKey = `s3_us_east_1_regional_endpoint` - - // DefaultSharedConfigProfile is the default profile to be used when - // loading configuration from the config files if another profile name - // is not provided. - DefaultSharedConfigProfile = `default` - - // S3 ARN Region Usage - s3UseARNRegionKey = "s3_use_arn_region" - - // EC2 IMDS Endpoint Mode - ec2MetadataServiceEndpointModeKey = "ec2_metadata_service_endpoint_mode" - - // EC2 IMDS Endpoint - ec2MetadataServiceEndpointKey = "ec2_metadata_service_endpoint" - - // ECS IMDSv1 disable fallback - ec2MetadataV1DisabledKey = "ec2_metadata_v1_disabled" - - // Use DualStack Endpoint Resolution - useDualStackEndpoint = "use_dualstack_endpoint" - - // Use FIPS Endpoint Resolution - useFIPSEndpointKey = "use_fips_endpoint" -) - -// sharedConfig represents the configuration fields of the SDK config files. -type sharedConfig struct { - Profile string - - // Credentials values from the config file. Both aws_access_key_id and - // aws_secret_access_key must be provided together in the same file to be - // considered valid. The values will be ignored if not a complete group. - // aws_session_token is an optional field that can be provided if both of - // the other two fields are also provided. - // - // aws_access_key_id - // aws_secret_access_key - // aws_session_token - Creds credentials.Value - - CredentialSource string - CredentialProcess string - WebIdentityTokenFile string - - // SSO session options - SSOSessionName string - SSOSession *ssoSession - - SSOAccountID string - SSORegion string - SSORoleName string - SSOStartURL string - - RoleARN string - RoleSessionName string - ExternalID string - MFASerial string - AssumeRoleDuration *time.Duration - - SourceProfileName string - SourceProfile *sharedConfig - - // Region is the region the SDK should use for looking up AWS service - // endpoints and signing requests. - // - // region - Region string - - // CustomCABundle is the file path to a PEM file the SDK will read and - // use to configure the HTTP transport with additional CA certs that are - // not present in the platforms default CA store. - // - // This value will be ignored if the file does not exist. - // - // ca_bundle - CustomCABundle string - - // EnableEndpointDiscovery can be enabled in the shared config by setting - // endpoint_discovery_enabled to true - // - // endpoint_discovery_enabled = true - EnableEndpointDiscovery *bool - - // CSM Options - CSMEnabled *bool - CSMHost string - CSMPort string - CSMClientID string - - // Specifies the Regional Endpoint flag for the SDK to resolve the endpoint for a service - // - // sts_regional_endpoints = regional - // This can take value as `LegacySTSEndpoint` or `RegionalSTSEndpoint` - STSRegionalEndpoint endpoints.STSRegionalEndpoint - - // Specifies the Regional Endpoint flag for the SDK to resolve the endpoint for a service - // - // s3_us_east_1_regional_endpoint = regional - // This can take value as `LegacyS3UsEast1Endpoint` or `RegionalS3UsEast1Endpoint` - S3UsEast1RegionalEndpoint endpoints.S3UsEast1RegionalEndpoint - - // Specifies if the S3 service should allow ARNs to direct the region - // the client's requests are sent to. - // - // s3_use_arn_region=true - S3UseARNRegion bool - - // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) - // - // ec2_metadata_service_endpoint_mode=IPv6 - EC2IMDSEndpointMode endpoints.EC2IMDSEndpointModeState - - // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EC2IMDSEndpointMode. - // - // ec2_metadata_service_endpoint=http://fd00:ec2::254 - EC2IMDSEndpoint string - - // Specifies that IMDS clients should not fallback to IMDSv1 if token - // requests fail. - // - // ec2_metadata_v1_disabled=true - EC2IMDSv1Disabled *bool - - // Specifies that SDK clients must resolve a dual-stack endpoint for - // services. - // - // use_dualstack_endpoint=true - UseDualStackEndpoint endpoints.DualStackEndpointState - - // Specifies that SDK clients must resolve a FIPS endpoint for - // services. - // - // use_fips_endpoint=true - UseFIPSEndpoint endpoints.FIPSEndpointState -} - -type sharedConfigFile struct { - Filename string - IniData ini.Sections -} - -// SSOSession provides the shared configuration parameters of the sso-session -// section. -type ssoSession struct { - Name string - SSORegion string - SSOStartURL string -} - -func (s *ssoSession) setFromIniSection(section ini.Section) { - updateString(&s.Name, section, ssoSessionNameKey) - updateString(&s.SSORegion, section, ssoRegionKey) - updateString(&s.SSOStartURL, section, ssoStartURL) -} - -// loadSharedConfig retrieves the configuration from the list of files using -// the profile provided. The order the files are listed will determine -// precedence. Values in subsequent files will overwrite values defined in -// earlier files. -// -// For example, given two files A and B. Both define credentials. If the order -// of the files are A then B, B's credential values will be used instead of -// A's. -// -// See sharedConfig.setFromFile for information how the config files -// will be loaded. -func loadSharedConfig(profile string, filenames []string, exOpts bool) (sharedConfig, error) { - if len(profile) == 0 { - profile = DefaultSharedConfigProfile - } - - files, err := loadSharedConfigIniFiles(filenames) - if err != nil { - return sharedConfig{}, err - } - - cfg := sharedConfig{} - profiles := map[string]struct{}{} - if err = cfg.setFromIniFiles(profiles, profile, files, exOpts); err != nil { - return sharedConfig{}, err - } - - return cfg, nil -} - -func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) { - files := make([]sharedConfigFile, 0, len(filenames)) - - for _, filename := range filenames { - sections, err := ini.OpenFile(filename) - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == ini.ErrCodeUnableToReadFile { - // Skip files which can't be opened and read for whatever reason - continue - } else if err != nil { - return nil, SharedConfigLoadError{Filename: filename, Err: err} - } - - files = append(files, sharedConfigFile{ - Filename: filename, IniData: sections, - }) - } - - return files, nil -} - -func (cfg *sharedConfig) setFromIniFiles(profiles map[string]struct{}, profile string, files []sharedConfigFile, exOpts bool) error { - cfg.Profile = profile - - // Trim files from the list that don't exist. - var skippedFiles int - var profileNotFoundErr error - for _, f := range files { - if err := cfg.setFromIniFile(profile, f, exOpts); err != nil { - if _, ok := err.(SharedConfigProfileNotExistsError); ok { - // Ignore profiles not defined in individual files. - profileNotFoundErr = err - skippedFiles++ - continue - } - return err - } - } - if skippedFiles == len(files) { - // If all files were skipped because the profile is not found, return - // the original profile not found error. - return profileNotFoundErr - } - - if _, ok := profiles[profile]; ok { - // if this is the second instance of the profile the Assume Role - // options must be cleared because they are only valid for the - // first reference of a profile. The self linked instance of the - // profile only have credential provider options. - cfg.clearAssumeRoleOptions() - } else { - // First time a profile has been seen. Assert if the credential type - // requires a role ARN, the ARN is also set - if err := cfg.validateCredentialsConfig(profile); err != nil { - return err - } - } - - profiles[profile] = struct{}{} - - if err := cfg.validateCredentialType(); err != nil { - return err - } - - // Link source profiles for assume roles - if len(cfg.SourceProfileName) != 0 { - // Linked profile via source_profile ignore credential provider - // options, the source profile must provide the credentials. - cfg.clearCredentialOptions() - - srcCfg := &sharedConfig{} - err := srcCfg.setFromIniFiles(profiles, cfg.SourceProfileName, files, exOpts) - if err != nil { - // SourceProfile that doesn't exist is an error in configuration. - if _, ok := err.(SharedConfigProfileNotExistsError); ok { - err = SharedConfigAssumeRoleError{ - RoleARN: cfg.RoleARN, - SourceProfile: cfg.SourceProfileName, - } - } - return err - } - - if !srcCfg.hasCredentials() { - return SharedConfigAssumeRoleError{ - RoleARN: cfg.RoleARN, - SourceProfile: cfg.SourceProfileName, - } - } - - cfg.SourceProfile = srcCfg - } - - // If the profile contains an SSO session parameter, the session MUST exist - // as a section in the config file. Load the SSO session using the name - // provided. If the session section is not found or incomplete an error - // will be returned. - if cfg.hasSSOTokenProviderConfiguration() { - skippedFiles = 0 - for _, f := range files { - section, ok := f.IniData.GetSection(fmt.Sprintf(ssoSectionPrefix + strings.TrimSpace(cfg.SSOSessionName))) - if ok { - var ssoSession ssoSession - ssoSession.setFromIniSection(section) - ssoSession.Name = cfg.SSOSessionName - cfg.SSOSession = &ssoSession - break - } - skippedFiles++ - } - if skippedFiles == len(files) { - // If all files were skipped because the sso session section is not found, return - // the sso section not found error. - return fmt.Errorf("failed to find SSO session section, %v", cfg.SSOSessionName) - } - } - - return nil -} - -// setFromFile loads the configuration from the file using the profile -// provided. A sharedConfig pointer type value is used so that multiple config -// file loadings can be chained. -// -// Only loads complete logically grouped values, and will not set fields in cfg -// for incomplete grouped values in the config. Such as credentials. For -// example if a config file only includes aws_access_key_id but no -// aws_secret_access_key the aws_access_key_id will be ignored. -func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile, exOpts bool) error { - section, ok := file.IniData.GetSection(profile) - if !ok { - // Fallback to to alternate profile name: profile - section, ok = file.IniData.GetSection(fmt.Sprintf("profile %s", profile)) - if !ok { - return SharedConfigProfileNotExistsError{Profile: profile, Err: nil} - } - } - - if exOpts { - // Assume Role Parameters - updateString(&cfg.RoleARN, section, roleArnKey) - updateString(&cfg.ExternalID, section, externalIDKey) - updateString(&cfg.MFASerial, section, mfaSerialKey) - updateString(&cfg.RoleSessionName, section, roleSessionNameKey) - updateString(&cfg.SourceProfileName, section, sourceProfileKey) - updateString(&cfg.CredentialSource, section, credentialSourceKey) - updateString(&cfg.Region, section, regionKey) - updateString(&cfg.CustomCABundle, section, customCABundleKey) - - // we're retaining a behavioral quirk with this field that existed before - // the removal of literal parsing for (aws-sdk-go-v2/#2276): - // - if the key is missing, the config field will not be set - // - if the key is set to a non-numeric, the config field will be set to 0 - if section.Has(roleDurationSecondsKey) { - var d time.Duration - if v, ok := section.Int(roleDurationSecondsKey); ok { - d = time.Duration(v) * time.Second - } - cfg.AssumeRoleDuration = &d - } - - if v := section.String(stsRegionalEndpointSharedKey); len(v) != 0 { - sre, err := endpoints.GetSTSRegionalEndpoint(v) - if err != nil { - return fmt.Errorf("failed to load %s from shared config, %s, %v", - stsRegionalEndpointSharedKey, file.Filename, err) - } - cfg.STSRegionalEndpoint = sre - } - - if v := section.String(s3UsEast1RegionalSharedKey); len(v) != 0 { - sre, err := endpoints.GetS3UsEast1RegionalEndpoint(v) - if err != nil { - return fmt.Errorf("failed to load %s from shared config, %s, %v", - s3UsEast1RegionalSharedKey, file.Filename, err) - } - cfg.S3UsEast1RegionalEndpoint = sre - } - - // AWS Single Sign-On (AWS SSO) - // SSO session options - updateString(&cfg.SSOSessionName, section, ssoSessionNameKey) - - // AWS Single Sign-On (AWS SSO) - updateString(&cfg.SSOAccountID, section, ssoAccountIDKey) - updateString(&cfg.SSORegion, section, ssoRegionKey) - updateString(&cfg.SSORoleName, section, ssoRoleNameKey) - updateString(&cfg.SSOStartURL, section, ssoStartURL) - - if err := updateEC2MetadataServiceEndpointMode(&cfg.EC2IMDSEndpointMode, section, ec2MetadataServiceEndpointModeKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %s, %v", - ec2MetadataServiceEndpointModeKey, file.Filename, err) - } - updateString(&cfg.EC2IMDSEndpoint, section, ec2MetadataServiceEndpointKey) - updateBoolPtr(&cfg.EC2IMDSv1Disabled, section, ec2MetadataV1DisabledKey) - - updateUseDualStackEndpoint(&cfg.UseDualStackEndpoint, section, useDualStackEndpoint) - - updateUseFIPSEndpoint(&cfg.UseFIPSEndpoint, section, useFIPSEndpointKey) - } - - updateString(&cfg.CredentialProcess, section, credentialProcessKey) - updateString(&cfg.WebIdentityTokenFile, section, webIdentityTokenFileKey) - - // Shared Credentials - creds := credentials.Value{ - AccessKeyID: section.String(accessKeyIDKey), - SecretAccessKey: section.String(secretAccessKey), - SessionToken: section.String(sessionTokenKey), - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", file.Filename), - } - if creds.HasKeys() { - cfg.Creds = creds - } - - // Endpoint discovery - updateBoolPtr(&cfg.EnableEndpointDiscovery, section, enableEndpointDiscoveryKey) - - // CSM options - updateBoolPtr(&cfg.CSMEnabled, section, csmEnabledKey) - updateString(&cfg.CSMHost, section, csmHostKey) - updateString(&cfg.CSMPort, section, csmPortKey) - updateString(&cfg.CSMClientID, section, csmClientIDKey) - - updateBool(&cfg.S3UseARNRegion, section, s3UseARNRegionKey) - - return nil -} - -func updateEC2MetadataServiceEndpointMode(endpointMode *endpoints.EC2IMDSEndpointModeState, section ini.Section, key string) error { - if !section.Has(key) { - return nil - } - value := section.String(key) - return endpointMode.SetFromString(value) -} - -func (cfg *sharedConfig) validateCredentialsConfig(profile string) error { - if err := cfg.validateCredentialsRequireARN(profile); err != nil { - return err - } - - return nil -} - -func (cfg *sharedConfig) validateCredentialsRequireARN(profile string) error { - var credSource string - - switch { - case len(cfg.SourceProfileName) != 0: - credSource = sourceProfileKey - case len(cfg.CredentialSource) != 0: - credSource = credentialSourceKey - case len(cfg.WebIdentityTokenFile) != 0: - credSource = webIdentityTokenFileKey - } - - if len(credSource) != 0 && len(cfg.RoleARN) == 0 { - return CredentialRequiresARNError{ - Type: credSource, - Profile: profile, - } - } - - return nil -} - -func (cfg *sharedConfig) validateCredentialType() error { - // Only one or no credential type can be defined. - if !oneOrNone( - len(cfg.SourceProfileName) != 0, - len(cfg.CredentialSource) != 0, - len(cfg.CredentialProcess) != 0, - len(cfg.WebIdentityTokenFile) != 0, - ) { - return ErrSharedConfigSourceCollision - } - - return nil -} - -func (cfg *sharedConfig) validateSSOConfiguration() error { - if cfg.hasSSOTokenProviderConfiguration() { - err := cfg.validateSSOTokenProviderConfiguration() - if err != nil { - return err - } - return nil - } - - if cfg.hasLegacySSOConfiguration() { - err := cfg.validateLegacySSOConfiguration() - if err != nil { - return err - } - } - return nil -} - -func (cfg *sharedConfig) hasCredentials() bool { - switch { - case len(cfg.SourceProfileName) != 0: - case len(cfg.CredentialSource) != 0: - case len(cfg.CredentialProcess) != 0: - case len(cfg.WebIdentityTokenFile) != 0: - case cfg.hasSSOConfiguration(): - case cfg.Creds.HasKeys(): - default: - return false - } - - return true -} - -func (cfg *sharedConfig) clearCredentialOptions() { - cfg.CredentialSource = "" - cfg.CredentialProcess = "" - cfg.WebIdentityTokenFile = "" - cfg.Creds = credentials.Value{} - cfg.SSOAccountID = "" - cfg.SSORegion = "" - cfg.SSORoleName = "" - cfg.SSOStartURL = "" -} - -func (cfg *sharedConfig) clearAssumeRoleOptions() { - cfg.RoleARN = "" - cfg.ExternalID = "" - cfg.MFASerial = "" - cfg.RoleSessionName = "" - cfg.SourceProfileName = "" -} - -func (cfg *sharedConfig) hasSSOConfiguration() bool { - return cfg.hasSSOTokenProviderConfiguration() || cfg.hasLegacySSOConfiguration() -} - -func (c *sharedConfig) hasSSOTokenProviderConfiguration() bool { - return len(c.SSOSessionName) > 0 -} - -func (c *sharedConfig) hasLegacySSOConfiguration() bool { - return len(c.SSORegion) > 0 || len(c.SSOAccountID) > 0 || len(c.SSOStartURL) > 0 || len(c.SSORoleName) > 0 -} - -func (c *sharedConfig) validateSSOTokenProviderConfiguration() error { - var missing []string - - if len(c.SSOSessionName) == 0 { - missing = append(missing, ssoSessionNameKey) - } - - if c.SSOSession == nil { - missing = append(missing, ssoSectionPrefix) - } else { - if len(c.SSOSession.SSORegion) == 0 { - missing = append(missing, ssoRegionKey) - } - - if len(c.SSOSession.SSOStartURL) == 0 { - missing = append(missing, ssoStartURL) - } - } - - if len(missing) > 0 { - return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", - c.Profile, strings.Join(missing, ", ")) - } - - if len(c.SSORegion) > 0 && c.SSORegion != c.SSOSession.SSORegion { - return fmt.Errorf("%s in profile %q must match %s in %s", ssoRegionKey, c.Profile, ssoRegionKey, ssoSectionPrefix) - } - - if len(c.SSOStartURL) > 0 && c.SSOStartURL != c.SSOSession.SSOStartURL { - return fmt.Errorf("%s in profile %q must match %s in %s", ssoStartURL, c.Profile, ssoStartURL, ssoSectionPrefix) - } - - return nil -} - -func (c *sharedConfig) validateLegacySSOConfiguration() error { - var missing []string - - if len(c.SSORegion) == 0 { - missing = append(missing, ssoRegionKey) - } - - if len(c.SSOStartURL) == 0 { - missing = append(missing, ssoStartURL) - } - - if len(c.SSOAccountID) == 0 { - missing = append(missing, ssoAccountIDKey) - } - - if len(c.SSORoleName) == 0 { - missing = append(missing, ssoRoleNameKey) - } - - if len(missing) > 0 { - return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", - c.Profile, strings.Join(missing, ", ")) - } - return nil -} - -func oneOrNone(bs ...bool) bool { - var count int - - for _, b := range bs { - if b { - count++ - if count > 1 { - return false - } - } - } - - return true -} - -// updateString will only update the dst with the value in the section key, key -// is present in the section. -func updateString(dst *string, section ini.Section, key string) { - if !section.Has(key) { - return - } - *dst = section.String(key) -} - -// updateBool will only update the dst with the value in the section key, key -// is present in the section. -func updateBool(dst *bool, section ini.Section, key string) { - if !section.Has(key) { - return - } - - // retains pre-(aws-sdk-go-v2#2276) behavior where non-bool value would resolve to false - v, _ := section.Bool(key) - *dst = v -} - -// updateBoolPtr will only update the dst with the value in the section key, -// key is present in the section. -func updateBoolPtr(dst **bool, section ini.Section, key string) { - if !section.Has(key) { - return - } - - // retains pre-(aws-sdk-go-v2#2276) behavior where non-bool value would resolve to false - v, _ := section.Bool(key) - *dst = new(bool) - **dst = v -} - -// SharedConfigLoadError is an error for the shared config file failed to load. -type SharedConfigLoadError struct { - Filename string - Err error -} - -// Code is the short id of the error. -func (e SharedConfigLoadError) Code() string { - return "SharedConfigLoadError" -} - -// Message is the description of the error -func (e SharedConfigLoadError) Message() string { - return fmt.Sprintf("failed to load config file, %s", e.Filename) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigLoadError) OrigErr() error { - return e.Err -} - -// Error satisfies the error interface. -func (e SharedConfigLoadError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", e.Err) -} - -// SharedConfigProfileNotExistsError is an error for the shared config when -// the profile was not find in the config file. -type SharedConfigProfileNotExistsError struct { - Profile string - Err error -} - -// Code is the short id of the error. -func (e SharedConfigProfileNotExistsError) Code() string { - return "SharedConfigProfileNotExistsError" -} - -// Message is the description of the error -func (e SharedConfigProfileNotExistsError) Message() string { - return fmt.Sprintf("failed to get profile, %s", e.Profile) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigProfileNotExistsError) OrigErr() error { - return e.Err -} - -// Error satisfies the error interface. -func (e SharedConfigProfileNotExistsError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", e.Err) -} - -// SharedConfigAssumeRoleError is an error for the shared config when the -// profile contains assume role information, but that information is invalid -// or not complete. -type SharedConfigAssumeRoleError struct { - RoleARN string - SourceProfile string -} - -// Code is the short id of the error. -func (e SharedConfigAssumeRoleError) Code() string { - return "SharedConfigAssumeRoleError" -} - -// Message is the description of the error -func (e SharedConfigAssumeRoleError) Message() string { - return fmt.Sprintf( - "failed to load assume role for %s, source profile %s has no shared credentials", - e.RoleARN, e.SourceProfile, - ) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigAssumeRoleError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e SharedConfigAssumeRoleError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} - -// CredentialRequiresARNError provides the error for shared config credentials -// that are incorrectly configured in the shared config or credentials file. -type CredentialRequiresARNError struct { - // type of credentials that were configured. - Type string - - // Profile name the credentials were in. - Profile string -} - -// Code is the short id of the error. -func (e CredentialRequiresARNError) Code() string { - return "CredentialRequiresARNError" -} - -// Message is the description of the error -func (e CredentialRequiresARNError) Message() string { - return fmt.Sprintf( - "credential type %s requires role_arn, profile %s", - e.Type, e.Profile, - ) -} - -// OrigErr is the underlying error that caused the failure. -func (e CredentialRequiresARNError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e CredentialRequiresARNError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} - -// updateEndpointDiscoveryType will only update the dst with the value in the section, if -// a valid key and corresponding EndpointDiscoveryType is found. -func updateUseDualStackEndpoint(dst *endpoints.DualStackEndpointState, section ini.Section, key string) { - if !section.Has(key) { - return - } - - // retains pre-(aws-sdk-go-v2/#2276) behavior where non-bool value would resolve to false - if v, _ := section.Bool(key); v { - *dst = endpoints.DualStackEndpointStateEnabled - } else { - *dst = endpoints.DualStackEndpointStateDisabled - } - - return -} - -// updateEndpointDiscoveryType will only update the dst with the value in the section, if -// a valid key and corresponding EndpointDiscoveryType is found. -func updateUseFIPSEndpoint(dst *endpoints.FIPSEndpointState, section ini.Section, key string) { - if !section.Has(key) { - return - } - - // retains pre-(aws-sdk-go-v2/#2276) behavior where non-bool value would resolve to false - if v, _ := section.Bool(key); v { - *dst = endpoints.FIPSEndpointStateEnabled - } else { - *dst = endpoints.FIPSEndpointStateDisabled - } - - return -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go deleted file mode 100644 index 993753831..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go +++ /dev/null @@ -1,81 +0,0 @@ -package v4 - -import ( - "github.com/aws/aws-sdk-go/internal/strings" -) - -// validator houses a set of rule needed for validation of a -// string value -type rules []rule - -// rule interface allows for more flexible rules and just simply -// checks whether or not a value adheres to that rule -type rule interface { - IsValid(value string) bool -} - -// IsValid will iterate through all rules and see if any rules -// apply to the value and supports nested rules -func (r rules) IsValid(value string) bool { - for _, rule := range r { - if rule.IsValid(value) { - return true - } - } - return false -} - -// mapRule generic rule for maps -type mapRule map[string]struct{} - -// IsValid for the map rule satisfies whether it exists in the map -func (m mapRule) IsValid(value string) bool { - _, ok := m[value] - return ok -} - -// allowList is a generic rule for allow listing -type allowList struct { - rule -} - -// IsValid for allow list checks if the value is within the allow list -func (w allowList) IsValid(value string) bool { - return w.rule.IsValid(value) -} - -// excludeList is a generic rule for exclude listing -type excludeList struct { - rule -} - -// IsValid for exclude list checks if the value is within the exclude list -func (b excludeList) IsValid(value string) bool { - return !b.rule.IsValid(value) -} - -type patterns []string - -// IsValid for patterns checks each pattern and returns if a match has -// been found -func (p patterns) IsValid(value string) bool { - for _, pattern := range p { - if strings.HasPrefixFold(value, pattern) { - return true - } - } - return false -} - -// inclusiveRules rules allow for rules to depend on one another -type inclusiveRules []rule - -// IsValid will return true if all rules are true -func (r inclusiveRules) IsValid(value string) bool { - for _, rule := range r { - if !rule.IsValid(value) { - return false - } - } - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go deleted file mode 100644 index 6aa2ed241..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go +++ /dev/null @@ -1,7 +0,0 @@ -package v4 - -// WithUnsignedPayload will enable and set the UnsignedPayload field to -// true of the signer. -func WithUnsignedPayload(v4 *Signer) { - v4.UnsignedPayload = true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/request_context_go1.5.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/request_context_go1.5.go deleted file mode 100644 index cf672b6ac..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/request_context_go1.5.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !go1.7 -// +build !go1.7 - -package v4 - -import ( - "net/http" - - "github.com/aws/aws-sdk-go/aws" -) - -func requestContext(r *http.Request) aws.Context { - return aws.BackgroundContext() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/request_context_go1.7.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/request_context_go1.7.go deleted file mode 100644 index 21fe74e6f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/request_context_go1.7.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build go1.7 -// +build go1.7 - -package v4 - -import ( - "net/http" - - "github.com/aws/aws-sdk-go/aws" -) - -func requestContext(r *http.Request) aws.Context { - return r.Context() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/stream.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/stream.go deleted file mode 100644 index 02cbd97e2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/stream.go +++ /dev/null @@ -1,63 +0,0 @@ -package v4 - -import ( - "encoding/hex" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/credentials" -) - -type credentialValueProvider interface { - Get() (credentials.Value, error) -} - -// StreamSigner implements signing of event stream encoded payloads -type StreamSigner struct { - region string - service string - - credentials credentialValueProvider - - prevSig []byte -} - -// NewStreamSigner creates a SigV4 signer used to sign Event Stream encoded messages -func NewStreamSigner(region, service string, seedSignature []byte, credentials *credentials.Credentials) *StreamSigner { - return &StreamSigner{ - region: region, - service: service, - credentials: credentials, - prevSig: seedSignature, - } -} - -// GetSignature takes an event stream encoded headers and payload and returns a signature -func (s *StreamSigner) GetSignature(headers, payload []byte, date time.Time) ([]byte, error) { - credValue, err := s.credentials.Get() - if err != nil { - return nil, err - } - - sigKey := deriveSigningKey(s.region, s.service, credValue.SecretAccessKey, date) - - keyPath := buildSigningScope(s.region, s.service, date) - - stringToSign := buildEventStreamStringToSign(headers, payload, s.prevSig, keyPath, date) - - signature := hmacSHA256(sigKey, []byte(stringToSign)) - s.prevSig = signature - - return signature, nil -} - -func buildEventStreamStringToSign(headers, payload, prevSig []byte, scope string, date time.Time) string { - return strings.Join([]string{ - "AWS4-HMAC-SHA256-PAYLOAD", - formatTime(date), - scope, - hex.EncodeToString(prevSig), - hex.EncodeToString(hashSHA256(headers)), - hex.EncodeToString(hashSHA256(payload)), - }, "\n") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go deleted file mode 100644 index 7711ec737..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build go1.5 -// +build go1.5 - -package v4 - -import ( - "net/url" - "strings" -) - -func getURIPath(u *url.URL) string { - var uri string - - if len(u.Opaque) > 0 { - uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/") - } else { - uri = u.EscapedPath() - } - - if len(uri) == 0 { - uri = "/" - } - - return uri -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go deleted file mode 100644 index b542df931..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ /dev/null @@ -1,857 +0,0 @@ -// Package v4 implements signing for AWS V4 signer -// -// Provides request signing for request that need to be signed with -// AWS V4 Signatures. -// -// # Standalone Signer -// -// Generally using the signer outside of the SDK should not require any additional -// logic when using Go v1.5 or higher. The signer does this by taking advantage -// of the URL.EscapedPath method. If your request URI requires additional escaping -// you may need to use the URL.Opaque to define what the raw URI should be sent -// to the service as. -// -// The signer will first check the URL.Opaque field, and use its value if set. -// The signer does require the URL.Opaque field to be set in the form of: -// -// "///" -// -// // e.g. -// "//example.com/some/path" -// -// The leading "//" and hostname are required or the URL.Opaque escaping will -// not work correctly. -// -// If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() -// method and using the returned value. If you're using Go v1.4 you must set -// URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with -// Go v1.5 the signer will fallback to URL.Path. -// -// AWS v4 signature validation requires that the canonical string's URI path -// element must be the URI escaped form of the HTTP request's path. -// http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html -// -// The Go HTTP client will perform escaping automatically on the request. Some -// of these escaping may cause signature validation errors because the HTTP -// request differs from the URI path or query that the signature was generated. -// https://golang.org/pkg/net/url/#URL.EscapedPath -// -// Because of this, it is recommended that when using the signer outside of the -// SDK that explicitly escaping the request prior to being signed is preferable, -// and will help prevent signature validation errors. This can be done by setting -// the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then -// call URL.EscapedPath() if Opaque is not set. -// -// If signing a request intended for HTTP2 server, and you're using Go 1.6.2 -// through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the -// request URL. https://github.com/golang/go/issues/16847 points to a bug in -// Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP -// message. URL.Opaque generally will force Go to make requests with absolute URL. -// URL.RawPath does not do this, but RawPath must be a valid escaping of Path -// or url.EscapedPath will ignore the RawPath escaping. -// -// Test `TestStandaloneSign` provides a complete example of using the signer -// outside of the SDK and pre-escaping the URI path. -package v4 - -import ( - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkio" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -const ( - authorizationHeader = "Authorization" - authHeaderSignatureElem = "Signature=" - signatureQueryKey = "X-Amz-Signature" - - authHeaderPrefix = "AWS4-HMAC-SHA256" - timeFormat = "20060102T150405Z" - shortTimeFormat = "20060102" - awsV4Request = "aws4_request" - - // emptyStringSHA256 is a SHA256 of an empty string - emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` -) - -var ignoredHeaders = rules{ - excludeList{ - mapRule{ - authorizationHeader: struct{}{}, - "User-Agent": struct{}{}, - "X-Amzn-Trace-Id": struct{}{}, - }, - }, -} - -// requiredSignedHeaders is a allow list for build canonical headers. -var requiredSignedHeaders = rules{ - allowList{ - mapRule{ - "Cache-Control": struct{}{}, - "Content-Disposition": struct{}{}, - "Content-Encoding": struct{}{}, - "Content-Language": struct{}{}, - "Content-Md5": struct{}{}, - "Content-Type": struct{}{}, - "Expires": struct{}{}, - "If-Match": struct{}{}, - "If-Modified-Since": struct{}{}, - "If-None-Match": struct{}{}, - "If-Unmodified-Since": struct{}{}, - "Range": struct{}{}, - "X-Amz-Acl": struct{}{}, - "X-Amz-Copy-Source": struct{}{}, - "X-Amz-Copy-Source-If-Match": struct{}{}, - "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, - "X-Amz-Copy-Source-If-None-Match": struct{}{}, - "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, - "X-Amz-Copy-Source-Range": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Expected-Bucket-Owner": struct{}{}, - "X-Amz-Grant-Full-control": struct{}{}, - "X-Amz-Grant-Read": struct{}{}, - "X-Amz-Grant-Read-Acp": struct{}{}, - "X-Amz-Grant-Write": struct{}{}, - "X-Amz-Grant-Write-Acp": struct{}{}, - "X-Amz-Metadata-Directive": struct{}{}, - "X-Amz-Mfa": struct{}{}, - "X-Amz-Request-Payer": struct{}{}, - "X-Amz-Server-Side-Encryption": struct{}{}, - "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, - "X-Amz-Server-Side-Encryption-Context": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Storage-Class": struct{}{}, - "X-Amz-Tagging": struct{}{}, - "X-Amz-Website-Redirect-Location": struct{}{}, - "X-Amz-Content-Sha256": struct{}{}, - }, - }, - patterns{"X-Amz-Meta-"}, - patterns{"X-Amz-Object-Lock-"}, -} - -// allowedHoisting is a allow list for build query headers. The boolean value -// represents whether or not it is a pattern. -var allowedQueryHoisting = inclusiveRules{ - excludeList{requiredSignedHeaders}, - patterns{"X-Amz-"}, -} - -// Signer applies AWS v4 signing to given request. Use this to sign requests -// that need to be signed with AWS V4 Signatures. -type Signer struct { - // The authentication credentials the request will be signed against. - // This value must be set to sign requests. - Credentials *credentials.Credentials - - // Sets the log level the signer should use when reporting information to - // the logger. If the logger is nil nothing will be logged. See - // aws.LogLevelType for more information on available logging levels - // - // By default nothing will be logged. - Debug aws.LogLevelType - - // The logger loging information will be written to. If there the logger - // is nil, nothing will be logged. - Logger aws.Logger - - // Disables the Signer's moving HTTP header key/value pairs from the HTTP - // request header to the request's query string. This is most commonly used - // with pre-signed requests preventing headers from being added to the - // request's query string. - DisableHeaderHoisting bool - - // Disables the automatic escaping of the URI path of the request for the - // siganture's canonical string's path. For services that do not need additional - // escaping then use this to disable the signer escaping the path. - // - // S3 is an example of a service that does not need additional escaping. - // - // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html - DisableURIPathEscaping bool - - // Disables the automatical setting of the HTTP request's Body field with the - // io.ReadSeeker passed in to the signer. This is useful if you're using a - // custom wrapper around the body for the io.ReadSeeker and want to preserve - // the Body value on the Request.Body. - // - // This does run the risk of signing a request with a body that will not be - // sent in the request. Need to ensure that the underlying data of the Body - // values are the same. - DisableRequestBodyOverwrite bool - - // currentTimeFn returns the time value which represents the current time. - // This value should only be used for testing. If it is nil the default - // time.Now will be used. - currentTimeFn func() time.Time - - // UnsignedPayload will prevent signing of the payload. This will only - // work for services that have support for this. - UnsignedPayload bool -} - -// NewSigner returns a Signer pointer configured with the credentials and optional -// option values provided. If not options are provided the Signer will use its -// default configuration. -func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer { - v4 := &Signer{ - Credentials: credentials, - } - - for _, option := range options { - option(v4) - } - - return v4 -} - -type signingCtx struct { - ServiceName string - Region string - Request *http.Request - Body io.ReadSeeker - Query url.Values - Time time.Time - ExpireTime time.Duration - SignedHeaderVals http.Header - - DisableURIPathEscaping bool - - credValues credentials.Value - isPresign bool - unsignedPayload bool - - bodyDigest string - signedHeaders string - canonicalHeaders string - canonicalString string - credentialString string - stringToSign string - signature string - authorization string -} - -// Sign signs AWS v4 requests with the provided body, service name, region the -// request is made to, and time the request is signed at. The signTime allows -// you to specify that a request is signed for the future, and cannot be -// used until then. -// -// Returns a list of HTTP headers that were included in the signature or an -// error if signing the request failed. Generally for signed requests this value -// is not needed as the full request context will be captured by the http.Request -// value. It is included for reference though. -// -// Sign will set the request's Body to be the `body` parameter passed in. If -// the body is not already an io.ReadCloser, it will be wrapped within one. If -// a `nil` body parameter passed to Sign, the request's Body field will be -// also set to nil. Its important to note that this functionality will not -// change the request's ContentLength of the request. -// -// Sign differs from Presign in that it will sign the request using HTTP -// header values. This type of signing is intended for http.Request values that -// will not be shared, or are shared in a way the header values on the request -// will not be lost. -// -// The requests body is an io.ReadSeeker so the SHA256 of the body can be -// generated. To bypass the signer computing the hash you can set the -// "X-Amz-Content-Sha256" header with a precomputed value. The signer will -// only compute the hash if the request header value is empty. -func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, 0, false, signTime) -} - -// Presign signs AWS v4 requests with the provided body, service name, region -// the request is made to, and time the request is signed at. The signTime -// allows you to specify that a request is signed for the future, and cannot -// be used until then. -// -// Returns a list of HTTP headers that were included in the signature or an -// error if signing the request failed. For presigned requests these headers -// and their values must be included on the HTTP request when it is made. This -// is helpful to know what header values need to be shared with the party the -// presigned request will be distributed to. -// -// Presign differs from Sign in that it will sign the request using query string -// instead of header values. This allows you to share the Presigned Request's -// URL with third parties, or distribute it throughout your system with minimal -// dependencies. -// -// Presign also takes an exp value which is the duration the -// signed request will be valid after the signing time. This is allows you to -// set when the request will expire. -// -// The requests body is an io.ReadSeeker so the SHA256 of the body can be -// generated. To bypass the signer computing the hash you can set the -// "X-Amz-Content-Sha256" header with a precomputed value. The signer will -// only compute the hash if the request header value is empty. -// -// Presigning a S3 request will not compute the body's SHA256 hash by default. -// This is done due to the general use case for S3 presigned URLs is to share -// PUT/GET capabilities. If you would like to include the body's SHA256 in the -// presigned request's signature you can set the "X-Amz-Content-Sha256" -// HTTP header and that will be included in the request's signature. -func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, exp, true, signTime) -} - -func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, isPresign bool, signTime time.Time) (http.Header, error) { - currentTimeFn := v4.currentTimeFn - if currentTimeFn == nil { - currentTimeFn = time.Now - } - - ctx := &signingCtx{ - Request: r, - Body: body, - Query: r.URL.Query(), - Time: signTime, - ExpireTime: exp, - isPresign: isPresign, - ServiceName: service, - Region: region, - DisableURIPathEscaping: v4.DisableURIPathEscaping, - unsignedPayload: v4.UnsignedPayload, - } - - for key := range ctx.Query { - sort.Strings(ctx.Query[key]) - } - - if ctx.isRequestSigned() { - ctx.Time = currentTimeFn() - ctx.handlePresignRemoval() - } - - var err error - ctx.credValues, err = v4.Credentials.GetWithContext(requestContext(r)) - if err != nil { - return http.Header{}, err - } - - ctx.sanitizeHostForHeader() - ctx.assignAmzQueryValues() - if err := ctx.build(v4.DisableHeaderHoisting); err != nil { - return nil, err - } - - // If the request is not presigned the body should be attached to it. This - // prevents the confusion of wanting to send a signed request without - // the body the request was signed for attached. - if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) { - var reader io.ReadCloser - if body != nil { - var ok bool - if reader, ok = body.(io.ReadCloser); !ok { - reader = ioutil.NopCloser(body) - } - } - r.Body = reader - } - - if v4.Debug.Matches(aws.LogDebugWithSigning) { - v4.logSigningInfo(ctx) - } - - return ctx.SignedHeaderVals, nil -} - -func (ctx *signingCtx) sanitizeHostForHeader() { - request.SanitizeHostForHeader(ctx.Request) -} - -func (ctx *signingCtx) handlePresignRemoval() { - if !ctx.isPresign { - return - } - - // The credentials have expired for this request. The current signing - // is invalid, and needs to be request because the request will fail. - ctx.removePresign() - - // Update the request's query string to ensure the values stays in - // sync in the case retrieving the new credentials fails. - ctx.Request.URL.RawQuery = ctx.Query.Encode() -} - -func (ctx *signingCtx) assignAmzQueryValues() { - if ctx.isPresign { - ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix) - if ctx.credValues.SessionToken != "" { - ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) - } else { - ctx.Query.Del("X-Amz-Security-Token") - } - - return - } - - if ctx.credValues.SessionToken != "" { - ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) - } -} - -// SignRequestHandler is a named request handler the SDK will use to sign -// service client request with using the V4 signature. -var SignRequestHandler = request.NamedHandler{ - Name: "v4.SignRequestHandler", Fn: SignSDKRequest, -} - -// SignSDKRequest signs an AWS request with the V4 signature. This -// request handler should only be used with the SDK's built in service client's -// API operation requests. -// -// This function should not be used on its own, but in conjunction with -// an AWS service client's API operation call. To sign a standalone request -// not created by a service client's API operation method use the "Sign" or -// "Presign" functions of the "Signer" type. -// -// If the credentials of the request's config are set to -// credentials.AnonymousCredentials the request will not be signed. -func SignSDKRequest(req *request.Request) { - SignSDKRequestWithCurrentTime(req, time.Now) -} - -// BuildNamedHandler will build a generic handler for signing. -func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { - return request.NamedHandler{ - Name: name, - Fn: func(req *request.Request) { - SignSDKRequestWithCurrentTime(req, time.Now, opts...) - }, - } -} - -// SignSDKRequestWithCurrentTime will sign the SDK's request using the time -// function passed in. Behaves the same as SignSDKRequest with the exception -// the request is signed with the value returned by the current time function. -func SignSDKRequestWithCurrentTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { - // If the request does not need to be signed ignore the signing of the - // request if the AnonymousCredentials object is used. - if req.Config.Credentials == credentials.AnonymousCredentials { - return - } - - region := req.ClientInfo.SigningRegion - if region == "" { - region = aws.StringValue(req.Config.Region) - } - - name := req.ClientInfo.SigningName - if name == "" { - name = req.ClientInfo.ServiceName - } - - v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) { - v4.Debug = req.Config.LogLevel.Value() - v4.Logger = req.Config.Logger - v4.DisableHeaderHoisting = req.NotHoist - v4.currentTimeFn = curTimeFn - if name == "s3" { - // S3 service should not have any escaping applied - v4.DisableURIPathEscaping = true - } - // Prevents setting the HTTPRequest's Body. Since the Body could be - // wrapped in a custom io.Closer that we do not want to be stompped - // on top of by the signer. - v4.DisableRequestBodyOverwrite = true - }) - - for _, opt := range opts { - opt(v4) - } - - curTime := curTimeFn() - signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), - name, region, req.ExpireTime, req.ExpireTime > 0, curTime, - ) - if err != nil { - req.Error = err - req.SignedHeaderVals = nil - return - } - - req.SignedHeaderVals = signedHeaders - req.LastSignedAt = curTime -} - -const logSignInfoMsg = `DEBUG: Request Signature: ----[ CANONICAL STRING ]----------------------------- -%s ----[ STRING TO SIGN ]-------------------------------- -%s%s ------------------------------------------------------` -const logSignedURLMsg = ` ----[ SIGNED URL ]------------------------------------ -%s` - -func (v4 *Signer) logSigningInfo(ctx *signingCtx) { - signedURLMsg := "" - if ctx.isPresign { - signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String()) - } - msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg) - v4.Logger.Log(msg) -} - -func (ctx *signingCtx) build(disableHeaderHoisting bool) error { - ctx.buildTime() // no depends - ctx.buildCredentialString() // no depends - - if err := ctx.buildBodyDigest(); err != nil { - return err - } - - unsignedHeaders := ctx.Request.Header - if ctx.isPresign { - if !disableHeaderHoisting { - urlValues := url.Values{} - urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends - for k := range urlValues { - ctx.Query[k] = urlValues[k] - } - } - } - - ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) - ctx.buildCanonicalString() // depends on canon headers / signed headers - ctx.buildStringToSign() // depends on canon string - ctx.buildSignature() // depends on string to sign - - if ctx.isPresign { - ctx.Request.URL.RawQuery += "&" + signatureQueryKey + "=" + ctx.signature - } else { - parts := []string{ - authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString, - "SignedHeaders=" + ctx.signedHeaders, - authHeaderSignatureElem + ctx.signature, - } - ctx.Request.Header.Set(authorizationHeader, strings.Join(parts, ", ")) - } - - return nil -} - -// GetSignedRequestSignature attempts to extract the signature of the request. -// Returning an error if the request is unsigned, or unable to extract the -// signature. -func GetSignedRequestSignature(r *http.Request) ([]byte, error) { - - if auth := r.Header.Get(authorizationHeader); len(auth) != 0 { - ps := strings.Split(auth, ", ") - for _, p := range ps { - if idx := strings.Index(p, authHeaderSignatureElem); idx >= 0 { - sig := p[len(authHeaderSignatureElem):] - if len(sig) == 0 { - return nil, fmt.Errorf("invalid request signature authorization header") - } - return hex.DecodeString(sig) - } - } - } - - if sig := r.URL.Query().Get("X-Amz-Signature"); len(sig) != 0 { - return hex.DecodeString(sig) - } - - return nil, fmt.Errorf("request not signed") -} - -func (ctx *signingCtx) buildTime() { - if ctx.isPresign { - duration := int64(ctx.ExpireTime / time.Second) - ctx.Query.Set("X-Amz-Date", formatTime(ctx.Time)) - ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) - } else { - ctx.Request.Header.Set("X-Amz-Date", formatTime(ctx.Time)) - } -} - -func (ctx *signingCtx) buildCredentialString() { - ctx.credentialString = buildSigningScope(ctx.Region, ctx.ServiceName, ctx.Time) - - if ctx.isPresign { - ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString) - } -} - -func buildQuery(r rule, header http.Header) (url.Values, http.Header) { - query := url.Values{} - unsignedHeaders := http.Header{} - for k, h := range header { - if r.IsValid(k) { - query[k] = h - } else { - unsignedHeaders[k] = h - } - } - - return query, unsignedHeaders -} -func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { - var headers []string - headers = append(headers, "host") - for k, v := range header { - if !r.IsValid(k) { - continue // ignored header - } - if ctx.SignedHeaderVals == nil { - ctx.SignedHeaderVals = make(http.Header) - } - - lowerCaseKey := strings.ToLower(k) - if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok { - // include additional values - ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...) - continue - } - - headers = append(headers, lowerCaseKey) - ctx.SignedHeaderVals[lowerCaseKey] = v - } - sort.Strings(headers) - - ctx.signedHeaders = strings.Join(headers, ";") - - if ctx.isPresign { - ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) - } - - headerItems := make([]string, len(headers)) - for i, k := range headers { - if k == "host" { - if ctx.Request.Host != "" { - headerItems[i] = "host:" + ctx.Request.Host - } else { - headerItems[i] = "host:" + ctx.Request.URL.Host - } - } else { - headerValues := make([]string, len(ctx.SignedHeaderVals[k])) - for i, v := range ctx.SignedHeaderVals[k] { - headerValues[i] = strings.TrimSpace(v) - } - headerItems[i] = k + ":" + - strings.Join(headerValues, ",") - } - } - stripExcessSpaces(headerItems) - ctx.canonicalHeaders = strings.Join(headerItems, "\n") -} - -func (ctx *signingCtx) buildCanonicalString() { - ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1) - - uri := getURIPath(ctx.Request.URL) - - if !ctx.DisableURIPathEscaping { - uri = rest.EscapePath(uri, false) - } - - ctx.canonicalString = strings.Join([]string{ - ctx.Request.Method, - uri, - ctx.Request.URL.RawQuery, - ctx.canonicalHeaders + "\n", - ctx.signedHeaders, - ctx.bodyDigest, - }, "\n") -} - -func (ctx *signingCtx) buildStringToSign() { - ctx.stringToSign = strings.Join([]string{ - authHeaderPrefix, - formatTime(ctx.Time), - ctx.credentialString, - hex.EncodeToString(hashSHA256([]byte(ctx.canonicalString))), - }, "\n") -} - -func (ctx *signingCtx) buildSignature() { - creds := deriveSigningKey(ctx.Region, ctx.ServiceName, ctx.credValues.SecretAccessKey, ctx.Time) - signature := hmacSHA256(creds, []byte(ctx.stringToSign)) - ctx.signature = hex.EncodeToString(signature) -} - -func (ctx *signingCtx) buildBodyDigest() error { - hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") - if hash == "" { - includeSHA256Header := ctx.unsignedPayload || - ctx.ServiceName == "s3" || - ctx.ServiceName == "s3-object-lambda" || - ctx.ServiceName == "glacier" || - ctx.ServiceName == "s3-outposts" - - s3Presign := ctx.isPresign && - (ctx.ServiceName == "s3" || - ctx.ServiceName == "s3-object-lambda") - - if ctx.unsignedPayload || s3Presign { - hash = "UNSIGNED-PAYLOAD" - includeSHA256Header = !s3Presign - } else if ctx.Body == nil { - hash = emptyStringSHA256 - } else { - if !aws.IsReaderSeekable(ctx.Body) { - return fmt.Errorf("cannot use unseekable request body %T, for signed request with body", ctx.Body) - } - hashBytes, err := makeSha256Reader(ctx.Body) - if err != nil { - return err - } - hash = hex.EncodeToString(hashBytes) - } - - if includeSHA256Header { - ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) - } - } - ctx.bodyDigest = hash - - return nil -} - -// isRequestSigned returns if the request is currently signed or presigned -func (ctx *signingCtx) isRequestSigned() bool { - if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" { - return true - } - if ctx.Request.Header.Get("Authorization") != "" { - return true - } - - return false -} - -// unsign removes signing flags for both signed and presigned requests. -func (ctx *signingCtx) removePresign() { - ctx.Query.Del("X-Amz-Algorithm") - ctx.Query.Del("X-Amz-Signature") - ctx.Query.Del("X-Amz-Security-Token") - ctx.Query.Del("X-Amz-Date") - ctx.Query.Del("X-Amz-Expires") - ctx.Query.Del("X-Amz-Credential") - ctx.Query.Del("X-Amz-SignedHeaders") -} - -func hmacSHA256(key []byte, data []byte) []byte { - hash := hmac.New(sha256.New, key) - hash.Write(data) - return hash.Sum(nil) -} - -func hashSHA256(data []byte) []byte { - hash := sha256.New() - hash.Write(data) - return hash.Sum(nil) -} - -func makeSha256Reader(reader io.ReadSeeker) (hashBytes []byte, err error) { - hash := sha256.New() - start, err := reader.Seek(0, sdkio.SeekCurrent) - if err != nil { - return nil, err - } - defer func() { - // ensure error is return if unable to seek back to start of payload. - _, err = reader.Seek(start, sdkio.SeekStart) - }() - - // Use CopyN to avoid allocating the 32KB buffer in io.Copy for bodies - // smaller than 32KB. Fall back to io.Copy if we fail to determine the size. - size, err := aws.SeekerLen(reader) - if err != nil { - io.Copy(hash, reader) - } else { - io.CopyN(hash, reader, size) - } - - return hash.Sum(nil), nil -} - -const doubleSpace = " " - -// stripExcessSpaces will rewrite the passed in slice's string values to not -// contain multiple side-by-side spaces. -func stripExcessSpaces(vals []string) { - var j, k, l, m, spaces int - for i, str := range vals { - // Trim trailing spaces - for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { - } - - // Trim leading spaces - for k = 0; k < j && str[k] == ' '; k++ { - } - str = str[k : j+1] - - // Strip multiple spaces. - j = strings.Index(str, doubleSpace) - if j < 0 { - vals[i] = str - continue - } - - buf := []byte(str) - for k, m, l = j, j, len(buf); k < l; k++ { - if buf[k] == ' ' { - if spaces == 0 { - // First space. - buf[m] = buf[k] - m++ - } - spaces++ - } else { - // End of multiple spaces. - spaces = 0 - buf[m] = buf[k] - m++ - } - } - - vals[i] = string(buf[:m]) - } -} - -func buildSigningScope(region, service string, dt time.Time) string { - return strings.Join([]string{ - formatShortTime(dt), - region, - service, - awsV4Request, - }, "/") -} - -func deriveSigningKey(region, service, secretKey string, dt time.Time) []byte { - kDate := hmacSHA256([]byte("AWS4"+secretKey), []byte(formatShortTime(dt))) - kRegion := hmacSHA256(kDate, []byte(region)) - kService := hmacSHA256(kRegion, []byte(service)) - signingKey := hmacSHA256(kService, []byte(awsV4Request)) - return signingKey -} - -func formatShortTime(dt time.Time) string { - return dt.UTC().Format(shortTimeFormat) -} - -func formatTime(dt time.Time) string { - return dt.UTC().Format(timeFormat) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types.go b/vendor/github.com/aws/aws-sdk-go/aws/types.go deleted file mode 100644 index 98751ee84..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/types.go +++ /dev/null @@ -1,264 +0,0 @@ -package aws - -import ( - "io" - "strings" - "sync" - - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -// ReadSeekCloser wraps a io.Reader returning a ReaderSeekerCloser. Allows the -// SDK to accept an io.Reader that is not also an io.Seeker for unsigned -// streaming payload API operations. -// -// A ReadSeekCloser wrapping an nonseekable io.Reader used in an API -// operation's input will prevent that operation being retried in the case of -// network errors, and cause operation requests to fail if the operation -// requires payload signing. -// -// Note: If using With S3 PutObject to stream an object upload The SDK's S3 -// Upload manager (s3manager.Uploader) provides support for streaming with the -// ability to retry network errors. -func ReadSeekCloser(r io.Reader) ReaderSeekerCloser { - return ReaderSeekerCloser{r} -} - -// ReaderSeekerCloser represents a reader that can also delegate io.Seeker and -// io.Closer interfaces to the underlying object if they are available. -type ReaderSeekerCloser struct { - r io.Reader -} - -// IsReaderSeekable returns if the underlying reader type can be seeked. A -// io.Reader might not actually be seekable if it is the ReaderSeekerCloser -// type. -func IsReaderSeekable(r io.Reader) bool { - switch v := r.(type) { - case ReaderSeekerCloser: - return v.IsSeeker() - case *ReaderSeekerCloser: - return v.IsSeeker() - case io.ReadSeeker: - return true - default: - return false - } -} - -// Read reads from the reader up to size of p. The number of bytes read, and -// error if it occurred will be returned. -// -// If the reader is not an io.Reader zero bytes read, and nil error will be -// returned. -// -// Performs the same functionality as io.Reader Read -func (r ReaderSeekerCloser) Read(p []byte) (int, error) { - switch t := r.r.(type) { - case io.Reader: - return t.Read(p) - } - return 0, nil -} - -// Seek sets the offset for the next Read to offset, interpreted according to -// whence: 0 means relative to the origin of the file, 1 means relative to the -// current offset, and 2 means relative to the end. Seek returns the new offset -// and an error, if any. -// -// If the ReaderSeekerCloser is not an io.Seeker nothing will be done. -func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) { - switch t := r.r.(type) { - case io.Seeker: - return t.Seek(offset, whence) - } - return int64(0), nil -} - -// IsSeeker returns if the underlying reader is also a seeker. -func (r ReaderSeekerCloser) IsSeeker() bool { - _, ok := r.r.(io.Seeker) - return ok -} - -// HasLen returns the length of the underlying reader if the value implements -// the Len() int method. -func (r ReaderSeekerCloser) HasLen() (int, bool) { - type lenner interface { - Len() int - } - - if lr, ok := r.r.(lenner); ok { - return lr.Len(), true - } - - return 0, false -} - -// GetLen returns the length of the bytes remaining in the underlying reader. -// Checks first for Len(), then io.Seeker to determine the size of the -// underlying reader. -// -// Will return -1 if the length cannot be determined. -func (r ReaderSeekerCloser) GetLen() (int64, error) { - if l, ok := r.HasLen(); ok { - return int64(l), nil - } - - if s, ok := r.r.(io.Seeker); ok { - return seekerLen(s) - } - - return -1, nil -} - -// SeekerLen attempts to get the number of bytes remaining at the seeker's -// current position. Returns the number of bytes remaining or error. -func SeekerLen(s io.Seeker) (int64, error) { - // Determine if the seeker is actually seekable. ReaderSeekerCloser - // hides the fact that a io.Readers might not actually be seekable. - switch v := s.(type) { - case ReaderSeekerCloser: - return v.GetLen() - case *ReaderSeekerCloser: - return v.GetLen() - } - - return seekerLen(s) -} - -func seekerLen(s io.Seeker) (int64, error) { - curOffset, err := s.Seek(0, sdkio.SeekCurrent) - if err != nil { - return 0, err - } - - endOffset, err := s.Seek(0, sdkio.SeekEnd) - if err != nil { - return 0, err - } - - _, err = s.Seek(curOffset, sdkio.SeekStart) - if err != nil { - return 0, err - } - - return endOffset - curOffset, nil -} - -// Close closes the ReaderSeekerCloser. -// -// If the ReaderSeekerCloser is not an io.Closer nothing will be done. -func (r ReaderSeekerCloser) Close() error { - switch t := r.r.(type) { - case io.Closer: - return t.Close() - } - return nil -} - -// A WriteAtBuffer provides a in memory buffer supporting the io.WriterAt interface -// Can be used with the s3manager.Downloader to download content to a buffer -// in memory. Safe to use concurrently. -type WriteAtBuffer struct { - buf []byte - m sync.Mutex - - // GrowthCoeff defines the growth rate of the internal buffer. By - // default, the growth rate is 1, where expanding the internal - // buffer will allocate only enough capacity to fit the new expected - // length. - GrowthCoeff float64 -} - -// NewWriteAtBuffer creates a WriteAtBuffer with an internal buffer -// provided by buf. -func NewWriteAtBuffer(buf []byte) *WriteAtBuffer { - return &WriteAtBuffer{buf: buf} -} - -// WriteAt writes a slice of bytes to a buffer starting at the position provided -// The number of bytes written will be returned, or error. Can overwrite previous -// written slices if the write ats overlap. -func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) { - pLen := len(p) - expLen := pos + int64(pLen) - b.m.Lock() - defer b.m.Unlock() - if int64(len(b.buf)) < expLen { - if int64(cap(b.buf)) < expLen { - if b.GrowthCoeff < 1 { - b.GrowthCoeff = 1 - } - newBuf := make([]byte, expLen, int64(b.GrowthCoeff*float64(expLen))) - copy(newBuf, b.buf) - b.buf = newBuf - } - b.buf = b.buf[:expLen] - } - copy(b.buf[pos:], p) - return pLen, nil -} - -// Bytes returns a slice of bytes written to the buffer. -func (b *WriteAtBuffer) Bytes() []byte { - b.m.Lock() - defer b.m.Unlock() - return b.buf -} - -// MultiCloser is a utility to close multiple io.Closers within a single -// statement. -type MultiCloser []io.Closer - -// Close closes all of the io.Closers making up the MultiClosers. Any -// errors that occur while closing will be returned in the order they -// occur. -func (m MultiCloser) Close() error { - var errs errors - for _, c := range m { - err := c.Close() - if err != nil { - errs = append(errs, err) - } - } - if len(errs) != 0 { - return errs - } - - return nil -} - -type errors []error - -func (es errors) Error() string { - var parts []string - for _, e := range es { - parts = append(parts, e.Error()) - } - - return strings.Join(parts, "\n") -} - -// CopySeekableBody copies the seekable body to an io.Writer -func CopySeekableBody(dst io.Writer, src io.ReadSeeker) (int64, error) { - curPos, err := src.Seek(0, sdkio.SeekCurrent) - if err != nil { - return 0, err - } - - // copy errors may be assumed to be from the body. - n, err := io.Copy(dst, src) - if err != nil { - return n, err - } - - // seek back to the first position after reading to reset - // the body for transmission. - _, err = src.Seek(curPos, sdkio.SeekStart) - if err != nil { - return n, err - } - - return n, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/url.go b/vendor/github.com/aws/aws-sdk-go/aws/url.go deleted file mode 100644 index fed561bd5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/url.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build go1.8 -// +build go1.8 - -package aws - -import "net/url" - -// URLHostname will extract the Hostname without port from the URL value. -// -// Wrapper of net/url#URL.Hostname for backwards Go version compatibility. -func URLHostname(url *url.URL) string { - return url.Hostname() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go deleted file mode 100644 index 95282db03..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go +++ /dev/null @@ -1,30 +0,0 @@ -//go:build !go1.8 -// +build !go1.8 - -package aws - -import ( - "net/url" - "strings" -) - -// URLHostname will extract the Hostname without port from the URL value. -// -// Copy of Go 1.8's net/url#URL.Hostname functionality. -func URLHostname(url *url.URL) string { - return stripPort(url.Host) - -} - -// stripPort is copy of Go 1.8 url#URL.Hostname functionality. -// https://golang.org/src/net/url/url.go -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go deleted file mode 100644 index d15e3c84c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package aws provides core functionality for making requests to AWS services. -package aws - -// SDKName is the name of this AWS SDK -const SDKName = "aws-sdk-go" - -// SDKVersion is the version of this SDK -const SDKVersion = "1.55.5" diff --git a/vendor/github.com/aws/aws-sdk-go/internal/context/background_go1.5.go b/vendor/github.com/aws/aws-sdk-go/internal/context/background_go1.5.go deleted file mode 100644 index 365345353..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/context/background_go1.5.go +++ /dev/null @@ -1,41 +0,0 @@ -//go:build !go1.7 -// +build !go1.7 - -package context - -import "time" - -// An emptyCtx is a copy of the Go 1.7 context.emptyCtx type. This is copied to -// provide a 1.6 and 1.5 safe version of context that is compatible with Go -// 1.7's Context. -// -// 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 BackgroundCtx: - return "aws.BackgroundContext" - } - return "unknown empty Context" -} - -// BackgroundCtx is the common base context. -var BackgroundCtx = new(emptyCtx) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ast.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ast.go deleted file mode 100644 index e83a99886..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/ast.go +++ /dev/null @@ -1,120 +0,0 @@ -package ini - -// ASTKind represents different states in the parse table -// and the type of AST that is being constructed -type ASTKind int - -// ASTKind* is used in the parse table to transition between -// the different states -const ( - ASTKindNone = ASTKind(iota) - ASTKindStart - ASTKindExpr - ASTKindEqualExpr - ASTKindStatement - ASTKindSkipStatement - ASTKindExprStatement - ASTKindSectionStatement - ASTKindNestedSectionStatement - ASTKindCompletedNestedSectionStatement - ASTKindCommentStatement - ASTKindCompletedSectionStatement -) - -func (k ASTKind) String() string { - switch k { - case ASTKindNone: - return "none" - case ASTKindStart: - return "start" - case ASTKindExpr: - return "expr" - case ASTKindStatement: - return "stmt" - case ASTKindSectionStatement: - return "section_stmt" - case ASTKindExprStatement: - return "expr_stmt" - case ASTKindCommentStatement: - return "comment" - case ASTKindNestedSectionStatement: - return "nested_section_stmt" - case ASTKindCompletedSectionStatement: - return "completed_stmt" - case ASTKindSkipStatement: - return "skip" - default: - return "" - } -} - -// AST interface allows us to determine what kind of node we -// are on and casting may not need to be necessary. -// -// The root is always the first node in Children -type AST struct { - Kind ASTKind - Root Token - RootToken bool - Children []AST -} - -func newAST(kind ASTKind, root AST, children ...AST) AST { - return AST{ - Kind: kind, - Children: append([]AST{root}, children...), - } -} - -func newASTWithRootToken(kind ASTKind, root Token, children ...AST) AST { - return AST{ - Kind: kind, - Root: root, - RootToken: true, - Children: children, - } -} - -// AppendChild will append to the list of children an AST has. -func (a *AST) AppendChild(child AST) { - a.Children = append(a.Children, child) -} - -// GetRoot will return the root AST which can be the first entry -// in the children list or a token. -func (a *AST) GetRoot() AST { - if a.RootToken { - return *a - } - - if len(a.Children) == 0 { - return AST{} - } - - return a.Children[0] -} - -// GetChildren will return the current AST's list of children -func (a *AST) GetChildren() []AST { - if len(a.Children) == 0 { - return []AST{} - } - - if a.RootToken { - return a.Children - } - - return a.Children[1:] -} - -// SetChildren will set and override all children of the AST. -func (a *AST) SetChildren(children []AST) { - if a.RootToken { - a.Children = children - } else { - a.Children = append(a.Children[:1], children...) - } -} - -// Start is used to indicate the starting state of the parse table. -var Start = newAST(ASTKindStart, AST{}) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/comma_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/comma_token.go deleted file mode 100644 index 0895d53cb..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/comma_token.go +++ /dev/null @@ -1,11 +0,0 @@ -package ini - -var commaRunes = []rune(",") - -func isComma(b rune) bool { - return b == ',' -} - -func newCommaToken() Token { - return newToken(TokenComma, commaRunes, NoneType) -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/comment_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/comment_token.go deleted file mode 100644 index 0b76999ba..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/comment_token.go +++ /dev/null @@ -1,35 +0,0 @@ -package ini - -// isComment will return whether or not the next byte(s) is a -// comment. -func isComment(b []rune) bool { - if len(b) == 0 { - return false - } - - switch b[0] { - case ';': - return true - case '#': - return true - } - - return false -} - -// newCommentToken will create a comment token and -// return how many bytes were read. -func newCommentToken(b []rune) (Token, int, error) { - i := 0 - for ; i < len(b); i++ { - if b[i] == '\n' { - break - } - - if len(b)-i > 2 && b[i] == '\r' && b[i+1] == '\n' { - break - } - } - - return newToken(TokenComment, b[:i], NoneType), i, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/doc.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/doc.go deleted file mode 100644 index 1e55bbd07..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/doc.go +++ /dev/null @@ -1,42 +0,0 @@ -// Package ini is an LL(1) parser for configuration files. -// -// Example: -// sections, err := ini.OpenFile("/path/to/file") -// if err != nil { -// panic(err) -// } -// -// profile := "foo" -// section, ok := sections.GetSection(profile) -// if !ok { -// fmt.Printf("section %q could not be found", profile) -// } -// -// Below is the BNF that describes this parser -// Grammar: -// stmt -> section | stmt' -// stmt' -> epsilon | expr -// expr -> value (stmt)* | equal_expr (stmt)* -// equal_expr -> value ( ':' | '=' ) equal_expr' -// equal_expr' -> number | string | quoted_string -// quoted_string -> " quoted_string' -// quoted_string' -> string quoted_string_end -// quoted_string_end -> " -// -// section -> [ section' -// section' -> section_value section_close -// section_value -> number | string_subset | boolean | quoted_string_subset -// quoted_string_subset -> " quoted_string_subset' -// quoted_string_subset' -> string_subset quoted_string_end -// quoted_string_subset -> " -// section_close -> ] -// -// value -> number | string_subset | boolean -// string -> ? UTF-8 Code-Points except '\n' (U+000A) and '\r\n' (U+000D U+000A) ? -// string_subset -> ? Code-points excepted by grammar except ':' (U+003A), '=' (U+003D), '[' (U+005B), and ']' (U+005D) ? -// -// SkipState will skip (NL WS)+ -// -// comment -> # comment' | ; comment' -// comment' -> epsilon | value -package ini diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/empty_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/empty_token.go deleted file mode 100644 index 04345a54c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/empty_token.go +++ /dev/null @@ -1,4 +0,0 @@ -package ini - -// emptyToken is used to satisfy the Token interface -var emptyToken = newToken(TokenNone, []rune{}, NoneType) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/expression.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/expression.go deleted file mode 100644 index 91ba2a59d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/expression.go +++ /dev/null @@ -1,24 +0,0 @@ -package ini - -// newExpression will return an expression AST. -// Expr represents an expression -// -// grammar: -// expr -> string | number -func newExpression(tok Token) AST { - return newASTWithRootToken(ASTKindExpr, tok) -} - -func newEqualExpr(left AST, tok Token) AST { - return newASTWithRootToken(ASTKindEqualExpr, tok, left) -} - -// EqualExprKey will return a LHS value in the equal expr -func EqualExprKey(ast AST) string { - children := ast.GetChildren() - if len(children) == 0 || ast.Kind != ASTKindEqualExpr { - return "" - } - - return string(children[0].Root.Raw()) -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/fuzz.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/fuzz.go deleted file mode 100644 index 6e545b63b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/fuzz.go +++ /dev/null @@ -1,18 +0,0 @@ -//go:build gofuzz -// +build gofuzz - -package ini - -import ( - "bytes" -) - -func Fuzz(data []byte) int { - b := bytes.NewReader(data) - - if _, err := Parse(b); err != nil { - return 0 - } - - return 1 -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini.go deleted file mode 100644 index 3b0ca7afe..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini.go +++ /dev/null @@ -1,51 +0,0 @@ -package ini - -import ( - "io" - "os" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// OpenFile takes a path to a given file, and will open and parse -// that file. -func OpenFile(path string) (Sections, error) { - f, err := os.Open(path) - if err != nil { - return Sections{}, awserr.New(ErrCodeUnableToReadFile, "unable to open file", err) - } - defer f.Close() - - return Parse(f) -} - -// Parse will parse the given file using the shared config -// visitor. -func Parse(f io.Reader) (Sections, error) { - tree, err := ParseAST(f) - if err != nil { - return Sections{}, err - } - - v := NewDefaultVisitor() - if err = Walk(tree, v); err != nil { - return Sections{}, err - } - - return v.Sections, nil -} - -// ParseBytes will parse the given bytes and return the parsed sections. -func ParseBytes(b []byte) (Sections, error) { - tree, err := ParseASTBytes(b) - if err != nil { - return Sections{}, err - } - - v := NewDefaultVisitor() - if err = Walk(tree, v); err != nil { - return Sections{}, err - } - - return v.Sections, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_lexer.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_lexer.go deleted file mode 100644 index 582c024ad..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_lexer.go +++ /dev/null @@ -1,165 +0,0 @@ -package ini - -import ( - "bytes" - "io" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -const ( - // ErrCodeUnableToReadFile is used when a file is failed to be - // opened or read from. - ErrCodeUnableToReadFile = "FailedRead" -) - -// TokenType represents the various different tokens types -type TokenType int - -func (t TokenType) String() string { - switch t { - case TokenNone: - return "none" - case TokenLit: - return "literal" - case TokenSep: - return "sep" - case TokenOp: - return "op" - case TokenWS: - return "ws" - case TokenNL: - return "newline" - case TokenComment: - return "comment" - case TokenComma: - return "comma" - default: - return "" - } -} - -// TokenType enums -const ( - TokenNone = TokenType(iota) - TokenLit - TokenSep - TokenComma - TokenOp - TokenWS - TokenNL - TokenComment -) - -type iniLexer struct{} - -// Tokenize will return a list of tokens during lexical analysis of the -// io.Reader. -func (l *iniLexer) Tokenize(r io.Reader) ([]Token, error) { - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, awserr.New(ErrCodeUnableToReadFile, "unable to read file", err) - } - - return l.tokenize(b) -} - -func (l *iniLexer) tokenize(b []byte) ([]Token, error) { - runes := bytes.Runes(b) - var err error - n := 0 - tokenAmount := countTokens(runes) - tokens := make([]Token, tokenAmount) - count := 0 - - for len(runes) > 0 && count < tokenAmount { - switch { - case isWhitespace(runes[0]): - tokens[count], n, err = newWSToken(runes) - case isComma(runes[0]): - tokens[count], n = newCommaToken(), 1 - case isComment(runes): - tokens[count], n, err = newCommentToken(runes) - case isNewline(runes): - tokens[count], n, err = newNewlineToken(runes) - case isSep(runes): - tokens[count], n, err = newSepToken(runes) - case isOp(runes): - tokens[count], n, err = newOpToken(runes) - default: - tokens[count], n, err = newLitToken(runes) - } - - if err != nil { - return nil, err - } - - count++ - - runes = runes[n:] - } - - return tokens[:count], nil -} - -func countTokens(runes []rune) int { - count, n := 0, 0 - var err error - - for len(runes) > 0 { - switch { - case isWhitespace(runes[0]): - _, n, err = newWSToken(runes) - case isComma(runes[0]): - _, n = newCommaToken(), 1 - case isComment(runes): - _, n, err = newCommentToken(runes) - case isNewline(runes): - _, n, err = newNewlineToken(runes) - case isSep(runes): - _, n, err = newSepToken(runes) - case isOp(runes): - _, n, err = newOpToken(runes) - default: - _, n, err = newLitToken(runes) - } - - if err != nil { - return 0 - } - - count++ - runes = runes[n:] - } - - return count + 1 -} - -// Token indicates a metadata about a given value. -type Token struct { - t TokenType - ValueType ValueType - base int - raw []rune -} - -var emptyValue = Value{} - -func newToken(t TokenType, raw []rune, v ValueType) Token { - return Token{ - t: t, - raw: raw, - ValueType: v, - } -} - -// Raw return the raw runes that were consumed -func (tok Token) Raw() []rune { - return tok.raw -} - -// Type returns the token type -func (tok Token) Type() TokenType { - return tok.t -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_parser.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_parser.go deleted file mode 100644 index 0ba319491..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/ini_parser.go +++ /dev/null @@ -1,350 +0,0 @@ -package ini - -import ( - "fmt" - "io" -) - -// ParseState represents the current state of the parser. -type ParseState uint - -// State enums for the parse table -const ( - InvalidState ParseState = iota - // stmt -> value stmt' - StatementState - // stmt' -> MarkComplete | op stmt - StatementPrimeState - // value -> number | string | boolean | quoted_string - ValueState - // section -> [ section' - OpenScopeState - // section' -> value section_close - SectionState - // section_close -> ] - CloseScopeState - // SkipState will skip (NL WS)+ - SkipState - // SkipTokenState will skip any token and push the previous - // state onto the stack. - SkipTokenState - // comment -> # comment' | ; comment' - // comment' -> MarkComplete | value - CommentState - // MarkComplete state will complete statements and move that - // to the completed AST list - MarkCompleteState - // TerminalState signifies that the tokens have been fully parsed - TerminalState -) - -// parseTable is a state machine to dictate the grammar above. -var parseTable = map[ASTKind]map[TokenType]ParseState{ - ASTKindStart: { - TokenLit: StatementState, - TokenSep: OpenScopeState, - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenComment: CommentState, - TokenNone: TerminalState, - }, - ASTKindCommentStatement: { - TokenLit: StatementState, - TokenSep: OpenScopeState, - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenComment: CommentState, - TokenNone: MarkCompleteState, - }, - ASTKindExpr: { - TokenOp: StatementPrimeState, - TokenLit: ValueState, - TokenSep: OpenScopeState, - TokenWS: ValueState, - TokenNL: SkipState, - TokenComment: CommentState, - TokenNone: MarkCompleteState, - }, - ASTKindEqualExpr: { - TokenLit: ValueState, - TokenSep: ValueState, - TokenOp: ValueState, - TokenWS: SkipTokenState, - TokenNL: SkipState, - TokenNone: SkipState, - }, - ASTKindStatement: { - TokenLit: SectionState, - TokenSep: CloseScopeState, - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenComment: CommentState, - TokenNone: MarkCompleteState, - }, - ASTKindExprStatement: { - TokenLit: ValueState, - TokenSep: ValueState, - TokenOp: ValueState, - TokenWS: ValueState, - TokenNL: MarkCompleteState, - TokenComment: CommentState, - TokenNone: TerminalState, - TokenComma: SkipState, - }, - ASTKindSectionStatement: { - TokenLit: SectionState, - TokenOp: SectionState, - TokenSep: CloseScopeState, - TokenWS: SectionState, - TokenNL: SkipTokenState, - }, - ASTKindCompletedSectionStatement: { - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenLit: StatementState, - TokenSep: OpenScopeState, - TokenComment: CommentState, - TokenNone: MarkCompleteState, - }, - ASTKindSkipStatement: { - TokenLit: StatementState, - TokenSep: OpenScopeState, - TokenWS: SkipTokenState, - TokenNL: SkipTokenState, - TokenComment: CommentState, - TokenNone: TerminalState, - }, -} - -// ParseAST will parse input from an io.Reader using -// an LL(1) parser. -func ParseAST(r io.Reader) ([]AST, error) { - lexer := iniLexer{} - tokens, err := lexer.Tokenize(r) - if err != nil { - return []AST{}, err - } - - return parse(tokens) -} - -// ParseASTBytes will parse input from a byte slice using -// an LL(1) parser. -func ParseASTBytes(b []byte) ([]AST, error) { - lexer := iniLexer{} - tokens, err := lexer.tokenize(b) - if err != nil { - return []AST{}, err - } - - return parse(tokens) -} - -func parse(tokens []Token) ([]AST, error) { - start := Start - stack := newParseStack(3, len(tokens)) - - stack.Push(start) - s := newSkipper() - -loop: - for stack.Len() > 0 { - k := stack.Pop() - - var tok Token - if len(tokens) == 0 { - // this occurs when all the tokens have been processed - // but reduction of what's left on the stack needs to - // occur. - tok = emptyToken - } else { - tok = tokens[0] - } - - step := parseTable[k.Kind][tok.Type()] - if s.ShouldSkip(tok) { - // being in a skip state with no tokens will break out of - // the parse loop since there is nothing left to process. - if len(tokens) == 0 { - break loop - } - // if should skip is true, we skip the tokens until should skip is set to false. - step = SkipTokenState - } - - switch step { - case TerminalState: - // Finished parsing. Push what should be the last - // statement to the stack. If there is anything left - // on the stack, an error in parsing has occurred. - if k.Kind != ASTKindStart { - stack.MarkComplete(k) - } - break loop - case SkipTokenState: - // When skipping a token, the previous state was popped off the stack. - // To maintain the correct state, the previous state will be pushed - // onto the stack. - stack.Push(k) - case StatementState: - if k.Kind != ASTKindStart { - stack.MarkComplete(k) - } - expr := newExpression(tok) - stack.Push(expr) - case StatementPrimeState: - if tok.Type() != TokenOp { - stack.MarkComplete(k) - continue - } - - if k.Kind != ASTKindExpr { - return nil, NewParseError( - fmt.Sprintf("invalid expression: expected Expr type, but found %T type", k), - ) - } - - k = trimSpaces(k) - expr := newEqualExpr(k, tok) - stack.Push(expr) - case ValueState: - // ValueState requires the previous state to either be an equal expression - // or an expression statement. - switch k.Kind { - case ASTKindEqualExpr: - // assigning a value to some key - k.AppendChild(newExpression(tok)) - stack.Push(newExprStatement(k)) - case ASTKindExpr: - k.Root.raw = append(k.Root.raw, tok.Raw()...) - stack.Push(k) - case ASTKindExprStatement: - root := k.GetRoot() - children := root.GetChildren() - if len(children) == 0 { - return nil, NewParseError( - fmt.Sprintf("invalid expression: AST contains no children %s", k.Kind), - ) - } - - rhs := children[len(children)-1] - - if rhs.Root.ValueType != QuotedStringType { - rhs.Root.ValueType = StringType - rhs.Root.raw = append(rhs.Root.raw, tok.Raw()...) - - } - - children[len(children)-1] = rhs - root.SetChildren(children) - - stack.Push(k) - } - case OpenScopeState: - if !runeCompare(tok.Raw(), openBrace) { - return nil, NewParseError("expected '['") - } - // If OpenScopeState is not at the start, we must mark the previous ast as complete - // - // for example: if previous ast was a skip statement; - // we should mark it as complete before we create a new statement - if k.Kind != ASTKindStart { - stack.MarkComplete(k) - } - - stmt := newStatement() - stack.Push(stmt) - case CloseScopeState: - if !runeCompare(tok.Raw(), closeBrace) { - return nil, NewParseError("expected ']'") - } - - k = trimSpaces(k) - stack.Push(newCompletedSectionStatement(k)) - case SectionState: - var stmt AST - - switch k.Kind { - case ASTKindStatement: - // If there are multiple literals inside of a scope declaration, - // then the current token's raw value will be appended to the Name. - // - // This handles cases like [ profile default ] - // - // k will represent a SectionStatement with the children representing - // the label of the section - stmt = newSectionStatement(tok) - case ASTKindSectionStatement: - k.Root.raw = append(k.Root.raw, tok.Raw()...) - stmt = k - default: - return nil, NewParseError( - fmt.Sprintf("invalid statement: expected statement: %v", k.Kind), - ) - } - - stack.Push(stmt) - case MarkCompleteState: - if k.Kind != ASTKindStart { - stack.MarkComplete(k) - } - - if stack.Len() == 0 { - stack.Push(start) - } - case SkipState: - stack.Push(newSkipStatement(k)) - s.Skip() - case CommentState: - if k.Kind == ASTKindStart { - stack.Push(k) - } else { - stack.MarkComplete(k) - } - - stmt := newCommentStatement(tok) - stack.Push(stmt) - default: - return nil, NewParseError( - fmt.Sprintf("invalid state with ASTKind %v and TokenType %v", - k, tok.Type())) - } - - if len(tokens) > 0 { - tokens = tokens[1:] - } - } - - // this occurs when a statement has not been completed - if stack.top > 1 { - return nil, NewParseError(fmt.Sprintf("incomplete ini expression")) - } - - // returns a sublist which excludes the start symbol - return stack.List(), nil -} - -// trimSpaces will trim spaces on the left and right hand side of -// the literal. -func trimSpaces(k AST) AST { - // trim left hand side of spaces - for i := 0; i < len(k.Root.raw); i++ { - if !isWhitespace(k.Root.raw[i]) { - break - } - - k.Root.raw = k.Root.raw[1:] - i-- - } - - // trim right hand side of spaces - for i := len(k.Root.raw) - 1; i >= 0; i-- { - if !isWhitespace(k.Root.raw[i]) { - break - } - - k.Root.raw = k.Root.raw[:len(k.Root.raw)-1] - } - - return k -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go deleted file mode 100644 index b1b686086..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/literal_tokens.go +++ /dev/null @@ -1,337 +0,0 @@ -package ini - -import ( - "fmt" - "strconv" - "strings" - "unicode" -) - -var ( - runesTrue = []rune("true") - runesFalse = []rune("false") -) - -var literalValues = [][]rune{ - runesTrue, - runesFalse, -} - -func isBoolValue(b []rune) bool { - for _, lv := range literalValues { - if isCaselessLitValue(lv, b) { - return true - } - } - return false -} - -func isLitValue(want, have []rune) bool { - if len(have) < len(want) { - return false - } - - for i := 0; i < len(want); i++ { - if want[i] != have[i] { - return false - } - } - - return true -} - -// isCaselessLitValue is a caseless value comparison, assumes want is already lower-cased for efficiency. -func isCaselessLitValue(want, have []rune) bool { - if len(have) < len(want) { - return false - } - - for i := 0; i < len(want); i++ { - if want[i] != unicode.ToLower(have[i]) { - return false - } - } - - return true -} - -// isNumberValue will return whether not the leading characters in -// a byte slice is a number. A number is delimited by whitespace or -// the newline token. -// -// A number is defined to be in a binary, octal, decimal (int | float), hex format, -// or in scientific notation. -func isNumberValue(b []rune) bool { - negativeIndex := 0 - helper := numberHelper{} - needDigit := false - - for i := 0; i < len(b); i++ { - negativeIndex++ - - switch b[i] { - case '-': - if helper.IsNegative() || negativeIndex != 1 { - return false - } - helper.Determine(b[i]) - needDigit = true - continue - case 'e', 'E': - if err := helper.Determine(b[i]); err != nil { - return false - } - negativeIndex = 0 - needDigit = true - continue - case 'b': - if helper.numberFormat == hex { - break - } - fallthrough - case 'o', 'x': - needDigit = true - if i == 0 { - return false - } - - fallthrough - case '.': - if err := helper.Determine(b[i]); err != nil { - return false - } - needDigit = true - continue - } - - if i > 0 && (isNewline(b[i:]) || isWhitespace(b[i])) { - return !needDigit - } - - if !helper.CorrectByte(b[i]) { - return false - } - needDigit = false - } - - return !needDigit -} - -func isValid(b []rune) (bool, int, error) { - if len(b) == 0 { - // TODO: should probably return an error - return false, 0, nil - } - - return isValidRune(b[0]), 1, nil -} - -func isValidRune(r rune) bool { - return r != ':' && r != '=' && r != '[' && r != ']' && r != ' ' && r != '\n' -} - -// ValueType is an enum that will signify what type -// the Value is -type ValueType int - -func (v ValueType) String() string { - switch v { - case NoneType: - return "NONE" - case DecimalType: - return "FLOAT" - case IntegerType: - return "INT" - case StringType: - return "STRING" - case BoolType: - return "BOOL" - } - - return "" -} - -// ValueType enums -const ( - NoneType = ValueType(iota) - DecimalType // deprecated - IntegerType // deprecated - StringType - QuotedStringType - BoolType // deprecated -) - -// Value is a union container -type Value struct { - Type ValueType - raw []rune - - integer int64 // deprecated - decimal float64 // deprecated - boolean bool // deprecated - str string -} - -func newValue(t ValueType, base int, raw []rune) (Value, error) { - v := Value{ - Type: t, - raw: raw, - } - var err error - - switch t { - case DecimalType: - v.decimal, err = strconv.ParseFloat(string(raw), 64) - case IntegerType: - if base != 10 { - raw = raw[2:] - } - - v.integer, err = strconv.ParseInt(string(raw), base, 64) - case StringType: - v.str = string(raw) - case QuotedStringType: - v.str = string(raw[1 : len(raw)-1]) - case BoolType: - v.boolean = isCaselessLitValue(runesTrue, v.raw) - } - - // issue 2253 - // - // if the value trying to be parsed is too large, then we will use - // the 'StringType' and raw value instead. - if nerr, ok := err.(*strconv.NumError); ok && nerr.Err == strconv.ErrRange { - v.Type = StringType - v.str = string(raw) - err = nil - } - - return v, err -} - -// Append will append values and change the type to a string -// type. -func (v *Value) Append(tok Token) { - r := tok.Raw() - if v.Type != QuotedStringType { - v.Type = StringType - r = tok.raw[1 : len(tok.raw)-1] - } - if tok.Type() != TokenLit { - v.raw = append(v.raw, tok.Raw()...) - } else { - v.raw = append(v.raw, r...) - } -} - -func (v Value) String() string { - switch v.Type { - case DecimalType: - return fmt.Sprintf("decimal: %f", v.decimal) - case IntegerType: - return fmt.Sprintf("integer: %d", v.integer) - case StringType: - return fmt.Sprintf("string: %s", string(v.raw)) - case QuotedStringType: - return fmt.Sprintf("quoted string: %s", string(v.raw)) - case BoolType: - return fmt.Sprintf("bool: %t", v.boolean) - default: - return "union not set" - } -} - -func newLitToken(b []rune) (Token, int, error) { - n := 0 - var err error - - token := Token{} - if b[0] == '"' { - n, err = getStringValue(b) - if err != nil { - return token, n, err - } - - token = newToken(TokenLit, b[:n], QuotedStringType) - } else { - n, err = getValue(b) - token = newToken(TokenLit, b[:n], StringType) - } - - return token, n, err -} - -// IntValue returns an integer value -func (v Value) IntValue() (int64, bool) { - i, err := strconv.ParseInt(string(v.raw), 0, 64) - if err != nil { - return 0, false - } - return i, true -} - -// FloatValue returns a float value -func (v Value) FloatValue() (float64, bool) { - f, err := strconv.ParseFloat(string(v.raw), 64) - if err != nil { - return 0, false - } - return f, true -} - -// BoolValue returns a bool value -func (v Value) BoolValue() (bool, bool) { - // we don't use ParseBool as it recognizes more than what we've - // historically supported - if isCaselessLitValue(runesTrue, v.raw) { - return true, true - } else if isCaselessLitValue(runesFalse, v.raw) { - return false, true - } - return false, false -} - -func isTrimmable(r rune) bool { - switch r { - case '\n', ' ': - return true - } - return false -} - -// StringValue returns the string value -func (v Value) StringValue() string { - switch v.Type { - case StringType: - return strings.TrimFunc(string(v.raw), isTrimmable) - case QuotedStringType: - // preserve all characters in the quotes - return string(removeEscapedCharacters(v.raw[1 : len(v.raw)-1])) - default: - return strings.TrimFunc(string(v.raw), isTrimmable) - } -} - -func contains(runes []rune, c rune) bool { - for i := 0; i < len(runes); i++ { - if runes[i] == c { - return true - } - } - - return false -} - -func runeCompare(v1 []rune, v2 []rune) bool { - if len(v1) != len(v2) { - return false - } - - for i := 0; i < len(v1); i++ { - if v1[i] != v2[i] { - return false - } - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/newline_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/newline_token.go deleted file mode 100644 index e52ac399f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/newline_token.go +++ /dev/null @@ -1,30 +0,0 @@ -package ini - -func isNewline(b []rune) bool { - if len(b) == 0 { - return false - } - - if b[0] == '\n' { - return true - } - - if len(b) < 2 { - return false - } - - return b[0] == '\r' && b[1] == '\n' -} - -func newNewlineToken(b []rune) (Token, int, error) { - i := 1 - if b[0] == '\r' && isNewline(b[1:]) { - i++ - } - - if !isNewline([]rune(b[:i])) { - return emptyToken, 0, NewParseError("invalid new line token") - } - - return newToken(TokenNL, b[:i], NoneType), i, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/number_helper.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/number_helper.go deleted file mode 100644 index a45c0bc56..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/number_helper.go +++ /dev/null @@ -1,152 +0,0 @@ -package ini - -import ( - "bytes" - "fmt" - "strconv" -) - -const ( - none = numberFormat(iota) - binary - octal - decimal - hex - exponent -) - -type numberFormat int - -// numberHelper is used to dictate what format a number is in -// and what to do for negative values. Since -1e-4 is a valid -// number, we cannot just simply check for duplicate negatives. -type numberHelper struct { - numberFormat numberFormat - - negative bool - negativeExponent bool -} - -func (b numberHelper) Exists() bool { - return b.numberFormat != none -} - -func (b numberHelper) IsNegative() bool { - return b.negative || b.negativeExponent -} - -func (b *numberHelper) Determine(c rune) error { - if b.Exists() { - return NewParseError(fmt.Sprintf("multiple number formats: 0%v", string(c))) - } - - switch c { - case 'b': - b.numberFormat = binary - case 'o': - b.numberFormat = octal - case 'x': - b.numberFormat = hex - case 'e', 'E': - b.numberFormat = exponent - case '-': - if b.numberFormat != exponent { - b.negative = true - } else { - b.negativeExponent = true - } - case '.': - b.numberFormat = decimal - default: - return NewParseError(fmt.Sprintf("invalid number character: %v", string(c))) - } - - return nil -} - -func (b numberHelper) CorrectByte(c rune) bool { - switch { - case b.numberFormat == binary: - if !isBinaryByte(c) { - return false - } - case b.numberFormat == octal: - if !isOctalByte(c) { - return false - } - case b.numberFormat == hex: - if !isHexByte(c) { - return false - } - case b.numberFormat == decimal: - if !isDigit(c) { - return false - } - case b.numberFormat == exponent: - if !isDigit(c) { - return false - } - case b.negativeExponent: - if !isDigit(c) { - return false - } - case b.negative: - if !isDigit(c) { - return false - } - default: - if !isDigit(c) { - return false - } - } - - return true -} - -func (b numberHelper) Base() int { - switch b.numberFormat { - case binary: - return 2 - case octal: - return 8 - case hex: - return 16 - default: - return 10 - } -} - -func (b numberHelper) String() string { - buf := bytes.Buffer{} - i := 0 - - switch b.numberFormat { - case binary: - i++ - buf.WriteString(strconv.Itoa(i) + ": binary format\n") - case octal: - i++ - buf.WriteString(strconv.Itoa(i) + ": octal format\n") - case hex: - i++ - buf.WriteString(strconv.Itoa(i) + ": hex format\n") - case exponent: - i++ - buf.WriteString(strconv.Itoa(i) + ": exponent format\n") - default: - i++ - buf.WriteString(strconv.Itoa(i) + ": integer format\n") - } - - if b.negative { - i++ - buf.WriteString(strconv.Itoa(i) + ": negative format\n") - } - - if b.negativeExponent { - i++ - buf.WriteString(strconv.Itoa(i) + ": negative exponent format\n") - } - - return buf.String() -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/op_tokens.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/op_tokens.go deleted file mode 100644 index 8a84c7cbe..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/op_tokens.go +++ /dev/null @@ -1,39 +0,0 @@ -package ini - -import ( - "fmt" -) - -var ( - equalOp = []rune("=") - equalColonOp = []rune(":") -) - -func isOp(b []rune) bool { - if len(b) == 0 { - return false - } - - switch b[0] { - case '=': - return true - case ':': - return true - default: - return false - } -} - -func newOpToken(b []rune) (Token, int, error) { - tok := Token{} - - switch b[0] { - case '=': - tok = newToken(TokenOp, equalOp, NoneType) - case ':': - tok = newToken(TokenOp, equalColonOp, NoneType) - default: - return tok, 0, NewParseError(fmt.Sprintf("unexpected op type, %v", b[0])) - } - return tok, 1, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_error.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_error.go deleted file mode 100644 index 457287019..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_error.go +++ /dev/null @@ -1,43 +0,0 @@ -package ini - -import "fmt" - -const ( - // ErrCodeParseError is returned when a parsing error - // has occurred. - ErrCodeParseError = "INIParseError" -) - -// ParseError is an error which is returned during any part of -// the parsing process. -type ParseError struct { - msg string -} - -// NewParseError will return a new ParseError where message -// is the description of the error. -func NewParseError(message string) *ParseError { - return &ParseError{ - msg: message, - } -} - -// Code will return the ErrCodeParseError -func (err *ParseError) Code() string { - return ErrCodeParseError -} - -// Message returns the error's message -func (err *ParseError) Message() string { - return err.msg -} - -// OrigError return nothing since there will never be any -// original error. -func (err *ParseError) OrigError() error { - return nil -} - -func (err *ParseError) Error() string { - return fmt.Sprintf("%s: %s", err.Code(), err.Message()) -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_stack.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_stack.go deleted file mode 100644 index 7f01cf7c7..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/parse_stack.go +++ /dev/null @@ -1,60 +0,0 @@ -package ini - -import ( - "bytes" - "fmt" -) - -// ParseStack is a stack that contains a container, the stack portion, -// and the list which is the list of ASTs that have been successfully -// parsed. -type ParseStack struct { - top int - container []AST - list []AST - index int -} - -func newParseStack(sizeContainer, sizeList int) ParseStack { - return ParseStack{ - container: make([]AST, sizeContainer), - list: make([]AST, sizeList), - } -} - -// Pop will return and truncate the last container element. -func (s *ParseStack) Pop() AST { - s.top-- - return s.container[s.top] -} - -// Push will add the new AST to the container -func (s *ParseStack) Push(ast AST) { - s.container[s.top] = ast - s.top++ -} - -// MarkComplete will append the AST to the list of completed statements -func (s *ParseStack) MarkComplete(ast AST) { - s.list[s.index] = ast - s.index++ -} - -// List will return the completed statements -func (s ParseStack) List() []AST { - return s.list[:s.index] -} - -// Len will return the length of the container -func (s *ParseStack) Len() int { - return s.top -} - -func (s ParseStack) String() string { - buf := bytes.Buffer{} - for i, node := range s.list { - buf.WriteString(fmt.Sprintf("%d: %v\n", i+1, node)) - } - - return buf.String() -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/sep_tokens.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/sep_tokens.go deleted file mode 100644 index f82095ba2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/sep_tokens.go +++ /dev/null @@ -1,41 +0,0 @@ -package ini - -import ( - "fmt" -) - -var ( - emptyRunes = []rune{} -) - -func isSep(b []rune) bool { - if len(b) == 0 { - return false - } - - switch b[0] { - case '[', ']': - return true - default: - return false - } -} - -var ( - openBrace = []rune("[") - closeBrace = []rune("]") -) - -func newSepToken(b []rune) (Token, int, error) { - tok := Token{} - - switch b[0] { - case '[': - tok = newToken(TokenSep, openBrace, NoneType) - case ']': - tok = newToken(TokenSep, closeBrace, NoneType) - default: - return tok, 0, NewParseError(fmt.Sprintf("unexpected sep type, %v", b[0])) - } - return tok, 1, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/skipper.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/skipper.go deleted file mode 100644 index da7a4049c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/skipper.go +++ /dev/null @@ -1,45 +0,0 @@ -package ini - -// skipper is used to skip certain blocks of an ini file. -// Currently skipper is used to skip nested blocks of ini -// files. See example below -// -// [ foo ] -// nested = ; this section will be skipped -// a=b -// c=d -// bar=baz ; this will be included -type skipper struct { - shouldSkip bool - TokenSet bool - prevTok Token -} - -func newSkipper() skipper { - return skipper{ - prevTok: emptyToken, - } -} - -func (s *skipper) ShouldSkip(tok Token) bool { - // should skip state will be modified only if previous token was new line (NL); - // and the current token is not WhiteSpace (WS). - if s.shouldSkip && - s.prevTok.Type() == TokenNL && - tok.Type() != TokenWS { - s.Continue() - return false - } - s.prevTok = tok - return s.shouldSkip -} - -func (s *skipper) Skip() { - s.shouldSkip = true -} - -func (s *skipper) Continue() { - s.shouldSkip = false - // empty token is assigned as we return to default state, when should skip is false - s.prevTok = emptyToken -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/statement.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/statement.go deleted file mode 100644 index 18f3fe893..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/statement.go +++ /dev/null @@ -1,35 +0,0 @@ -package ini - -// Statement is an empty AST mostly used for transitioning states. -func newStatement() AST { - return newAST(ASTKindStatement, AST{}) -} - -// SectionStatement represents a section AST -func newSectionStatement(tok Token) AST { - return newASTWithRootToken(ASTKindSectionStatement, tok) -} - -// ExprStatement represents a completed expression AST -func newExprStatement(ast AST) AST { - return newAST(ASTKindExprStatement, ast) -} - -// CommentStatement represents a comment in the ini definition. -// -// grammar: -// comment -> #comment' | ;comment' -// comment' -> epsilon | value -func newCommentStatement(tok Token) AST { - return newAST(ASTKindCommentStatement, newExpression(tok)) -} - -// CompletedSectionStatement represents a completed section -func newCompletedSectionStatement(ast AST) AST { - return newAST(ASTKindCompletedSectionStatement, ast) -} - -// SkipStatement is used to skip whole statements -func newSkipStatement(ast AST) AST { - return newAST(ASTKindSkipStatement, ast) -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/value_util.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/value_util.go deleted file mode 100644 index b5480fdeb..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/value_util.go +++ /dev/null @@ -1,284 +0,0 @@ -package ini - -import ( - "fmt" -) - -// getStringValue will return a quoted string and the amount -// of bytes read -// -// an error will be returned if the string is not properly formatted -func getStringValue(b []rune) (int, error) { - if b[0] != '"' { - return 0, NewParseError("strings must start with '\"'") - } - - endQuote := false - i := 1 - - for ; i < len(b) && !endQuote; i++ { - if escaped := isEscaped(b[:i], b[i]); b[i] == '"' && !escaped { - endQuote = true - break - } else if escaped { - /*c, err := getEscapedByte(b[i]) - if err != nil { - return 0, err - } - - b[i-1] = c - b = append(b[:i], b[i+1:]...) - i--*/ - - continue - } - } - - if !endQuote { - return 0, NewParseError("missing '\"' in string value") - } - - return i + 1, nil -} - -// getBoolValue will return a boolean and the amount -// of bytes read -// -// an error will be returned if the boolean is not of a correct -// value -func getBoolValue(b []rune) (int, error) { - if len(b) < 4 { - return 0, NewParseError("invalid boolean value") - } - - n := 0 - for _, lv := range literalValues { - if len(lv) > len(b) { - continue - } - - if isCaselessLitValue(lv, b) { - n = len(lv) - } - } - - if n == 0 { - return 0, NewParseError("invalid boolean value") - } - - return n, nil -} - -// getNumericalValue will return a numerical string, the amount -// of bytes read, and the base of the number -// -// an error will be returned if the number is not of a correct -// value -func getNumericalValue(b []rune) (int, int, error) { - if !isDigit(b[0]) { - return 0, 0, NewParseError("invalid digit value") - } - - i := 0 - helper := numberHelper{} - -loop: - for negativeIndex := 0; i < len(b); i++ { - negativeIndex++ - - if !isDigit(b[i]) { - switch b[i] { - case '-': - if helper.IsNegative() || negativeIndex != 1 { - return 0, 0, NewParseError("parse error '-'") - } - - n := getNegativeNumber(b[i:]) - i += (n - 1) - helper.Determine(b[i]) - continue - case '.': - if err := helper.Determine(b[i]); err != nil { - return 0, 0, err - } - case 'e', 'E': - if err := helper.Determine(b[i]); err != nil { - return 0, 0, err - } - - negativeIndex = 0 - case 'b': - if helper.numberFormat == hex { - break - } - fallthrough - case 'o', 'x': - if i == 0 && b[i] != '0' { - return 0, 0, NewParseError("incorrect base format, expected leading '0'") - } - - if i != 1 { - return 0, 0, NewParseError(fmt.Sprintf("incorrect base format found %s at %d index", string(b[i]), i)) - } - - if err := helper.Determine(b[i]); err != nil { - return 0, 0, err - } - default: - if isWhitespace(b[i]) { - break loop - } - - if isNewline(b[i:]) { - break loop - } - - if !(helper.numberFormat == hex && isHexByte(b[i])) { - if i+2 < len(b) && !isNewline(b[i:i+2]) { - return 0, 0, NewParseError("invalid numerical character") - } else if !isNewline([]rune{b[i]}) { - return 0, 0, NewParseError("invalid numerical character") - } - - break loop - } - } - } - } - - return helper.Base(), i, nil -} - -// isDigit will return whether or not something is an integer -func isDigit(b rune) bool { - return b >= '0' && b <= '9' -} - -func hasExponent(v []rune) bool { - return contains(v, 'e') || contains(v, 'E') -} - -func isBinaryByte(b rune) bool { - switch b { - case '0', '1': - return true - default: - return false - } -} - -func isOctalByte(b rune) bool { - switch b { - case '0', '1', '2', '3', '4', '5', '6', '7': - return true - default: - return false - } -} - -func isHexByte(b rune) bool { - if isDigit(b) { - return true - } - return (b >= 'A' && b <= 'F') || - (b >= 'a' && b <= 'f') -} - -func getValue(b []rune) (int, error) { - i := 0 - - for i < len(b) { - if isNewline(b[i:]) { - break - } - - if isOp(b[i:]) { - break - } - - valid, n, err := isValid(b[i:]) - if err != nil { - return 0, err - } - - if !valid { - break - } - - i += n - } - - return i, nil -} - -// getNegativeNumber will return a negative number from a -// byte slice. This will iterate through all characters until -// a non-digit has been found. -func getNegativeNumber(b []rune) int { - if b[0] != '-' { - return 0 - } - - i := 1 - for ; i < len(b); i++ { - if !isDigit(b[i]) { - return i - } - } - - return i -} - -// isEscaped will return whether or not the character is an escaped -// character. -func isEscaped(value []rune, b rune) bool { - if len(value) == 0 { - return false - } - - switch b { - case '\'': // single quote - case '"': // quote - case 'n': // newline - case 't': // tab - case '\\': // backslash - default: - return false - } - - return value[len(value)-1] == '\\' -} - -func getEscapedByte(b rune) (rune, error) { - switch b { - case '\'': // single quote - return '\'', nil - case '"': // quote - return '"', nil - case 'n': // newline - return '\n', nil - case 't': // table - return '\t', nil - case '\\': // backslash - return '\\', nil - default: - return b, NewParseError(fmt.Sprintf("invalid escaped character %c", b)) - } -} - -func removeEscapedCharacters(b []rune) []rune { - for i := 0; i < len(b); i++ { - if isEscaped(b[:i], b[i]) { - c, err := getEscapedByte(b[i]) - if err != nil { - return b - } - - b[i-1] = c - b = append(b[:i], b[i+1:]...) - i-- - } - } - - return b -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go deleted file mode 100644 index 1d08e138a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/visitor.go +++ /dev/null @@ -1,169 +0,0 @@ -package ini - -import ( - "fmt" - "sort" -) - -// Visitor is an interface used by walkers that will -// traverse an array of ASTs. -type Visitor interface { - VisitExpr(AST) error - VisitStatement(AST) error -} - -// DefaultVisitor is used to visit statements and expressions -// and ensure that they are both of the correct format. -// In addition, upon visiting this will build sections and populate -// the Sections field which can be used to retrieve profile -// configuration. -type DefaultVisitor struct { - scope string - Sections Sections -} - -// NewDefaultVisitor return a DefaultVisitor -func NewDefaultVisitor() *DefaultVisitor { - return &DefaultVisitor{ - Sections: Sections{ - container: map[string]Section{}, - }, - } -} - -// VisitExpr visits expressions... -func (v *DefaultVisitor) VisitExpr(expr AST) error { - t := v.Sections.container[v.scope] - if t.values == nil { - t.values = values{} - } - - switch expr.Kind { - case ASTKindExprStatement: - opExpr := expr.GetRoot() - switch opExpr.Kind { - case ASTKindEqualExpr: - children := opExpr.GetChildren() - if len(children) <= 1 { - return NewParseError("unexpected token type") - } - - rhs := children[1] - - // The right-hand value side the equality expression is allowed to contain '[', ']', ':', '=' in the values. - // If the token is not either a literal or one of the token types that identifies those four additional - // tokens then error. - if !(rhs.Root.Type() == TokenLit || rhs.Root.Type() == TokenOp || rhs.Root.Type() == TokenSep) { - return NewParseError("unexpected token type") - } - - key := EqualExprKey(opExpr) - v, err := newValue(rhs.Root.ValueType, rhs.Root.base, rhs.Root.Raw()) - if err != nil { - return err - } - - t.values[key] = v - default: - return NewParseError(fmt.Sprintf("unsupported expression %v", expr)) - } - default: - return NewParseError(fmt.Sprintf("unsupported expression %v", expr)) - } - - v.Sections.container[v.scope] = t - return nil -} - -// VisitStatement visits statements... -func (v *DefaultVisitor) VisitStatement(stmt AST) error { - switch stmt.Kind { - case ASTKindCompletedSectionStatement: - child := stmt.GetRoot() - if child.Kind != ASTKindSectionStatement { - return NewParseError(fmt.Sprintf("unsupported child statement: %T", child)) - } - - name := string(child.Root.Raw()) - v.Sections.container[name] = Section{} - v.scope = name - default: - return NewParseError(fmt.Sprintf("unsupported statement: %s", stmt.Kind)) - } - - return nil -} - -// Sections is a map of Section structures that represent -// a configuration. -type Sections struct { - container map[string]Section -} - -// GetSection will return section p. If section p does not exist, -// false will be returned in the second parameter. -func (t Sections) GetSection(p string) (Section, bool) { - v, ok := t.container[p] - return v, ok -} - -// values represents a map of union values. -type values map[string]Value - -// List will return a list of all sections that were successfully -// parsed. -func (t Sections) List() []string { - keys := make([]string, len(t.container)) - i := 0 - for k := range t.container { - keys[i] = k - i++ - } - - sort.Strings(keys) - return keys -} - -// Section contains a name and values. This represent -// a sectioned entry in a configuration file. -type Section struct { - Name string - values values -} - -// Has will return whether or not an entry exists in a given section -func (t Section) Has(k string) bool { - _, ok := t.values[k] - return ok -} - -// ValueType will returned what type the union is set to. If -// k was not found, the NoneType will be returned. -func (t Section) ValueType(k string) (ValueType, bool) { - v, ok := t.values[k] - return v.Type, ok -} - -// Bool returns a bool value at k -func (t Section) Bool(k string) (bool, bool) { - return t.values[k].BoolValue() -} - -// Int returns an integer value at k -func (t Section) Int(k string) (int64, bool) { - return t.values[k].IntValue() -} - -// Float64 returns a float value at k -func (t Section) Float64(k string) (float64, bool) { - return t.values[k].FloatValue() -} - -// String returns the string value at k -func (t Section) String(k string) string { - _, ok := t.values[k] - if !ok { - return "" - } - return t.values[k].StringValue() -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/walker.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/walker.go deleted file mode 100644 index 99915f7f7..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/walker.go +++ /dev/null @@ -1,25 +0,0 @@ -package ini - -// Walk will traverse the AST using the v, the Visitor. -func Walk(tree []AST, v Visitor) error { - for _, node := range tree { - switch node.Kind { - case ASTKindExpr, - ASTKindExprStatement: - - if err := v.VisitExpr(node); err != nil { - return err - } - case ASTKindStatement, - ASTKindCompletedSectionStatement, - ASTKindNestedSectionStatement, - ASTKindCompletedNestedSectionStatement: - - if err := v.VisitStatement(node); err != nil { - return err - } - } - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/ini/ws_token.go b/vendor/github.com/aws/aws-sdk-go/internal/ini/ws_token.go deleted file mode 100644 index 7ffb4ae06..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/ini/ws_token.go +++ /dev/null @@ -1,24 +0,0 @@ -package ini - -import ( - "unicode" -) - -// isWhitespace will return whether or not the character is -// a whitespace character. -// -// Whitespace is defined as a space or tab. -func isWhitespace(c rune) bool { - return unicode.IsSpace(c) && c != '\n' && c != '\r' -} - -func newWSToken(b []rune) (Token, int, error) { - i := 0 - for ; i < len(b); i++ { - if !isWhitespace(b[i]) { - break - } - } - - return newToken(TokenWS, b[:i], NoneType), i, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/byte.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/byte.go deleted file mode 100644 index 6c443988b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/byte.go +++ /dev/null @@ -1,12 +0,0 @@ -package sdkio - -const ( - // Byte is 8 bits - Byte int64 = 1 - // KibiByte (KiB) is 1024 Bytes - KibiByte = Byte * 1024 - // MebiByte (MiB) is 1024 KiB - MebiByte = KibiByte * 1024 - // GibiByte (GiB) is 1024 MiB - GibiByte = MebiByte * 1024 -) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go deleted file mode 100644 index 037a998c4..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !go1.7 -// +build !go1.7 - -package sdkio - -// Copy of Go 1.7 io package's Seeker constants. -const ( - SeekStart = 0 // seek relative to the origin of the file - SeekCurrent = 1 // seek relative to the current offset - SeekEnd = 2 // seek relative to the end -) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go deleted file mode 100644 index 65e7c60c4..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build go1.7 -// +build go1.7 - -package sdkio - -import "io" - -// Alias for Go 1.7 io package Seeker constants -const ( - SeekStart = io.SeekStart // seek relative to the origin of the file - SeekCurrent = io.SeekCurrent // seek relative to the current offset - SeekEnd = io.SeekEnd // seek relative to the end -) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkmath/floor.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkmath/floor.go deleted file mode 100644 index a84528783..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkmath/floor.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build go1.10 -// +build go1.10 - -package sdkmath - -import "math" - -// Round returns the nearest integer, rounding half away from zero. -// -// Special cases are: -// Round(±0) = ±0 -// Round(±Inf) = ±Inf -// Round(NaN) = NaN -func Round(x float64) float64 { - return math.Round(x) -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkmath/floor_go1.9.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkmath/floor_go1.9.go deleted file mode 100644 index a3ae3e5db..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkmath/floor_go1.9.go +++ /dev/null @@ -1,57 +0,0 @@ -//go:build !go1.10 -// +build !go1.10 - -package sdkmath - -import "math" - -// Copied from the Go standard library's (Go 1.12) math/floor.go for use in -// Go version prior to Go 1.10. -const ( - uvone = 0x3FF0000000000000 - mask = 0x7FF - shift = 64 - 11 - 1 - bias = 1023 - signMask = 1 << 63 - fracMask = 1<= 0.5 { - // return t + Copysign(1, x) - // } - // return t - // } - bits := math.Float64bits(x) - e := uint(bits>>shift) & mask - if e < bias { - // Round abs(x) < 1 including denormals. - bits &= signMask // +-0 - if e == bias-1 { - bits |= uvone // +-1 - } - } else if e < bias+shift { - // Round any abs(x) >= 1 containing a fractional component [0,1). - // - // Numbers with larger exponents are returned unchanged since they - // must be either an integer, infinity, or NaN. - const half = 1 << (shift - 1) - e -= bias - bits += half >> e - bits &^= fracMask >> e - } - return math.Float64frombits(bits) -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go deleted file mode 100644 index 0c9802d87..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go +++ /dev/null @@ -1,29 +0,0 @@ -package sdkrand - -import ( - "math/rand" - "sync" - "time" -) - -// lockedSource is a thread-safe implementation of rand.Source -type lockedSource struct { - lk sync.Mutex - src rand.Source -} - -func (r *lockedSource) Int63() (n int64) { - r.lk.Lock() - n = r.src.Int63() - r.lk.Unlock() - return -} - -func (r *lockedSource) Seed(seed int64) { - r.lk.Lock() - r.src.Seed(seed) - r.lk.Unlock() -} - -// SeededRand is a new RNG using a thread safe implementation of rand.Source -var SeededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/read.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/read.go deleted file mode 100644 index 4bae66cee..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/read.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build go1.6 -// +build go1.6 - -package sdkrand - -import "math/rand" - -// Read provides the stub for math.Rand.Read method support for go version's -// 1.6 and greater. -func Read(r *rand.Rand, p []byte) (int, error) { - return r.Read(p) -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/read_1_5.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/read_1_5.go deleted file mode 100644 index 3a6ab8825..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/read_1_5.go +++ /dev/null @@ -1,25 +0,0 @@ -//go:build !go1.6 -// +build !go1.6 - -package sdkrand - -import "math/rand" - -// Read backfills Go 1.6's math.Rand.Reader for Go 1.5 -func Read(r *rand.Rand, p []byte) (n int, err error) { - // Copy of Go standard libraries math package's read function not added to - // standard library until Go 1.6. - var pos int8 - var val int64 - for n = 0; n < len(p); n++ { - if pos == 0 { - val = r.Int63() - pos = 7 - } - p[n] = byte(val) - val >>= 8 - pos-- - } - - return n, err -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go deleted file mode 100644 index 38ea61afe..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkuri/path.go +++ /dev/null @@ -1,23 +0,0 @@ -package sdkuri - -import ( - "path" - "strings" -) - -// PathJoin will join the elements of the path delimited by the "/" -// character. Similar to path.Join with the exception the trailing "/" -// character is preserved if present. -func PathJoin(elems ...string) string { - if len(elems) == 0 { - return "" - } - - hasTrailing := strings.HasSuffix(elems[len(elems)-1], "/") - str := path.Join(elems...) - if hasTrailing && str != "/" { - str += "/" - } - - return str -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/ecs_container.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/ecs_container.go deleted file mode 100644 index 7da8a49ce..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/ecs_container.go +++ /dev/null @@ -1,12 +0,0 @@ -package shareddefaults - -const ( - // ECSCredsProviderEnvVar is an environmental variable key used to - // determine which path needs to be hit. - ECSCredsProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" -) - -// ECSContainerCredentialsURI is the endpoint to retrieve container -// credentials. This can be overridden to test to ensure the credential process -// is behaving correctly. -var ECSContainerCredentialsURI = "http://169.254.170.2" diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go deleted file mode 100644 index 34fea49ca..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go +++ /dev/null @@ -1,46 +0,0 @@ -package shareddefaults - -import ( - "os/user" - "path/filepath" -) - -// SharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func SharedCredentialsFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "credentials") -} - -// SharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func SharedConfigFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "config") -} - -// UserHomeDir returns the home directory for the user the process is -// running under. -func UserHomeDir() string { - var home string - - home = userHomeDir() - if len(home) > 0 { - return home - } - - currUser, _ := user.Current() - if currUser != nil { - home = currUser.HomeDir - } - - return home -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_resolve_home.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_resolve_home.go deleted file mode 100644 index eb298ae0f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_resolve_home.go +++ /dev/null @@ -1,18 +0,0 @@ -//go:build !go1.12 -// +build !go1.12 - -package shareddefaults - -import ( - "os" - "runtime" -) - -func userHomeDir() string { - if runtime.GOOS == "windows" { // Windows - return os.Getenv("USERPROFILE") - } - - // *nix - return os.Getenv("HOME") -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_resolve_home_go1.12.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_resolve_home_go1.12.go deleted file mode 100644 index 51541b508..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config_resolve_home_go1.12.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build go1.12 -// +build go1.12 - -package shareddefaults - -import ( - "os" -) - -func userHomeDir() string { - home, _ := os.UserHomeDir() - return home -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/strings/strings.go b/vendor/github.com/aws/aws-sdk-go/internal/strings/strings.go deleted file mode 100644 index d008ae27c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/strings/strings.go +++ /dev/null @@ -1,11 +0,0 @@ -package strings - -import ( - "strings" -) - -// HasPrefixFold tests whether the string s begins with prefix, interpreted as UTF-8 strings, -// under Unicode case-folding. -func HasPrefixFold(s, prefix string) bool { - return len(s) >= len(prefix) && strings.EqualFold(s[0:len(prefix)], prefix) -} diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sync/singleflight/LICENSE b/vendor/github.com/aws/aws-sdk-go/internal/sync/singleflight/LICENSE deleted file mode 100644 index 6a66aea5e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sync/singleflight/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. 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 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/vendor/github.com/aws/aws-sdk-go/internal/sync/singleflight/singleflight.go b/vendor/github.com/aws/aws-sdk-go/internal/sync/singleflight/singleflight.go deleted file mode 100644 index 14ad0c589..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sync/singleflight/singleflight.go +++ /dev/null @@ -1,120 +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. - -// Package singleflight provides a duplicate function call suppression -// mechanism. -package singleflight - -import "sync" - -// call is an in-flight or completed singleflight.Do call -type call struct { - wg sync.WaitGroup - - // These fields are written once before the WaitGroup is done - // and are only read after the WaitGroup is done. - val interface{} - err error - - // forgotten indicates whether Forget was called with this call's key - // while the call was still in flight. - forgotten bool - - // These fields are read and written with the singleflight - // mutex held before the WaitGroup is done, and are read but - // not written after the WaitGroup is done. - dups int - chans []chan<- Result -} - -// Group represents a class of work and forms a namespace in -// which units of work can be executed with duplicate suppression. -type Group struct { - mu sync.Mutex // protects m - m map[string]*call // lazily initialized -} - -// Result holds the results of Do, so they can be passed -// on a channel. -type Result struct { - Val interface{} - Err error - Shared bool -} - -// Do executes and returns the results of the given function, making -// sure that only one execution is in-flight for a given key at a -// time. If a duplicate comes in, the duplicate caller waits for the -// original to complete and receives the same results. -// The return value shared indicates whether v was given to multiple callers. -func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) { - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - g.mu.Unlock() - c.wg.Wait() - return c.val, c.err, true - } - c := new(call) - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - g.doCall(c, key, fn) - return c.val, c.err, c.dups > 0 -} - -// DoChan is like Do but returns a channel that will receive the -// results when they are ready. -func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result { - ch := make(chan Result, 1) - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - c.chans = append(c.chans, ch) - g.mu.Unlock() - return ch - } - c := &call{chans: []chan<- Result{ch}} - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - go g.doCall(c, key, fn) - - return ch -} - -// doCall handles the single call for a key. -func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) { - c.val, c.err = fn() - c.wg.Done() - - g.mu.Lock() - if !c.forgotten { - delete(g.m, key) - } - for _, ch := range c.chans { - ch <- Result{c.val, c.err, c.dups > 0} - } - g.mu.Unlock() -} - -// Forget tells the singleflight to forget about a key. Future calls -// to Do for this key will call the function rather than waiting for -// an earlier call to complete. -func (g *Group) Forget(key string) { - g.mu.Lock() - if c, ok := g.m[key]; ok { - c.forgotten = true - } - delete(g.m, key) - g.mu.Unlock() -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/debug.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/debug.go deleted file mode 100644 index 151054971..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/debug.go +++ /dev/null @@ -1,144 +0,0 @@ -package eventstream - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "strconv" -) - -type decodedMessage struct { - rawMessage - Headers decodedHeaders `json:"headers"` -} -type jsonMessage struct { - Length json.Number `json:"total_length"` - HeadersLen json.Number `json:"headers_length"` - PreludeCRC json.Number `json:"prelude_crc"` - Headers decodedHeaders `json:"headers"` - Payload []byte `json:"payload"` - CRC json.Number `json:"message_crc"` -} - -func (d *decodedMessage) UnmarshalJSON(b []byte) (err error) { - var jsonMsg jsonMessage - if err = json.Unmarshal(b, &jsonMsg); err != nil { - return err - } - - d.Length, err = numAsUint32(jsonMsg.Length) - if err != nil { - return err - } - d.HeadersLen, err = numAsUint32(jsonMsg.HeadersLen) - if err != nil { - return err - } - d.PreludeCRC, err = numAsUint32(jsonMsg.PreludeCRC) - if err != nil { - return err - } - d.Headers = jsonMsg.Headers - d.Payload = jsonMsg.Payload - d.CRC, err = numAsUint32(jsonMsg.CRC) - if err != nil { - return err - } - - return nil -} - -func (d *decodedMessage) MarshalJSON() ([]byte, error) { - jsonMsg := jsonMessage{ - Length: json.Number(strconv.Itoa(int(d.Length))), - HeadersLen: json.Number(strconv.Itoa(int(d.HeadersLen))), - PreludeCRC: json.Number(strconv.Itoa(int(d.PreludeCRC))), - Headers: d.Headers, - Payload: d.Payload, - CRC: json.Number(strconv.Itoa(int(d.CRC))), - } - - return json.Marshal(jsonMsg) -} - -func numAsUint32(n json.Number) (uint32, error) { - v, err := n.Int64() - if err != nil { - return 0, fmt.Errorf("failed to get int64 json number, %v", err) - } - - return uint32(v), nil -} - -func (d decodedMessage) Message() Message { - return Message{ - Headers: Headers(d.Headers), - Payload: d.Payload, - } -} - -type decodedHeaders Headers - -func (hs *decodedHeaders) UnmarshalJSON(b []byte) error { - var jsonHeaders []struct { - Name string `json:"name"` - Type valueType `json:"type"` - Value interface{} `json:"value"` - } - - decoder := json.NewDecoder(bytes.NewReader(b)) - decoder.UseNumber() - if err := decoder.Decode(&jsonHeaders); err != nil { - return err - } - - var headers Headers - for _, h := range jsonHeaders { - value, err := valueFromType(h.Type, h.Value) - if err != nil { - return err - } - headers.Set(h.Name, value) - } - *hs = decodedHeaders(headers) - - return nil -} - -func valueFromType(typ valueType, val interface{}) (Value, error) { - switch typ { - case trueValueType: - return BoolValue(true), nil - case falseValueType: - return BoolValue(false), nil - case int8ValueType: - v, err := val.(json.Number).Int64() - return Int8Value(int8(v)), err - case int16ValueType: - v, err := val.(json.Number).Int64() - return Int16Value(int16(v)), err - case int32ValueType: - v, err := val.(json.Number).Int64() - return Int32Value(int32(v)), err - case int64ValueType: - v, err := val.(json.Number).Int64() - return Int64Value(v), err - case bytesValueType: - v, err := base64.StdEncoding.DecodeString(val.(string)) - return BytesValue(v), err - case stringValueType: - v, err := base64.StdEncoding.DecodeString(val.(string)) - return StringValue(string(v)), err - case timestampValueType: - v, err := val.(json.Number).Int64() - return TimestampValue(timeFromEpochMilli(v)), err - case uuidValueType: - v, err := base64.StdEncoding.DecodeString(val.(string)) - var tv UUIDValue - copy(tv[:], v) - return tv, err - default: - panic(fmt.Sprintf("unknown type, %s, %T", typ.String(), val)) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/decode.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/decode.go deleted file mode 100644 index 474339391..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/decode.go +++ /dev/null @@ -1,216 +0,0 @@ -package eventstream - -import ( - "bytes" - "encoding/binary" - "encoding/hex" - "encoding/json" - "fmt" - "hash" - "hash/crc32" - "io" - - "github.com/aws/aws-sdk-go/aws" -) - -// Decoder provides decoding of an Event Stream messages. -type Decoder struct { - r io.Reader - logger aws.Logger -} - -// NewDecoder initializes and returns a Decoder for decoding event -// stream messages from the reader provided. -func NewDecoder(r io.Reader, opts ...func(*Decoder)) *Decoder { - d := &Decoder{ - r: r, - } - - for _, opt := range opts { - opt(d) - } - - return d -} - -// DecodeWithLogger adds a logger to be used by the decoder when decoding -// stream events. -func DecodeWithLogger(logger aws.Logger) func(*Decoder) { - return func(d *Decoder) { - d.logger = logger - } -} - -// Decode attempts to decode a single message from the event stream reader. -// Will return the event stream message, or error if Decode fails to read -// the message from the stream. -func (d *Decoder) Decode(payloadBuf []byte) (m Message, err error) { - reader := d.r - if d.logger != nil { - debugMsgBuf := bytes.NewBuffer(nil) - reader = io.TeeReader(reader, debugMsgBuf) - defer func() { - logMessageDecode(d.logger, debugMsgBuf, m, err) - }() - } - - m, err = Decode(reader, payloadBuf) - - return m, err -} - -// Decode attempts to decode a single message from the event stream reader. -// Will return the event stream message, or error if Decode fails to read -// the message from the reader. -func Decode(reader io.Reader, payloadBuf []byte) (m Message, err error) { - crc := crc32.New(crc32IEEETable) - hashReader := io.TeeReader(reader, crc) - - prelude, err := decodePrelude(hashReader, crc) - if err != nil { - return Message{}, err - } - - if prelude.HeadersLen > 0 { - lr := io.LimitReader(hashReader, int64(prelude.HeadersLen)) - m.Headers, err = decodeHeaders(lr) - if err != nil { - return Message{}, err - } - } - - if payloadLen := prelude.PayloadLen(); payloadLen > 0 { - buf, err := decodePayload(payloadBuf, io.LimitReader(hashReader, int64(payloadLen))) - if err != nil { - return Message{}, err - } - m.Payload = buf - } - - msgCRC := crc.Sum32() - if err := validateCRC(reader, msgCRC); err != nil { - return Message{}, err - } - - return m, nil -} - -func logMessageDecode(logger aws.Logger, msgBuf *bytes.Buffer, msg Message, decodeErr error) { - w := bytes.NewBuffer(nil) - defer func() { logger.Log(w.String()) }() - - fmt.Fprintf(w, "Raw message:\n%s\n", - hex.Dump(msgBuf.Bytes())) - - if decodeErr != nil { - fmt.Fprintf(w, "Decode error: %v\n", decodeErr) - return - } - - rawMsg, err := msg.rawMessage() - if err != nil { - fmt.Fprintf(w, "failed to create raw message, %v\n", err) - return - } - - decodedMsg := decodedMessage{ - rawMessage: rawMsg, - Headers: decodedHeaders(msg.Headers), - } - - fmt.Fprintf(w, "Decoded message:\n") - encoder := json.NewEncoder(w) - if err := encoder.Encode(decodedMsg); err != nil { - fmt.Fprintf(w, "failed to generate decoded message, %v\n", err) - } -} - -func decodePrelude(r io.Reader, crc hash.Hash32) (messagePrelude, error) { - var p messagePrelude - - var err error - p.Length, err = decodeUint32(r) - if err != nil { - return messagePrelude{}, err - } - - p.HeadersLen, err = decodeUint32(r) - if err != nil { - return messagePrelude{}, err - } - - if err := p.ValidateLens(); err != nil { - return messagePrelude{}, err - } - - preludeCRC := crc.Sum32() - if err := validateCRC(r, preludeCRC); err != nil { - return messagePrelude{}, err - } - - p.PreludeCRC = preludeCRC - - return p, nil -} - -func decodePayload(buf []byte, r io.Reader) ([]byte, error) { - w := bytes.NewBuffer(buf[0:0]) - - _, err := io.Copy(w, r) - return w.Bytes(), err -} - -func decodeUint8(r io.Reader) (uint8, error) { - type byteReader interface { - ReadByte() (byte, error) - } - - if br, ok := r.(byteReader); ok { - v, err := br.ReadByte() - return uint8(v), err - } - - var b [1]byte - _, err := io.ReadFull(r, b[:]) - return uint8(b[0]), err -} -func decodeUint16(r io.Reader) (uint16, error) { - var b [2]byte - bs := b[:] - _, err := io.ReadFull(r, bs) - if err != nil { - return 0, err - } - return binary.BigEndian.Uint16(bs), nil -} -func decodeUint32(r io.Reader) (uint32, error) { - var b [4]byte - bs := b[:] - _, err := io.ReadFull(r, bs) - if err != nil { - return 0, err - } - return binary.BigEndian.Uint32(bs), nil -} -func decodeUint64(r io.Reader) (uint64, error) { - var b [8]byte - bs := b[:] - _, err := io.ReadFull(r, bs) - if err != nil { - return 0, err - } - return binary.BigEndian.Uint64(bs), nil -} - -func validateCRC(r io.Reader, expect uint32) error { - msgCRC, err := decodeUint32(r) - if err != nil { - return err - } - - if msgCRC != expect { - return ChecksumError{} - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/encode.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/encode.go deleted file mode 100644 index ffade3bc0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/encode.go +++ /dev/null @@ -1,162 +0,0 @@ -package eventstream - -import ( - "bytes" - "encoding/binary" - "encoding/hex" - "encoding/json" - "fmt" - "hash" - "hash/crc32" - "io" - - "github.com/aws/aws-sdk-go/aws" -) - -// Encoder provides EventStream message encoding. -type Encoder struct { - w io.Writer - logger aws.Logger - - headersBuf *bytes.Buffer -} - -// NewEncoder initializes and returns an Encoder to encode Event Stream -// messages to an io.Writer. -func NewEncoder(w io.Writer, opts ...func(*Encoder)) *Encoder { - e := &Encoder{ - w: w, - headersBuf: bytes.NewBuffer(nil), - } - - for _, opt := range opts { - opt(e) - } - - return e -} - -// EncodeWithLogger adds a logger to be used by the encode when decoding -// stream events. -func EncodeWithLogger(logger aws.Logger) func(*Encoder) { - return func(d *Encoder) { - d.logger = logger - } -} - -// Encode encodes a single EventStream message to the io.Writer the Encoder -// was created with. An error is returned if writing the message fails. -func (e *Encoder) Encode(msg Message) (err error) { - e.headersBuf.Reset() - - writer := e.w - if e.logger != nil { - encodeMsgBuf := bytes.NewBuffer(nil) - writer = io.MultiWriter(writer, encodeMsgBuf) - defer func() { - logMessageEncode(e.logger, encodeMsgBuf, msg, err) - }() - } - - if err = EncodeHeaders(e.headersBuf, msg.Headers); err != nil { - return err - } - - crc := crc32.New(crc32IEEETable) - hashWriter := io.MultiWriter(writer, crc) - - headersLen := uint32(e.headersBuf.Len()) - payloadLen := uint32(len(msg.Payload)) - - if err = encodePrelude(hashWriter, crc, headersLen, payloadLen); err != nil { - return err - } - - if headersLen > 0 { - if _, err = io.Copy(hashWriter, e.headersBuf); err != nil { - return err - } - } - - if payloadLen > 0 { - if _, err = hashWriter.Write(msg.Payload); err != nil { - return err - } - } - - msgCRC := crc.Sum32() - return binary.Write(writer, binary.BigEndian, msgCRC) -} - -func logMessageEncode(logger aws.Logger, msgBuf *bytes.Buffer, msg Message, encodeErr error) { - w := bytes.NewBuffer(nil) - defer func() { logger.Log(w.String()) }() - - fmt.Fprintf(w, "Message to encode:\n") - encoder := json.NewEncoder(w) - if err := encoder.Encode(msg); err != nil { - fmt.Fprintf(w, "Failed to get encoded message, %v\n", err) - } - - if encodeErr != nil { - fmt.Fprintf(w, "Encode error: %v\n", encodeErr) - return - } - - fmt.Fprintf(w, "Raw message:\n%s\n", hex.Dump(msgBuf.Bytes())) -} - -func encodePrelude(w io.Writer, crc hash.Hash32, headersLen, payloadLen uint32) error { - p := messagePrelude{ - Length: minMsgLen + headersLen + payloadLen, - HeadersLen: headersLen, - } - if err := p.ValidateLens(); err != nil { - return err - } - - err := binaryWriteFields(w, binary.BigEndian, - p.Length, - p.HeadersLen, - ) - if err != nil { - return err - } - - p.PreludeCRC = crc.Sum32() - err = binary.Write(w, binary.BigEndian, p.PreludeCRC) - if err != nil { - return err - } - - return nil -} - -// EncodeHeaders writes the header values to the writer encoded in the event -// stream format. Returns an error if a header fails to encode. -func EncodeHeaders(w io.Writer, headers Headers) error { - for _, h := range headers { - hn := headerName{ - Len: uint8(len(h.Name)), - } - copy(hn.Name[:hn.Len], h.Name) - if err := hn.encode(w); err != nil { - return err - } - - if err := h.Value.encode(w); err != nil { - return err - } - } - - return nil -} - -func binaryWriteFields(w io.Writer, order binary.ByteOrder, vs ...interface{}) error { - for _, v := range vs { - if err := binary.Write(w, order, v); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/error.go deleted file mode 100644 index 5481ef307..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/error.go +++ /dev/null @@ -1,23 +0,0 @@ -package eventstream - -import "fmt" - -// LengthError provides the error for items being larger than a maximum length. -type LengthError struct { - Part string - Want int - Have int - Value interface{} -} - -func (e LengthError) Error() string { - return fmt.Sprintf("%s length invalid, %d/%d, %v", - e.Part, e.Want, e.Have, e.Value) -} - -// ChecksumError provides the error for message checksum invalidation errors. -type ChecksumError struct{} - -func (e ChecksumError) Error() string { - return "message checksum mismatch" -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/error.go deleted file mode 100644 index 0a63340e4..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/error.go +++ /dev/null @@ -1,81 +0,0 @@ -package eventstreamapi - -import ( - "fmt" - "sync" -) - -// InputWriterCloseErrorCode is used to denote an error occurred -// while closing the event stream input writer. -const InputWriterCloseErrorCode = "EventStreamInputWriterCloseError" - -type messageError struct { - code string - msg string -} - -func (e messageError) Code() string { - return e.code -} - -func (e messageError) Message() string { - return e.msg -} - -func (e messageError) Error() string { - return fmt.Sprintf("%s: %s", e.code, e.msg) -} - -func (e messageError) OrigErr() error { - return nil -} - -// OnceError wraps the behavior of recording an error -// once and signal on a channel when this has occurred. -// Signaling is done by closing of the channel. -// -// Type is safe for concurrent usage. -type OnceError struct { - mu sync.RWMutex - err error - ch chan struct{} -} - -// NewOnceError return a new OnceError -func NewOnceError() *OnceError { - return &OnceError{ - ch: make(chan struct{}, 1), - } -} - -// Err acquires a read-lock and returns an -// error if one has been set. -func (e *OnceError) Err() error { - e.mu.RLock() - err := e.err - e.mu.RUnlock() - - return err -} - -// SetError acquires a write-lock and will set -// the underlying error value if one has not been set. -func (e *OnceError) SetError(err error) { - if err == nil { - return - } - - e.mu.Lock() - if e.err == nil { - e.err = err - close(e.ch) - } - e.mu.Unlock() -} - -// ErrorSet returns a channel that will be used to signal -// that an error has been set. This channel will be closed -// when the error value has been set for OnceError. -func (e *OnceError) ErrorSet() <-chan struct{} { - return e.ch -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go deleted file mode 100644 index 0e4aa42f3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go +++ /dev/null @@ -1,173 +0,0 @@ -package eventstreamapi - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/eventstream" -) - -// Unmarshaler provides the interface for unmarshaling a EventStream -// message into a SDK type. -type Unmarshaler interface { - UnmarshalEvent(protocol.PayloadUnmarshaler, eventstream.Message) error -} - -// EventReader provides reading from the EventStream of an reader. -type EventReader struct { - decoder *eventstream.Decoder - - unmarshalerForEventType func(string) (Unmarshaler, error) - payloadUnmarshaler protocol.PayloadUnmarshaler - - payloadBuf []byte -} - -// NewEventReader returns a EventReader built from the reader and unmarshaler -// provided. Use ReadStream method to start reading from the EventStream. -func NewEventReader( - decoder *eventstream.Decoder, - payloadUnmarshaler protocol.PayloadUnmarshaler, - unmarshalerForEventType func(string) (Unmarshaler, error), -) *EventReader { - return &EventReader{ - decoder: decoder, - payloadUnmarshaler: payloadUnmarshaler, - unmarshalerForEventType: unmarshalerForEventType, - payloadBuf: make([]byte, 10*1024), - } -} - -// ReadEvent attempts to read a message from the EventStream and return the -// unmarshaled event value that the message is for. -// -// For EventStream API errors check if the returned error satisfies the -// awserr.Error interface to get the error's Code and Message components. -// -// EventUnmarshalers called with EventStream messages must take copies of the -// message's Payload. The payload will is reused between events read. -func (r *EventReader) ReadEvent() (event interface{}, err error) { - msg, err := r.decoder.Decode(r.payloadBuf) - if err != nil { - return nil, err - } - defer func() { - // Reclaim payload buffer for next message read. - r.payloadBuf = msg.Payload[0:0] - }() - - typ, err := GetHeaderString(msg, MessageTypeHeader) - if err != nil { - return nil, err - } - - switch typ { - case EventMessageType: - return r.unmarshalEventMessage(msg) - case ExceptionMessageType: - return nil, r.unmarshalEventException(msg) - case ErrorMessageType: - return nil, r.unmarshalErrorMessage(msg) - default: - return nil, &UnknownMessageTypeError{ - Type: typ, Message: msg.Clone(), - } - } -} - -// UnknownMessageTypeError provides an error when a message is received from -// the stream, but the reader is unable to determine what kind of message it is. -type UnknownMessageTypeError struct { - Type string - Message eventstream.Message -} - -func (e *UnknownMessageTypeError) Error() string { - return "unknown eventstream message type, " + e.Type -} - -func (r *EventReader) unmarshalEventMessage( - msg eventstream.Message, -) (event interface{}, err error) { - eventType, err := GetHeaderString(msg, EventTypeHeader) - if err != nil { - return nil, err - } - - ev, err := r.unmarshalerForEventType(eventType) - if err != nil { - return nil, err - } - - err = ev.UnmarshalEvent(r.payloadUnmarshaler, msg) - if err != nil { - return nil, err - } - - return ev, nil -} - -func (r *EventReader) unmarshalEventException( - msg eventstream.Message, -) (err error) { - eventType, err := GetHeaderString(msg, ExceptionTypeHeader) - if err != nil { - return err - } - - ev, err := r.unmarshalerForEventType(eventType) - if err != nil { - return err - } - - err = ev.UnmarshalEvent(r.payloadUnmarshaler, msg) - if err != nil { - return err - } - - var ok bool - err, ok = ev.(error) - if !ok { - err = messageError{ - code: "SerializationError", - msg: fmt.Sprintf( - "event stream exception %s mapped to non-error %T, %v", - eventType, ev, ev, - ), - } - } - - return err -} - -func (r *EventReader) unmarshalErrorMessage(msg eventstream.Message) (err error) { - var msgErr messageError - - msgErr.code, err = GetHeaderString(msg, ErrorCodeHeader) - if err != nil { - return err - } - - msgErr.msg, err = GetHeaderString(msg, ErrorMessageHeader) - if err != nil { - return err - } - - return msgErr -} - -// GetHeaderString returns the value of the header as a string. If the header -// is not set or the value is not a string an error will be returned. -func GetHeaderString(msg eventstream.Message, headerName string) (string, error) { - headerVal := msg.Headers.Get(headerName) - if headerVal == nil { - return "", fmt.Errorf("error header %s not present", headerName) - } - - v, ok := headerVal.Get().(string) - if !ok { - return "", fmt.Errorf("error header value is not a string, %T", headerVal) - } - - return v, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/shared.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/shared.go deleted file mode 100644 index e46b8acc2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/shared.go +++ /dev/null @@ -1,23 +0,0 @@ -package eventstreamapi - -// EventStream headers with specific meaning to async API functionality. -const ( - ChunkSignatureHeader = `:chunk-signature` // chunk signature for message - DateHeader = `:date` // Date header for signature - - // Message header and values - MessageTypeHeader = `:message-type` // Identifies type of message. - EventMessageType = `event` - ErrorMessageType = `error` - ExceptionMessageType = `exception` - - // Message Events - EventTypeHeader = `:event-type` // Identifies message event type e.g. "Stats". - - // Message Error - ErrorCodeHeader = `:error-code` - ErrorMessageHeader = `:error-message` - - // Message Exception - ExceptionTypeHeader = `:exception-type` -) diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/signer.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/signer.go deleted file mode 100644 index 3a7ba5cd5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/signer.go +++ /dev/null @@ -1,123 +0,0 @@ -package eventstreamapi - -import ( - "bytes" - "strings" - "time" - - "github.com/aws/aws-sdk-go/private/protocol/eventstream" -) - -var timeNow = time.Now - -// StreamSigner defines an interface for the implementation of signing of event stream payloads -type StreamSigner interface { - GetSignature(headers, payload []byte, date time.Time) ([]byte, error) -} - -// SignEncoder envelopes event stream messages -// into an event stream message payload with included -// signature headers using the provided signer and encoder. -type SignEncoder struct { - signer StreamSigner - encoder Encoder - bufEncoder *BufferEncoder - - closeErr error - closed bool -} - -// NewSignEncoder returns a new SignEncoder using the provided stream signer and -// event stream encoder. -func NewSignEncoder(signer StreamSigner, encoder Encoder) *SignEncoder { - // TODO: Need to pass down logging - - return &SignEncoder{ - signer: signer, - encoder: encoder, - bufEncoder: NewBufferEncoder(), - } -} - -// Close encodes a final event stream signing envelope with an empty event stream -// payload. This final end-frame is used to mark the conclusion of the stream. -func (s *SignEncoder) Close() error { - if s.closed { - return s.closeErr - } - - if err := s.encode([]byte{}); err != nil { - if strings.Contains(err.Error(), "on closed pipe") { - return nil - } - - s.closeErr = err - s.closed = true - return s.closeErr - } - - return nil -} - -// Encode takes the provided message and add envelopes the message -// with the required signature. -func (s *SignEncoder) Encode(msg eventstream.Message) error { - payload, err := s.bufEncoder.Encode(msg) - if err != nil { - return err - } - - return s.encode(payload) -} - -func (s SignEncoder) encode(payload []byte) error { - date := timeNow() - - var msg eventstream.Message - msg.Headers.Set(DateHeader, eventstream.TimestampValue(date)) - msg.Payload = payload - - var headers bytes.Buffer - if err := eventstream.EncodeHeaders(&headers, msg.Headers); err != nil { - return err - } - - sig, err := s.signer.GetSignature(headers.Bytes(), msg.Payload, date) - if err != nil { - return err - } - - msg.Headers.Set(ChunkSignatureHeader, eventstream.BytesValue(sig)) - - return s.encoder.Encode(msg) -} - -// BufferEncoder is a utility that provides a buffered -// event stream encoder -type BufferEncoder struct { - encoder Encoder - buffer *bytes.Buffer -} - -// NewBufferEncoder returns a new BufferEncoder initialized -// with a 1024 byte buffer. -func NewBufferEncoder() *BufferEncoder { - buf := bytes.NewBuffer(make([]byte, 1024)) - return &BufferEncoder{ - encoder: eventstream.NewEncoder(buf), - buffer: buf, - } -} - -// Encode returns the encoded message as a byte slice. -// The returned byte slice will be modified on the next encode call -// and should not be held onto. -func (e *BufferEncoder) Encode(msg eventstream.Message) ([]byte, error) { - e.buffer.Reset() - - if err := e.encoder.Encode(msg); err != nil { - return nil, err - } - - return e.buffer.Bytes(), nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/stream_writer.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/stream_writer.go deleted file mode 100644 index 433bb1630..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/stream_writer.go +++ /dev/null @@ -1,129 +0,0 @@ -package eventstreamapi - -import ( - "fmt" - "io" - "sync" - - "github.com/aws/aws-sdk-go/aws" -) - -// StreamWriter provides concurrent safe writing to an event stream. -type StreamWriter struct { - eventWriter *EventWriter - stream chan eventWriteAsyncReport - - done chan struct{} - closeOnce sync.Once - err *OnceError - - streamCloser io.Closer -} - -// NewStreamWriter returns a StreamWriter for the event writer, and stream -// closer provided. -func NewStreamWriter(eventWriter *EventWriter, streamCloser io.Closer) *StreamWriter { - w := &StreamWriter{ - eventWriter: eventWriter, - streamCloser: streamCloser, - stream: make(chan eventWriteAsyncReport), - done: make(chan struct{}), - err: NewOnceError(), - } - go w.writeStream() - - return w -} - -// Close terminates the writers ability to write new events to the stream. Any -// future call to Send will fail with an error. -func (w *StreamWriter) Close() error { - w.closeOnce.Do(w.safeClose) - return w.Err() -} - -func (w *StreamWriter) safeClose() { - close(w.done) -} - -// ErrorSet returns a channel which will be closed -// if an error occurs. -func (w *StreamWriter) ErrorSet() <-chan struct{} { - return w.err.ErrorSet() -} - -// Err returns any error that occurred while attempting to write an event to the -// stream. -func (w *StreamWriter) Err() error { - return w.err.Err() -} - -// Send writes a single event to the stream returning an error if the write -// failed. -// -// Send may be called concurrently. Events will be written to the stream -// safely. -func (w *StreamWriter) Send(ctx aws.Context, event Marshaler) error { - if err := w.Err(); err != nil { - return err - } - - resultCh := make(chan error) - wrapped := eventWriteAsyncReport{ - Event: event, - Result: resultCh, - } - - select { - case w.stream <- wrapped: - case <-ctx.Done(): - return ctx.Err() - case <-w.done: - return fmt.Errorf("stream closed, unable to send event") - } - - select { - case err := <-resultCh: - return err - case <-ctx.Done(): - return ctx.Err() - case <-w.done: - return fmt.Errorf("stream closed, unable to send event") - } -} - -func (w *StreamWriter) writeStream() { - defer w.Close() - - for { - select { - case wrapper := <-w.stream: - err := w.eventWriter.WriteEvent(wrapper.Event) - wrapper.ReportResult(w.done, err) - if err != nil { - w.err.SetError(err) - return - } - - case <-w.done: - if err := w.streamCloser.Close(); err != nil { - w.err.SetError(err) - } - return - } - } -} - -type eventWriteAsyncReport struct { - Event Marshaler - Result chan<- error -} - -func (e eventWriteAsyncReport) ReportResult(cancel <-chan struct{}, err error) bool { - select { - case e.Result <- err: - return true - case <-cancel: - return false - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/transport.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/transport.go deleted file mode 100644 index 4bf2b27b2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/transport.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -package eventstreamapi - -import "github.com/aws/aws-sdk-go/aws/request" - -// ApplyHTTPTransportFixes is a no-op for Go 1.18 and above. -func ApplyHTTPTransportFixes(r *request.Request) { -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/transport_go1.17.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/transport_go1.17.go deleted file mode 100644 index 2ee2c36fd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/transport_go1.17.go +++ /dev/null @@ -1,19 +0,0 @@ -//go:build !go1.18 -// +build !go1.18 - -package eventstreamapi - -import "github.com/aws/aws-sdk-go/aws/request" - -// ApplyHTTPTransportFixes applies fixes to the HTTP request for proper event -// stream functionality. Go 1.15 through 1.17 HTTP client could hang forever -// when an HTTP/2 connection failed with an non-200 status code and err. Using -// Expect 100-Continue, allows the HTTP client to gracefully handle the non-200 -// status code, and close the connection. -// -// This is a no-op for Go 1.18 and above. -func ApplyHTTPTransportFixes(r *request.Request) { - r.Handlers.Sign.PushBack(func(r *request.Request) { - r.HTTPRequest.Header.Set("Expect", "100-Continue") - }) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/writer.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/writer.go deleted file mode 100644 index 7d7a79352..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/writer.go +++ /dev/null @@ -1,63 +0,0 @@ -package eventstreamapi - -import ( - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/eventstream" -) - -// Marshaler provides a marshaling interface for event types to event stream -// messages. -type Marshaler interface { - MarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error) -} - -// Encoder is an stream encoder that will encode an event stream message for -// the transport. -type Encoder interface { - Encode(eventstream.Message) error -} - -// EventWriter provides a wrapper around the underlying event stream encoder -// for an io.WriteCloser. -type EventWriter struct { - encoder Encoder - payloadMarshaler protocol.PayloadMarshaler - eventTypeFor func(Marshaler) (string, error) -} - -// NewEventWriter returns a new event stream writer, that will write to the -// writer provided. Use the WriteEvent method to write an event to the stream. -func NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error), -) *EventWriter { - return &EventWriter{ - encoder: encoder, - payloadMarshaler: pm, - eventTypeFor: eventTypeFor, - } -} - -// WriteEvent writes an event to the stream. Returns an error if the event -// fails to marshal into a message, or writing to the underlying writer fails. -func (w *EventWriter) WriteEvent(event Marshaler) error { - msg, err := w.marshal(event) - if err != nil { - return err - } - - return w.encoder.Encode(msg) -} - -func (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) { - eventType, err := w.eventTypeFor(event) - if err != nil { - return eventstream.Message{}, err - } - - msg, err := event.MarshalEvent(w.payloadMarshaler) - if err != nil { - return eventstream.Message{}, err - } - - msg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType)) - return msg, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go deleted file mode 100644 index f6f8c5674..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go +++ /dev/null @@ -1,175 +0,0 @@ -package eventstream - -import ( - "encoding/binary" - "fmt" - "io" -) - -// Headers are a collection of EventStream header values. -type Headers []Header - -// Header is a single EventStream Key Value header pair. -type Header struct { - Name string - Value Value -} - -// Set associates the name with a value. If the header name already exists in -// the Headers the value will be replaced with the new one. -func (hs *Headers) Set(name string, value Value) { - var i int - for ; i < len(*hs); i++ { - if (*hs)[i].Name == name { - (*hs)[i].Value = value - return - } - } - - *hs = append(*hs, Header{ - Name: name, Value: value, - }) -} - -// Get returns the Value associated with the header. Nil is returned if the -// value does not exist. -func (hs Headers) Get(name string) Value { - for i := 0; i < len(hs); i++ { - if h := hs[i]; h.Name == name { - return h.Value - } - } - return nil -} - -// Del deletes the value in the Headers if it exists. -func (hs *Headers) Del(name string) { - for i := 0; i < len(*hs); i++ { - if (*hs)[i].Name == name { - copy((*hs)[i:], (*hs)[i+1:]) - (*hs) = (*hs)[:len(*hs)-1] - } - } -} - -// Clone returns a deep copy of the headers -func (hs Headers) Clone() Headers { - o := make(Headers, 0, len(hs)) - for _, h := range hs { - o.Set(h.Name, h.Value) - } - return o -} - -func decodeHeaders(r io.Reader) (Headers, error) { - hs := Headers{} - - for { - name, err := decodeHeaderName(r) - if err != nil { - if err == io.EOF { - // EOF while getting header name means no more headers - break - } - return nil, err - } - - value, err := decodeHeaderValue(r) - if err != nil { - return nil, err - } - - hs.Set(name, value) - } - - return hs, nil -} - -func decodeHeaderName(r io.Reader) (string, error) { - var n headerName - - var err error - n.Len, err = decodeUint8(r) - if err != nil { - return "", err - } - - name := n.Name[:n.Len] - if _, err := io.ReadFull(r, name); err != nil { - return "", err - } - - return string(name), nil -} - -func decodeHeaderValue(r io.Reader) (Value, error) { - var raw rawValue - - typ, err := decodeUint8(r) - if err != nil { - return nil, err - } - raw.Type = valueType(typ) - - var v Value - - switch raw.Type { - case trueValueType: - v = BoolValue(true) - case falseValueType: - v = BoolValue(false) - case int8ValueType: - var tv Int8Value - err = tv.decode(r) - v = tv - case int16ValueType: - var tv Int16Value - err = tv.decode(r) - v = tv - case int32ValueType: - var tv Int32Value - err = tv.decode(r) - v = tv - case int64ValueType: - var tv Int64Value - err = tv.decode(r) - v = tv - case bytesValueType: - var tv BytesValue - err = tv.decode(r) - v = tv - case stringValueType: - var tv StringValue - err = tv.decode(r) - v = tv - case timestampValueType: - var tv TimestampValue - err = tv.decode(r) - v = tv - case uuidValueType: - var tv UUIDValue - err = tv.decode(r) - v = tv - default: - panic(fmt.Sprintf("unknown value type %d", raw.Type)) - } - - // Error could be EOF, let caller deal with it - return v, err -} - -const maxHeaderNameLen = 255 - -type headerName struct { - Len uint8 - Name [maxHeaderNameLen]byte -} - -func (v headerName) encode(w io.Writer) error { - if err := binary.Write(w, binary.BigEndian, v.Len); err != nil { - return err - } - - _, err := w.Write(v.Name[:v.Len]) - return err -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header_value.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header_value.go deleted file mode 100644 index 9f509d8f6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header_value.go +++ /dev/null @@ -1,506 +0,0 @@ -package eventstream - -import ( - "encoding/base64" - "encoding/binary" - "fmt" - "io" - "strconv" - "time" -) - -const maxHeaderValueLen = 1<<15 - 1 // 2^15-1 or 32KB - 1 - -// valueType is the EventStream header value type. -type valueType uint8 - -// Header value types -const ( - trueValueType valueType = iota - falseValueType - int8ValueType // Byte - int16ValueType // Short - int32ValueType // Integer - int64ValueType // Long - bytesValueType - stringValueType - timestampValueType - uuidValueType -) - -func (t valueType) String() string { - switch t { - case trueValueType: - return "bool" - case falseValueType: - return "bool" - case int8ValueType: - return "int8" - case int16ValueType: - return "int16" - case int32ValueType: - return "int32" - case int64ValueType: - return "int64" - case bytesValueType: - return "byte_array" - case stringValueType: - return "string" - case timestampValueType: - return "timestamp" - case uuidValueType: - return "uuid" - default: - return fmt.Sprintf("unknown value type %d", uint8(t)) - } -} - -type rawValue struct { - Type valueType - Len uint16 // Only set for variable length slices - Value []byte // byte representation of value, BigEndian encoding. -} - -func (r rawValue) encodeScalar(w io.Writer, v interface{}) error { - return binaryWriteFields(w, binary.BigEndian, - r.Type, - v, - ) -} - -func (r rawValue) encodeFixedSlice(w io.Writer, v []byte) error { - binary.Write(w, binary.BigEndian, r.Type) - - _, err := w.Write(v) - return err -} - -func (r rawValue) encodeBytes(w io.Writer, v []byte) error { - if len(v) > maxHeaderValueLen { - return LengthError{ - Part: "header value", - Want: maxHeaderValueLen, Have: len(v), - Value: v, - } - } - r.Len = uint16(len(v)) - - err := binaryWriteFields(w, binary.BigEndian, - r.Type, - r.Len, - ) - if err != nil { - return err - } - - _, err = w.Write(v) - return err -} - -func (r rawValue) encodeString(w io.Writer, v string) error { - if len(v) > maxHeaderValueLen { - return LengthError{ - Part: "header value", - Want: maxHeaderValueLen, Have: len(v), - Value: v, - } - } - r.Len = uint16(len(v)) - - type stringWriter interface { - WriteString(string) (int, error) - } - - err := binaryWriteFields(w, binary.BigEndian, - r.Type, - r.Len, - ) - if err != nil { - return err - } - - if sw, ok := w.(stringWriter); ok { - _, err = sw.WriteString(v) - } else { - _, err = w.Write([]byte(v)) - } - - return err -} - -func decodeFixedBytesValue(r io.Reader, buf []byte) error { - _, err := io.ReadFull(r, buf) - return err -} - -func decodeBytesValue(r io.Reader) ([]byte, error) { - var raw rawValue - var err error - raw.Len, err = decodeUint16(r) - if err != nil { - return nil, err - } - - buf := make([]byte, raw.Len) - _, err = io.ReadFull(r, buf) - if err != nil { - return nil, err - } - - return buf, nil -} - -func decodeStringValue(r io.Reader) (string, error) { - v, err := decodeBytesValue(r) - return string(v), err -} - -// Value represents the abstract header value. -type Value interface { - Get() interface{} - String() string - valueType() valueType - encode(io.Writer) error -} - -// An BoolValue provides eventstream encoding, and representation -// of a Go bool value. -type BoolValue bool - -// Get returns the underlying type -func (v BoolValue) Get() interface{} { - return bool(v) -} - -// valueType returns the EventStream header value type value. -func (v BoolValue) valueType() valueType { - if v { - return trueValueType - } - return falseValueType -} - -func (v BoolValue) String() string { - return strconv.FormatBool(bool(v)) -} - -// encode encodes the BoolValue into an eventstream binary value -// representation. -func (v BoolValue) encode(w io.Writer) error { - return binary.Write(w, binary.BigEndian, v.valueType()) -} - -// An Int8Value provides eventstream encoding, and representation of a Go -// int8 value. -type Int8Value int8 - -// Get returns the underlying value. -func (v Int8Value) Get() interface{} { - return int8(v) -} - -// valueType returns the EventStream header value type value. -func (Int8Value) valueType() valueType { - return int8ValueType -} - -func (v Int8Value) String() string { - return fmt.Sprintf("0x%02x", int8(v)) -} - -// encode encodes the Int8Value into an eventstream binary value -// representation. -func (v Int8Value) encode(w io.Writer) error { - raw := rawValue{ - Type: v.valueType(), - } - - return raw.encodeScalar(w, v) -} - -func (v *Int8Value) decode(r io.Reader) error { - n, err := decodeUint8(r) - if err != nil { - return err - } - - *v = Int8Value(n) - return nil -} - -// An Int16Value provides eventstream encoding, and representation of a Go -// int16 value. -type Int16Value int16 - -// Get returns the underlying value. -func (v Int16Value) Get() interface{} { - return int16(v) -} - -// valueType returns the EventStream header value type value. -func (Int16Value) valueType() valueType { - return int16ValueType -} - -func (v Int16Value) String() string { - return fmt.Sprintf("0x%04x", int16(v)) -} - -// encode encodes the Int16Value into an eventstream binary value -// representation. -func (v Int16Value) encode(w io.Writer) error { - raw := rawValue{ - Type: v.valueType(), - } - return raw.encodeScalar(w, v) -} - -func (v *Int16Value) decode(r io.Reader) error { - n, err := decodeUint16(r) - if err != nil { - return err - } - - *v = Int16Value(n) - return nil -} - -// An Int32Value provides eventstream encoding, and representation of a Go -// int32 value. -type Int32Value int32 - -// Get returns the underlying value. -func (v Int32Value) Get() interface{} { - return int32(v) -} - -// valueType returns the EventStream header value type value. -func (Int32Value) valueType() valueType { - return int32ValueType -} - -func (v Int32Value) String() string { - return fmt.Sprintf("0x%08x", int32(v)) -} - -// encode encodes the Int32Value into an eventstream binary value -// representation. -func (v Int32Value) encode(w io.Writer) error { - raw := rawValue{ - Type: v.valueType(), - } - return raw.encodeScalar(w, v) -} - -func (v *Int32Value) decode(r io.Reader) error { - n, err := decodeUint32(r) - if err != nil { - return err - } - - *v = Int32Value(n) - return nil -} - -// An Int64Value provides eventstream encoding, and representation of a Go -// int64 value. -type Int64Value int64 - -// Get returns the underlying value. -func (v Int64Value) Get() interface{} { - return int64(v) -} - -// valueType returns the EventStream header value type value. -func (Int64Value) valueType() valueType { - return int64ValueType -} - -func (v Int64Value) String() string { - return fmt.Sprintf("0x%016x", int64(v)) -} - -// encode encodes the Int64Value into an eventstream binary value -// representation. -func (v Int64Value) encode(w io.Writer) error { - raw := rawValue{ - Type: v.valueType(), - } - return raw.encodeScalar(w, v) -} - -func (v *Int64Value) decode(r io.Reader) error { - n, err := decodeUint64(r) - if err != nil { - return err - } - - *v = Int64Value(n) - return nil -} - -// An BytesValue provides eventstream encoding, and representation of a Go -// byte slice. -type BytesValue []byte - -// Get returns the underlying value. -func (v BytesValue) Get() interface{} { - return []byte(v) -} - -// valueType returns the EventStream header value type value. -func (BytesValue) valueType() valueType { - return bytesValueType -} - -func (v BytesValue) String() string { - return base64.StdEncoding.EncodeToString([]byte(v)) -} - -// encode encodes the BytesValue into an eventstream binary value -// representation. -func (v BytesValue) encode(w io.Writer) error { - raw := rawValue{ - Type: v.valueType(), - } - - return raw.encodeBytes(w, []byte(v)) -} - -func (v *BytesValue) decode(r io.Reader) error { - buf, err := decodeBytesValue(r) - if err != nil { - return err - } - - *v = BytesValue(buf) - return nil -} - -// An StringValue provides eventstream encoding, and representation of a Go -// string. -type StringValue string - -// Get returns the underlying value. -func (v StringValue) Get() interface{} { - return string(v) -} - -// valueType returns the EventStream header value type value. -func (StringValue) valueType() valueType { - return stringValueType -} - -func (v StringValue) String() string { - return string(v) -} - -// encode encodes the StringValue into an eventstream binary value -// representation. -func (v StringValue) encode(w io.Writer) error { - raw := rawValue{ - Type: v.valueType(), - } - - return raw.encodeString(w, string(v)) -} - -func (v *StringValue) decode(r io.Reader) error { - s, err := decodeStringValue(r) - if err != nil { - return err - } - - *v = StringValue(s) - return nil -} - -// An TimestampValue provides eventstream encoding, and representation of a Go -// timestamp. -type TimestampValue time.Time - -// Get returns the underlying value. -func (v TimestampValue) Get() interface{} { - return time.Time(v) -} - -// valueType returns the EventStream header value type value. -func (TimestampValue) valueType() valueType { - return timestampValueType -} - -func (v TimestampValue) epochMilli() int64 { - nano := time.Time(v).UnixNano() - msec := nano / int64(time.Millisecond) - return msec -} - -func (v TimestampValue) String() string { - msec := v.epochMilli() - return strconv.FormatInt(msec, 10) -} - -// encode encodes the TimestampValue into an eventstream binary value -// representation. -func (v TimestampValue) encode(w io.Writer) error { - raw := rawValue{ - Type: v.valueType(), - } - - msec := v.epochMilli() - return raw.encodeScalar(w, msec) -} - -func (v *TimestampValue) decode(r io.Reader) error { - n, err := decodeUint64(r) - if err != nil { - return err - } - - *v = TimestampValue(timeFromEpochMilli(int64(n))) - return nil -} - -// MarshalJSON implements the json.Marshaler interface -func (v TimestampValue) MarshalJSON() ([]byte, error) { - return []byte(v.String()), nil -} - -func timeFromEpochMilli(t int64) time.Time { - secs := t / 1e3 - msec := t % 1e3 - return time.Unix(secs, msec*int64(time.Millisecond)).UTC() -} - -// An UUIDValue provides eventstream encoding, and representation of a UUID -// value. -type UUIDValue [16]byte - -// Get returns the underlying value. -func (v UUIDValue) Get() interface{} { - return v[:] -} - -// valueType returns the EventStream header value type value. -func (UUIDValue) valueType() valueType { - return uuidValueType -} - -func (v UUIDValue) String() string { - return fmt.Sprintf(`%X-%X-%X-%X-%X`, v[0:4], v[4:6], v[6:8], v[8:10], v[10:]) -} - -// encode encodes the UUIDValue into an eventstream binary value -// representation. -func (v UUIDValue) encode(w io.Writer) error { - raw := rawValue{ - Type: v.valueType(), - } - - return raw.encodeFixedSlice(w, v[:]) -} - -func (v *UUIDValue) decode(r io.Reader) error { - tv := (*v)[:] - return decodeFixedBytesValue(r, tv) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go deleted file mode 100644 index f7427da03..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go +++ /dev/null @@ -1,117 +0,0 @@ -package eventstream - -import ( - "bytes" - "encoding/binary" - "hash/crc32" -) - -const preludeLen = 8 -const preludeCRCLen = 4 -const msgCRCLen = 4 -const minMsgLen = preludeLen + preludeCRCLen + msgCRCLen -const maxPayloadLen = 1024 * 1024 * 16 // 16MB -const maxHeadersLen = 1024 * 128 // 128KB -const maxMsgLen = minMsgLen + maxHeadersLen + maxPayloadLen - -var crc32IEEETable = crc32.MakeTable(crc32.IEEE) - -// A Message provides the eventstream message representation. -type Message struct { - Headers Headers - Payload []byte -} - -func (m *Message) rawMessage() (rawMessage, error) { - var raw rawMessage - - if len(m.Headers) > 0 { - var headers bytes.Buffer - if err := EncodeHeaders(&headers, m.Headers); err != nil { - return rawMessage{}, err - } - raw.Headers = headers.Bytes() - raw.HeadersLen = uint32(len(raw.Headers)) - } - - raw.Length = raw.HeadersLen + uint32(len(m.Payload)) + minMsgLen - - hash := crc32.New(crc32IEEETable) - binaryWriteFields(hash, binary.BigEndian, raw.Length, raw.HeadersLen) - raw.PreludeCRC = hash.Sum32() - - binaryWriteFields(hash, binary.BigEndian, raw.PreludeCRC) - - if raw.HeadersLen > 0 { - hash.Write(raw.Headers) - } - - // Read payload bytes and update hash for it as well. - if len(m.Payload) > 0 { - raw.Payload = m.Payload - hash.Write(raw.Payload) - } - - raw.CRC = hash.Sum32() - - return raw, nil -} - -// Clone returns a deep copy of the message. -func (m Message) Clone() Message { - var payload []byte - if m.Payload != nil { - payload = make([]byte, len(m.Payload)) - copy(payload, m.Payload) - } - - return Message{ - Headers: m.Headers.Clone(), - Payload: payload, - } -} - -type messagePrelude struct { - Length uint32 - HeadersLen uint32 - PreludeCRC uint32 -} - -func (p messagePrelude) PayloadLen() uint32 { - return p.Length - p.HeadersLen - minMsgLen -} - -func (p messagePrelude) ValidateLens() error { - if p.Length == 0 || p.Length > maxMsgLen { - return LengthError{ - Part: "message prelude", - Want: maxMsgLen, - Have: int(p.Length), - } - } - if p.HeadersLen > maxHeadersLen { - return LengthError{ - Part: "message headers", - Want: maxHeadersLen, - Have: int(p.HeadersLen), - } - } - if payloadLen := p.PayloadLen(); payloadLen > maxPayloadLen { - return LengthError{ - Part: "message payload", - Want: maxPayloadLen, - Have: int(payloadLen), - } - } - - return nil -} - -type rawMessage struct { - messagePrelude - - Headers []byte - Payload []byte - - CRC uint32 -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/host.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/host.go deleted file mode 100644 index 1f1d27aea..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/host.go +++ /dev/null @@ -1,104 +0,0 @@ -package protocol - -import ( - "github.com/aws/aws-sdk-go/aws/request" - "net" - "strconv" - "strings" -) - -// ValidateEndpointHostHandler is a request handler that will validate the -// request endpoint's hosts is a valid RFC 3986 host. -var ValidateEndpointHostHandler = request.NamedHandler{ - Name: "awssdk.protocol.ValidateEndpointHostHandler", - Fn: func(r *request.Request) { - err := ValidateEndpointHost(r.Operation.Name, r.HTTPRequest.URL.Host) - if err != nil { - r.Error = err - } - }, -} - -// ValidateEndpointHost validates that the host string passed in is a valid RFC -// 3986 host. Returns error if the host is not valid. -func ValidateEndpointHost(opName, host string) error { - paramErrs := request.ErrInvalidParams{Context: opName} - - var hostname string - var port string - var err error - - if strings.Contains(host, ":") { - hostname, port, err = net.SplitHostPort(host) - - if err != nil { - paramErrs.Add(request.NewErrParamFormat("endpoint", err.Error(), host)) - } - - if !ValidPortNumber(port) { - paramErrs.Add(request.NewErrParamFormat("endpoint port number", "[0-65535]", port)) - } - } else { - hostname = host - } - - labels := strings.Split(hostname, ".") - for i, label := range labels { - if i == len(labels)-1 && len(label) == 0 { - // Allow trailing dot for FQDN hosts. - continue - } - - if !ValidHostLabel(label) { - paramErrs.Add(request.NewErrParamFormat( - "endpoint host label", "[a-zA-Z0-9-]{1,63}", label)) - } - } - - if len(hostname) == 0 { - paramErrs.Add(request.NewErrParamMinLen("endpoint host", 1)) - } - - if len(hostname) > 255 { - paramErrs.Add(request.NewErrParamMaxLen( - "endpoint host", 255, host, - )) - } - - if paramErrs.Len() > 0 { - return paramErrs - } - return nil -} - -// ValidHostLabel returns if the label is a valid RFC 3986 host label. -func ValidHostLabel(label string) bool { - if l := len(label); l == 0 || l > 63 { - return false - } - for _, r := range label { - switch { - case r >= '0' && r <= '9': - case r >= 'A' && r <= 'Z': - case r >= 'a' && r <= 'z': - case r == '-': - default: - return false - } - } - - return true -} - -// ValidPortNumber return if the port is valid RFC 3986 port -func ValidPortNumber(port string) bool { - i, err := strconv.Atoi(port) - if err != nil { - return false - } - - if i < 0 || i > 65535 { - return false - } - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/host_prefix.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/host_prefix.go deleted file mode 100644 index 915b0fcaf..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/host_prefix.go +++ /dev/null @@ -1,54 +0,0 @@ -package protocol - -import ( - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -// HostPrefixHandlerName is the handler name for the host prefix request -// handler. -const HostPrefixHandlerName = "awssdk.endpoint.HostPrefixHandler" - -// NewHostPrefixHandler constructs a build handler -func NewHostPrefixHandler(prefix string, labelsFn func() map[string]string) request.NamedHandler { - builder := HostPrefixBuilder{ - Prefix: prefix, - LabelsFn: labelsFn, - } - - return request.NamedHandler{ - Name: HostPrefixHandlerName, - Fn: builder.Build, - } -} - -// HostPrefixBuilder provides the request handler to expand and prepend -// the host prefix into the operation's request endpoint host. -type HostPrefixBuilder struct { - Prefix string - LabelsFn func() map[string]string -} - -// Build updates the passed in Request with the HostPrefix template expanded. -func (h HostPrefixBuilder) Build(r *request.Request) { - if aws.BoolValue(r.Config.DisableEndpointHostPrefix) { - return - } - - var labels map[string]string - if h.LabelsFn != nil { - labels = h.LabelsFn() - } - - prefix := h.Prefix - for name, value := range labels { - prefix = strings.Replace(prefix, "{"+name+"}", value, -1) - } - - r.HTTPRequest.URL.Host = prefix + r.HTTPRequest.URL.Host - if len(r.HTTPRequest.Host) > 0 { - r.HTTPRequest.Host = prefix + r.HTTPRequest.Host - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go deleted file mode 100644 index 53831dff9..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go +++ /dev/null @@ -1,75 +0,0 @@ -package protocol - -import ( - "crypto/rand" - "fmt" - "reflect" -) - -// RandReader is the random reader the protocol package will use to read -// random bytes from. This is exported for testing, and should not be used. -var RandReader = rand.Reader - -const idempotencyTokenFillTag = `idempotencyToken` - -// CanSetIdempotencyToken returns true if the struct field should be -// automatically populated with a Idempotency token. -// -// Only *string and string type fields that are tagged with idempotencyToken -// which are not already set can be auto filled. -func CanSetIdempotencyToken(v reflect.Value, f reflect.StructField) bool { - switch u := v.Interface().(type) { - // To auto fill an Idempotency token the field must be a string, - // tagged for auto fill, and have a zero value. - case *string: - return u == nil && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 - case string: - return len(u) == 0 && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 - } - - return false -} - -// GetIdempotencyToken returns a randomly generated idempotency token. -func GetIdempotencyToken() string { - b := make([]byte, 16) - RandReader.Read(b) - - return UUIDVersion4(b) -} - -// SetIdempotencyToken will set the value provided with a Idempotency Token. -// Given that the value can be set. Will panic if value is not setable. -func SetIdempotencyToken(v reflect.Value) { - if v.Kind() == reflect.Ptr { - if v.IsNil() && v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - v = reflect.Indirect(v) - - if !v.CanSet() { - panic(fmt.Sprintf("unable to set idempotnecy token %v", v)) - } - - b := make([]byte, 16) - _, err := rand.Read(b) - if err != nil { - // TODO handle error - return - } - - v.Set(reflect.ValueOf(UUIDVersion4(b))) -} - -// UUIDVersion4 returns a Version 4 random UUID from the byte slice provided -func UUIDVersion4(u []byte) string { - // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 - // 13th character is "4" - u[6] = (u[6] | 0x40) & 0x4F - // 17th character is "8", "9", "a", or "b" - u[8] = (u[8] | 0x80) & 0xBF - - return fmt.Sprintf(`%X-%X-%X-%X-%X`, u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go deleted file mode 100644 index 12e814ddf..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go +++ /dev/null @@ -1,309 +0,0 @@ -// Package jsonutil provides JSON serialization of AWS requests and responses. -package jsonutil - -import ( - "bytes" - "encoding/base64" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/private/protocol" -) - -const ( - floatNaN = "NaN" - floatInf = "Infinity" - floatNegInf = "-Infinity" -) - -var timeType = reflect.ValueOf(time.Time{}).Type() -var byteSliceType = reflect.ValueOf([]byte{}).Type() - -// BuildJSON builds a JSON string for a given object v. -func BuildJSON(v interface{}) ([]byte, error) { - var buf bytes.Buffer - - err := buildAny(reflect.ValueOf(v), &buf, "") - return buf.Bytes(), err -} - -func buildAny(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - origVal := value - value = reflect.Indirect(value) - if !value.IsValid() { - return nil - } - - vtype := value.Type() - - t := tag.Get("type") - if t == "" { - switch vtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if value.Type() != timeType { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := value.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - // cannot be a JSONValue map - if _, ok := value.Interface().(aws.JSONValue); !ok { - t = "map" - } - } - } - - switch t { - case "structure": - if field, ok := vtype.FieldByName("_"); ok { - tag = field.Tag - } - return buildStruct(value, buf, tag) - case "list": - return buildList(value, buf, tag) - case "map": - return buildMap(value, buf, tag) - default: - return buildScalar(origVal, buf, tag) - } -} - -func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - if !value.IsValid() { - return nil - } - - // unwrap payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := value.Type().FieldByName(payload) - tag = field.Tag - value = elemOf(value.FieldByName(payload)) - if !value.IsValid() && tag.Get("type") != "structure" { - return nil - } - } - - buf.WriteByte('{') - defer buf.WriteString("}") - - if !value.IsValid() { - return nil - } - - t := value.Type() - first := true - for i := 0; i < t.NumField(); i++ { - member := value.Field(i) - - // This allocates the most memory. - // Additionally, we cannot skip nil fields due to - // idempotency auto filling. - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("json") == "-" { - continue - } - if field.Tag.Get("location") != "" { - continue // ignore non-body elements - } - if field.Tag.Get("ignore") != "" { - continue - } - - if protocol.CanSetIdempotencyToken(member, field) { - token := protocol.GetIdempotencyToken() - member = reflect.ValueOf(&token) - } - - if (member.Kind() == reflect.Ptr || member.Kind() == reflect.Slice || member.Kind() == reflect.Map) && member.IsNil() { - continue // ignore unset fields - } - - if first { - first = false - } else { - buf.WriteByte(',') - } - - // figure out what this field is called - name := field.Name - if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - writeString(name, buf) - buf.WriteString(`:`) - - err := buildAny(member, buf, field.Tag) - if err != nil { - return err - } - - } - - return nil -} - -func buildList(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - buf.WriteString("[") - - for i := 0; i < value.Len(); i++ { - buildAny(value.Index(i), buf, "") - - if i < value.Len()-1 { - buf.WriteString(",") - } - } - - buf.WriteString("]") - - return nil -} - -type sortedValues []reflect.Value - -func (sv sortedValues) Len() int { return len(sv) } -func (sv sortedValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv sortedValues) Less(i, j int) bool { return sv[i].String() < sv[j].String() } - -func buildMap(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - buf.WriteString("{") - - sv := sortedValues(value.MapKeys()) - sort.Sort(sv) - - for i, k := range sv { - if i > 0 { - buf.WriteByte(',') - } - - writeString(k.String(), buf) - buf.WriteString(`:`) - - buildAny(value.MapIndex(k), buf, "") - } - - buf.WriteString("}") - - return nil -} - -func buildScalar(v reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - // prevents allocation on the heap. - scratch := [64]byte{} - switch value := reflect.Indirect(v); value.Kind() { - case reflect.String: - writeString(value.String(), buf) - case reflect.Bool: - if value.Bool() { - buf.WriteString("true") - } else { - buf.WriteString("false") - } - case reflect.Int64: - buf.Write(strconv.AppendInt(scratch[:0], value.Int(), 10)) - case reflect.Float64: - f := value.Float() - switch { - case math.IsNaN(f): - writeString(floatNaN, buf) - case math.IsInf(f, 1): - writeString(floatInf, buf) - case math.IsInf(f, -1): - writeString(floatNegInf, buf) - default: - buf.Write(strconv.AppendFloat(scratch[:0], f, 'f', -1, 64)) - } - default: - switch converted := value.Interface().(type) { - case time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.UnixTimeFormatName - } - - ts := protocol.FormatTime(format, converted) - if format != protocol.UnixTimeFormatName { - ts = `"` + ts + `"` - } - - buf.WriteString(ts) - case []byte: - if !value.IsNil() { - buf.WriteByte('"') - if len(converted) < 1024 { - // for small buffers, using Encode directly is much faster. - dst := make([]byte, base64.StdEncoding.EncodedLen(len(converted))) - base64.StdEncoding.Encode(dst, converted) - buf.Write(dst) - } else { - // for large buffers, avoid unnecessary extra temporary - // buffer space. - enc := base64.NewEncoder(base64.StdEncoding, buf) - enc.Write(converted) - enc.Close() - } - buf.WriteByte('"') - } - case aws.JSONValue: - str, err := protocol.EncodeJSONValue(converted, protocol.QuotedEscape) - if err != nil { - return fmt.Errorf("unable to encode JSONValue, %v", err) - } - buf.WriteString(str) - default: - return fmt.Errorf("unsupported JSON value %v (%s)", value.Interface(), value.Type()) - } - } - return nil -} - -var hex = "0123456789abcdef" - -func writeString(s string, buf *bytes.Buffer) { - buf.WriteByte('"') - for i := 0; i < len(s); i++ { - if s[i] == '"' { - buf.WriteString(`\"`) - } else if s[i] == '\\' { - buf.WriteString(`\\`) - } else if s[i] == '\b' { - buf.WriteString(`\b`) - } else if s[i] == '\f' { - buf.WriteString(`\f`) - } else if s[i] == '\r' { - buf.WriteString(`\r`) - } else if s[i] == '\t' { - buf.WriteString(`\t`) - } else if s[i] == '\n' { - buf.WriteString(`\n`) - } else if s[i] < 32 { - buf.WriteString("\\u00") - buf.WriteByte(hex[s[i]>>4]) - buf.WriteByte(hex[s[i]&0xF]) - } else { - buf.WriteByte(s[i]) - } - } - buf.WriteByte('"') -} - -// Returns the reflection element of a value, if it is a pointer. -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go deleted file mode 100644 index f9334879b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go +++ /dev/null @@ -1,317 +0,0 @@ -package jsonutil - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "math" - "math/big" - "reflect" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/private/protocol" -) - -var millisecondsFloat = new(big.Float).SetInt64(1e3) - -// UnmarshalJSONError unmarshal's the reader's JSON document into the passed in -// type. The value to unmarshal the json document into must be a pointer to the -// type. -func UnmarshalJSONError(v interface{}, stream io.Reader) error { - var errBuf bytes.Buffer - body := io.TeeReader(stream, &errBuf) - - err := json.NewDecoder(body).Decode(v) - if err != nil { - msg := "failed decoding error message" - if err == io.EOF { - msg = "error message missing" - err = nil - } - return awserr.NewUnmarshalError(err, msg, errBuf.Bytes()) - } - - return nil -} - -// UnmarshalJSON reads a stream and unmarshals the results in object v. -func UnmarshalJSON(v interface{}, stream io.Reader) error { - var out interface{} - - decoder := json.NewDecoder(stream) - decoder.UseNumber() - err := decoder.Decode(&out) - if err == io.EOF { - return nil - } else if err != nil { - return err - } - - return unmarshaler{}.unmarshalAny(reflect.ValueOf(v), out, "") -} - -// UnmarshalJSONCaseInsensitive reads a stream and unmarshals the result into the -// object v. Ignores casing for structure members. -func UnmarshalJSONCaseInsensitive(v interface{}, stream io.Reader) error { - var out interface{} - - decoder := json.NewDecoder(stream) - decoder.UseNumber() - err := decoder.Decode(&out) - if err == io.EOF { - return nil - } else if err != nil { - return err - } - - return unmarshaler{ - caseInsensitive: true, - }.unmarshalAny(reflect.ValueOf(v), out, "") -} - -type unmarshaler struct { - caseInsensitive bool -} - -func (u unmarshaler) unmarshalAny(value reflect.Value, data interface{}, tag reflect.StructTag) error { - vtype := value.Type() - if vtype.Kind() == reflect.Ptr { - vtype = vtype.Elem() // check kind of actual element type - } - - t := tag.Get("type") - if t == "" { - switch vtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if _, ok := value.Interface().(*time.Time); !ok { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := value.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - // cannot be a JSONValue map - if _, ok := value.Interface().(aws.JSONValue); !ok { - t = "map" - } - } - } - - switch t { - case "structure": - if field, ok := vtype.FieldByName("_"); ok { - tag = field.Tag - } - return u.unmarshalStruct(value, data, tag) - case "list": - return u.unmarshalList(value, data, tag) - case "map": - return u.unmarshalMap(value, data, tag) - default: - return u.unmarshalScalar(value, data, tag) - } -} - -func (u unmarshaler) unmarshalStruct(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - mapData, ok := data.(map[string]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a structure (%#v)", data) - } - - t := value.Type() - if value.Kind() == reflect.Ptr { - if value.IsNil() { // create the structure if it's nil - s := reflect.New(value.Type().Elem()) - value.Set(s) - value = s - } - - value = value.Elem() - t = t.Elem() - } - - // unwrap any payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := t.FieldByName(payload) - return u.unmarshalAny(value.FieldByName(payload), data, field.Tag) - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if field.PkgPath != "" { - continue // ignore unexported fields - } - - // figure out what this field is called - name := field.Name - if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - if u.caseInsensitive { - if _, ok := mapData[name]; !ok { - // Fallback to uncased name search if the exact name didn't match. - for kn, v := range mapData { - if strings.EqualFold(kn, name) { - mapData[name] = v - } - } - } - } - - member := value.FieldByIndex(field.Index) - err := u.unmarshalAny(member, mapData[name], field.Tag) - if err != nil { - return err - } - } - return nil -} - -func (u unmarshaler) unmarshalList(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - listData, ok := data.([]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a list (%#v)", data) - } - - if value.IsNil() { - l := len(listData) - value.Set(reflect.MakeSlice(value.Type(), l, l)) - } - - for i, c := range listData { - err := u.unmarshalAny(value.Index(i), c, "") - if err != nil { - return err - } - } - - return nil -} - -func (u unmarshaler) unmarshalMap(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - mapData, ok := data.(map[string]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a map (%#v)", data) - } - - if value.IsNil() { - value.Set(reflect.MakeMap(value.Type())) - } - - for k, v := range mapData { - kvalue := reflect.ValueOf(k) - vvalue := reflect.New(value.Type().Elem()).Elem() - - u.unmarshalAny(vvalue, v, "") - value.SetMapIndex(kvalue, vvalue) - } - - return nil -} - -func (u unmarshaler) unmarshalScalar(value reflect.Value, data interface{}, tag reflect.StructTag) error { - - switch d := data.(type) { - case nil: - return nil // nothing to do here - case string: - switch value.Interface().(type) { - case *string: - value.Set(reflect.ValueOf(&d)) - case []byte: - b, err := base64.StdEncoding.DecodeString(d) - if err != nil { - return err - } - value.Set(reflect.ValueOf(b)) - case *time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.ISO8601TimeFormatName - } - - t, err := protocol.ParseTime(format, d) - if err != nil { - return err - } - value.Set(reflect.ValueOf(&t)) - case aws.JSONValue: - // No need to use escaping as the value is a non-quoted string. - v, err := protocol.DecodeJSONValue(d, protocol.NoEscape) - if err != nil { - return err - } - value.Set(reflect.ValueOf(v)) - case *float64: - // These are regular strings when parsed by encoding/json's unmarshaler. - switch { - case strings.EqualFold(d, floatNaN): - value.Set(reflect.ValueOf(aws.Float64(math.NaN()))) - case strings.EqualFold(d, floatInf): - value.Set(reflect.ValueOf(aws.Float64(math.Inf(1)))) - case strings.EqualFold(d, floatNegInf): - value.Set(reflect.ValueOf(aws.Float64(math.Inf(-1)))) - default: - return fmt.Errorf("unknown JSON number value: %s", d) - } - default: - return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) - } - case json.Number: - switch value.Interface().(type) { - case *int64: - // Retain the old behavior where we would just truncate the float64 - // calling d.Int64() here could cause an invalid syntax error due to the usage of strconv.ParseInt - f, err := d.Float64() - if err != nil { - return err - } - di := int64(f) - value.Set(reflect.ValueOf(&di)) - case *float64: - f, err := d.Float64() - if err != nil { - return err - } - value.Set(reflect.ValueOf(&f)) - case *time.Time: - float, ok := new(big.Float).SetString(d.String()) - if !ok { - return fmt.Errorf("unsupported float time representation: %v", d.String()) - } - float = float.Mul(float, millisecondsFloat) - ms, _ := float.Int64() - t := time.Unix(0, ms*1e6).UTC() - value.Set(reflect.ValueOf(&t)) - default: - return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) - } - case bool: - switch value.Interface().(type) { - case *bool: - value.Set(reflect.ValueOf(&d)) - default: - return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) - } - default: - return fmt.Errorf("unsupported JSON value (%v)", data) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go deleted file mode 100644 index d9aa27114..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go +++ /dev/null @@ -1,87 +0,0 @@ -// Package jsonrpc provides JSON RPC utilities for serialization of AWS -// requests and responses. -package jsonrpc - -//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/input/json.json build_test.go -//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/output/json.json unmarshal_test.go - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -var emptyJSON = []byte("{}") - -// BuildHandler is a named request handler for building jsonrpc protocol -// requests -var BuildHandler = request.NamedHandler{ - Name: "awssdk.jsonrpc.Build", - Fn: Build, -} - -// UnmarshalHandler is a named request handler for unmarshaling jsonrpc -// protocol requests -var UnmarshalHandler = request.NamedHandler{ - Name: "awssdk.jsonrpc.Unmarshal", - Fn: Unmarshal, -} - -// UnmarshalMetaHandler is a named request handler for unmarshaling jsonrpc -// protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{ - Name: "awssdk.jsonrpc.UnmarshalMeta", - Fn: UnmarshalMeta, -} - -// Build builds a JSON payload for a JSON RPC request. -func Build(req *request.Request) { - var buf []byte - var err error - if req.ParamsFilled() { - buf, err = jsonutil.BuildJSON(req.Params) - if err != nil { - req.Error = awserr.New(request.ErrCodeSerialization, "failed encoding JSON RPC request", err) - return - } - } else { - buf = emptyJSON - } - - // Always serialize the body, don't suppress it. - req.SetBufferBody(buf) - - if req.ClientInfo.TargetPrefix != "" { - target := req.ClientInfo.TargetPrefix + "." + req.Operation.Name - req.HTTPRequest.Header.Add("X-Amz-Target", target) - } - - // Only set the content type if one is not already specified and an - // JSONVersion is specified. - if ct, v := req.HTTPRequest.Header.Get("Content-Type"), req.ClientInfo.JSONVersion; len(ct) == 0 && len(v) != 0 { - jsonVersion := req.ClientInfo.JSONVersion - req.HTTPRequest.Header.Set("Content-Type", "application/x-amz-json-"+jsonVersion) - } -} - -// Unmarshal unmarshals a response for a JSON RPC service. -func Unmarshal(req *request.Request) { - defer req.HTTPResponse.Body.Close() - if req.DataFilled() { - err := jsonutil.UnmarshalJSON(req.Data, req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, "failed decoding JSON RPC response", err), - req.HTTPResponse.StatusCode, - req.RequestID, - ) - } - } - return -} - -// UnmarshalMeta unmarshals headers from a response for a JSON RPC service. -func UnmarshalMeta(req *request.Request) { - rest.UnmarshalMeta(req) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/unmarshal_error.go deleted file mode 100644 index 9c1ccde54..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/unmarshal_error.go +++ /dev/null @@ -1,160 +0,0 @@ -package jsonrpc - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "strings" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" -) - -const ( - awsQueryError = "x-amzn-query-error" - // A valid header example - "x-amzn-query-error": ";" - awsQueryErrorPartsCount = 2 -) - -// UnmarshalTypedError provides unmarshaling errors API response errors -// for both typed and untyped errors. -type UnmarshalTypedError struct { - exceptions map[string]func(protocol.ResponseMetadata) error - queryExceptions map[string]func(protocol.ResponseMetadata, string) error -} - -// NewUnmarshalTypedError returns an UnmarshalTypedError initialized for the -// set of exception names to the error unmarshalers -func NewUnmarshalTypedError(exceptions map[string]func(protocol.ResponseMetadata) error) *UnmarshalTypedError { - return &UnmarshalTypedError{ - exceptions: exceptions, - queryExceptions: map[string]func(protocol.ResponseMetadata, string) error{}, - } -} - -// NewUnmarshalTypedErrorWithOptions works similar to NewUnmarshalTypedError applying options to the UnmarshalTypedError -// before returning it -func NewUnmarshalTypedErrorWithOptions(exceptions map[string]func(protocol.ResponseMetadata) error, optFns ...func(*UnmarshalTypedError)) *UnmarshalTypedError { - unmarshaledError := NewUnmarshalTypedError(exceptions) - for _, fn := range optFns { - fn(unmarshaledError) - } - return unmarshaledError -} - -// WithQueryCompatibility is a helper function to construct a functional option for use with NewUnmarshalTypedErrorWithOptions. -// The queryExceptions given act as an override for unmarshalling errors when query compatible error codes are found. -// See also [awsQueryCompatible trait] -// -// [awsQueryCompatible trait]: https://smithy.io/2.0/aws/protocols/aws-query-protocol.html#aws-protocols-awsquerycompatible-trait -func WithQueryCompatibility(queryExceptions map[string]func(protocol.ResponseMetadata, string) error) func(*UnmarshalTypedError) { - return func(typedError *UnmarshalTypedError) { - typedError.queryExceptions = queryExceptions - } -} - -// UnmarshalError attempts to unmarshal the HTTP response error as a known -// error type. If unable to unmarshal the error type, the generic SDK error -// type will be used. -func (u *UnmarshalTypedError) UnmarshalError( - resp *http.Response, - respMeta protocol.ResponseMetadata, -) (error, error) { - - var buf bytes.Buffer - var jsonErr jsonErrorResponse - teeReader := io.TeeReader(resp.Body, &buf) - err := jsonutil.UnmarshalJSONError(&jsonErr, teeReader) - if err != nil { - return nil, err - } - body := ioutil.NopCloser(&buf) - - // Code may be separated by hash(#), with the last element being the code - // used by the SDK. - codeParts := strings.SplitN(jsonErr.Code, "#", 2) - code := codeParts[len(codeParts)-1] - msg := jsonErr.Message - - queryCodeParts := queryCodeParts(resp, u) - - if fn, ok := u.exceptions[code]; ok { - // If query-compatible exceptions are found and query-error-header is found, - // then use associated constructor to get exception with query error code. - // - // If exception code is known, use associated constructor to get a value - // for the exception that the JSON body can be unmarshaled into. - var v error - queryErrFn, queryExceptionsFound := u.queryExceptions[code] - if len(queryCodeParts) == awsQueryErrorPartsCount && queryExceptionsFound { - v = queryErrFn(respMeta, queryCodeParts[0]) - } else { - v = fn(respMeta) - } - err := jsonutil.UnmarshalJSONCaseInsensitive(v, body) - if err != nil { - return nil, err - } - return v, nil - } - - if len(queryCodeParts) == awsQueryErrorPartsCount && len(u.queryExceptions) > 0 { - code = queryCodeParts[0] - } - - // fallback to unmodeled generic exceptions - return awserr.NewRequestFailure( - awserr.New(code, msg, nil), - respMeta.StatusCode, - respMeta.RequestID, - ), nil -} - -// A valid header example - "x-amzn-query-error": ";" -func queryCodeParts(resp *http.Response, u *UnmarshalTypedError) []string { - queryCodeHeader := resp.Header.Get(awsQueryError) - var queryCodeParts []string - if queryCodeHeader != "" && len(u.queryExceptions) > 0 { - queryCodeParts = strings.Split(queryCodeHeader, ";") - } - return queryCodeParts -} - -// UnmarshalErrorHandler is a named request handler for unmarshaling jsonrpc -// protocol request errors -var UnmarshalErrorHandler = request.NamedHandler{ - Name: "awssdk.jsonrpc.UnmarshalError", - Fn: UnmarshalError, -} - -// UnmarshalError unmarshals an error response for a JSON RPC service. -func UnmarshalError(req *request.Request) { - defer req.HTTPResponse.Body.Close() - - var jsonErr jsonErrorResponse - err := jsonutil.UnmarshalJSONError(&jsonErr, req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, - "failed to unmarshal error message", err), - req.HTTPResponse.StatusCode, - req.RequestID, - ) - return - } - - codes := strings.SplitN(jsonErr.Code, "#", 2) - req.Error = awserr.NewRequestFailure( - awserr.New(codes[len(codes)-1], jsonErr.Message, nil), - req.HTTPResponse.StatusCode, - req.RequestID, - ) -} - -type jsonErrorResponse struct { - Code string `json:"__type"` - Message string `json:"message"` -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go deleted file mode 100644 index 776d11018..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go +++ /dev/null @@ -1,76 +0,0 @@ -package protocol - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "strconv" - - "github.com/aws/aws-sdk-go/aws" -) - -// EscapeMode is the mode that should be use for escaping a value -type EscapeMode uint - -// The modes for escaping a value before it is marshaled, and unmarshaled. -const ( - NoEscape EscapeMode = iota - Base64Escape - QuotedEscape -) - -// EncodeJSONValue marshals the value into a JSON string, and optionally base64 -// encodes the string before returning it. -// -// Will panic if the escape mode is unknown. -func EncodeJSONValue(v aws.JSONValue, escape EscapeMode) (string, error) { - b, err := json.Marshal(v) - if err != nil { - return "", err - } - - switch escape { - case NoEscape: - return string(b), nil - case Base64Escape: - return base64.StdEncoding.EncodeToString(b), nil - case QuotedEscape: - return strconv.Quote(string(b)), nil - } - - panic(fmt.Sprintf("EncodeJSONValue called with unknown EscapeMode, %v", escape)) -} - -// DecodeJSONValue will attempt to decode the string input as a JSONValue. -// Optionally decoding base64 the value first before JSON unmarshaling. -// -// Will panic if the escape mode is unknown. -func DecodeJSONValue(v string, escape EscapeMode) (aws.JSONValue, error) { - var b []byte - var err error - - switch escape { - case NoEscape: - b = []byte(v) - case Base64Escape: - b, err = base64.StdEncoding.DecodeString(v) - case QuotedEscape: - var u string - u, err = strconv.Unquote(v) - b = []byte(u) - default: - panic(fmt.Sprintf("DecodeJSONValue called with unknown EscapeMode, %v", escape)) - } - - if err != nil { - return nil, err - } - - m := aws.JSONValue{} - err = json.Unmarshal(b, &m) - if err != nil { - return nil, err - } - - return m, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go deleted file mode 100644 index 0ea0647a5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/payload.go +++ /dev/null @@ -1,81 +0,0 @@ -package protocol - -import ( - "io" - "io/ioutil" - "net/http" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -// PayloadUnmarshaler provides the interface for unmarshaling a payload's -// reader into a SDK shape. -type PayloadUnmarshaler interface { - UnmarshalPayload(io.Reader, interface{}) error -} - -// HandlerPayloadUnmarshal implements the PayloadUnmarshaler from a -// HandlerList. This provides the support for unmarshaling a payload reader to -// a shape without needing a SDK request first. -type HandlerPayloadUnmarshal struct { - Unmarshalers request.HandlerList -} - -// UnmarshalPayload unmarshals the io.Reader payload into the SDK shape using -// the Unmarshalers HandlerList provided. Returns an error if unable -// unmarshaling fails. -func (h HandlerPayloadUnmarshal) UnmarshalPayload(r io.Reader, v interface{}) error { - req := &request.Request{ - HTTPRequest: &http.Request{}, - HTTPResponse: &http.Response{ - StatusCode: 200, - Header: http.Header{}, - Body: ioutil.NopCloser(r), - }, - Data: v, - } - - h.Unmarshalers.Run(req) - - return req.Error -} - -// PayloadMarshaler provides the interface for marshaling a SDK shape into and -// io.Writer. -type PayloadMarshaler interface { - MarshalPayload(io.Writer, interface{}) error -} - -// HandlerPayloadMarshal implements the PayloadMarshaler from a HandlerList. -// This provides support for marshaling a SDK shape into an io.Writer without -// needing a SDK request first. -type HandlerPayloadMarshal struct { - Marshalers request.HandlerList -} - -// MarshalPayload marshals the SDK shape into the io.Writer using the -// Marshalers HandlerList provided. Returns an error if unable if marshal -// fails. -func (h HandlerPayloadMarshal) MarshalPayload(w io.Writer, v interface{}) error { - req := request.New( - aws.Config{}, - metadata.ClientInfo{}, - request.Handlers{}, - nil, - &request.Operation{HTTPMethod: "PUT"}, - v, - nil, - ) - - h.Marshalers.Run(req) - - if req.Error != nil { - return req.Error - } - - io.Copy(w, req.GetBody()) - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol.go deleted file mode 100644 index 9d521dcb9..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/protocol.go +++ /dev/null @@ -1,49 +0,0 @@ -package protocol - -import ( - "fmt" - "strings" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// RequireHTTPMinProtocol request handler is used to enforce that -// the target endpoint supports the given major and minor HTTP protocol version. -type RequireHTTPMinProtocol struct { - Major, Minor int -} - -// Handler will mark the request.Request with an error if the -// target endpoint did not connect with the required HTTP protocol -// major and minor version. -func (p RequireHTTPMinProtocol) Handler(r *request.Request) { - if r.Error != nil || r.HTTPResponse == nil { - return - } - - if !strings.HasPrefix(r.HTTPResponse.Proto, "HTTP") { - r.Error = newMinHTTPProtoError(p.Major, p.Minor, r) - } - - if r.HTTPResponse.ProtoMajor < p.Major || r.HTTPResponse.ProtoMinor < p.Minor { - r.Error = newMinHTTPProtoError(p.Major, p.Minor, r) - } -} - -// ErrCodeMinimumHTTPProtocolError error code is returned when the target endpoint -// did not match the required HTTP major and minor protocol version. -const ErrCodeMinimumHTTPProtocolError = "MinimumHTTPProtocolError" - -func newMinHTTPProtoError(major, minor int, r *request.Request) error { - return awserr.NewRequestFailure( - awserr.New("MinimumHTTPProtocolError", - fmt.Sprintf( - "operation requires minimum HTTP protocol of HTTP/%d.%d, but was %s", - major, minor, r.HTTPResponse.Proto, - ), - nil, - ), - r.HTTPResponse.StatusCode, r.RequestID, - ) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go deleted file mode 100644 index d40346a77..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go +++ /dev/null @@ -1,36 +0,0 @@ -// Package query provides serialization of AWS query requests, and responses. -package query - -//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/input/query.json build_test.go - -import ( - "net/url" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/query/queryutil" -) - -// BuildHandler is a named request handler for building query protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.query.Build", Fn: Build} - -// Build builds a request for an AWS Query service. -func Build(r *request.Request) { - body := url.Values{ - "Action": {r.Operation.Name}, - "Version": {r.ClientInfo.APIVersion}, - } - if err := queryutil.Parse(body, r.Params, false); err != nil { - r.Error = awserr.New(request.ErrCodeSerialization, "failed encoding Query request", err) - return - } - - if !r.IsPresigned() { - r.HTTPRequest.Method = "POST" - r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") - r.SetBufferBody([]byte(body.Encode())) - } else { // This is a pre-signed request - r.HTTPRequest.Method = "GET" - r.HTTPRequest.URL.RawQuery = body.Encode() - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go deleted file mode 100644 index 2ca0b19db..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go +++ /dev/null @@ -1,276 +0,0 @@ -package queryutil - -import ( - "encoding/base64" - "fmt" - "math" - "net/url" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -const ( - floatNaN = "NaN" - floatInf = "Infinity" - floatNegInf = "-Infinity" -) - -// Parse parses an object i and fills a url.Values object. The isEC2 flag -// indicates if this is the EC2 Query sub-protocol. -func Parse(body url.Values, i interface{}, isEC2 bool) error { - q := queryParser{isEC2: isEC2} - return q.parseValue(body, reflect.ValueOf(i), "", "") -} - -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -type queryParser struct { - isEC2 bool -} - -func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - value = elemOf(value) - - // no need to handle zero values - if !value.IsValid() { - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - return q.parseStruct(v, value, prefix) - case "list": - return q.parseList(v, value, prefix, tag) - case "map": - return q.parseMap(v, value, prefix, tag) - default: - return q.parseScalar(v, value, prefix, tag) - } -} - -func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error { - if !value.IsValid() { - return nil - } - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - elemValue := elemOf(value.Field(i)) - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("ignore") != "" { - continue - } - - if protocol.CanSetIdempotencyToken(value.Field(i), field) { - token := protocol.GetIdempotencyToken() - elemValue = reflect.ValueOf(token) - } - - var name string - if q.isEC2 { - name = field.Tag.Get("queryName") - } - if name == "" { - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - if name != "" && q.isEC2 { - name = strings.ToUpper(name[0:1]) + name[1:] - } - } - if name == "" { - name = field.Name - } - - if prefix != "" { - name = prefix + "." + name - } - - if err := q.parseValue(v, elemValue, name, field.Tag); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, and not ec2, generate an empty value - if !value.IsNil() && value.Len() == 0 && !q.isEC2 { - v.Set(prefix, "") - return nil - } - - if _, ok := value.Interface().([]byte); ok { - return q.parseScalar(v, value, prefix, tag) - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - if listName := tag.Get("locationNameList"); listName == "" { - prefix += ".member" - } else { - prefix += "." + listName - } - } - - for i := 0; i < value.Len(); i++ { - slicePrefix := prefix - if slicePrefix == "" { - slicePrefix = strconv.Itoa(i + 1) - } else { - slicePrefix = slicePrefix + "." + strconv.Itoa(i+1) - } - if err := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - prefix += ".entry" - } - - // sort keys for improved serialization consistency. - // this is not strictly necessary for protocol support. - mapKeyValues := value.MapKeys() - mapKeys := map[string]reflect.Value{} - mapKeyNames := make([]string, len(mapKeyValues)) - for i, mapKey := range mapKeyValues { - name := mapKey.String() - mapKeys[name] = mapKey - mapKeyNames[i] = name - } - sort.Strings(mapKeyNames) - - for i, mapKeyName := range mapKeyNames { - mapKey := mapKeys[mapKeyName] - mapValue := value.MapIndex(mapKey) - - kname := tag.Get("locationNameKey") - if kname == "" { - kname = "key" - } - vname := tag.Get("locationNameValue") - if vname == "" { - vname = "value" - } - - // serialize key - var keyName string - if prefix == "" { - keyName = strconv.Itoa(i+1) + "." + kname - } else { - keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname - } - - if err := q.parseValue(v, mapKey, keyName, ""); err != nil { - return err - } - - // serialize value - var valueName string - if prefix == "" { - valueName = strconv.Itoa(i+1) + "." + vname - } else { - valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname - } - - if err := q.parseValue(v, mapValue, valueName, ""); err != nil { - return err - } - } - - return nil -} - -func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error { - switch value := r.Interface().(type) { - case string: - v.Set(name, value) - case []byte: - if !r.IsNil() { - v.Set(name, base64.StdEncoding.EncodeToString(value)) - } - case bool: - v.Set(name, strconv.FormatBool(value)) - case int64: - v.Set(name, strconv.FormatInt(value, 10)) - case int: - v.Set(name, strconv.Itoa(value)) - case float64: - var str string - switch { - case math.IsNaN(value): - str = floatNaN - case math.IsInf(value, 1): - str = floatInf - case math.IsInf(value, -1): - str = floatNegInf - default: - str = strconv.FormatFloat(value, 'f', -1, 64) - } - v.Set(name, str) - case float32: - asFloat64 := float64(value) - var str string - switch { - case math.IsNaN(asFloat64): - str = floatNaN - case math.IsInf(asFloat64, 1): - str = floatInf - case math.IsInf(asFloat64, -1): - str = floatNegInf - default: - str = strconv.FormatFloat(asFloat64, 'f', -1, 32) - } - v.Set(name, str) - case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.ISO8601TimeFormatName - } - - v.Set(name, protocol.FormatTime(format, value)) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name()) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go deleted file mode 100644 index 9231e95d1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go +++ /dev/null @@ -1,39 +0,0 @@ -package query - -//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/output/query.json unmarshal_test.go - -import ( - "encoding/xml" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" -) - -// UnmarshalHandler is a named request handler for unmarshaling query protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.query.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling query protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalMeta", Fn: UnmarshalMeta} - -// Unmarshal unmarshals a response for an AWS Query service. -func Unmarshal(r *request.Request) { - defer r.HTTPResponse.Body.Close() - if r.DataFilled() { - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result") - if err != nil { - r.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, "failed decoding Query response", err), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - return - } - } -} - -// UnmarshalMeta unmarshals header response values for an AWS Query service. -func UnmarshalMeta(r *request.Request) { - r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go deleted file mode 100644 index 2c0cbba90..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go +++ /dev/null @@ -1,70 +0,0 @@ -package query - -import ( - "encoding/xml" - "fmt" - "strings" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" -) - -// UnmarshalErrorHandler is a name request handler to unmarshal request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalError", Fn: UnmarshalError} - -type xmlErrorResponse struct { - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} - -type xmlResponseError struct { - xmlErrorResponse -} - -func (e *xmlResponseError) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { - const svcUnavailableTagName = "ServiceUnavailableException" - const errorResponseTagName = "ErrorResponse" - - switch start.Name.Local { - case svcUnavailableTagName: - e.Code = svcUnavailableTagName - e.Message = "service is unavailable" - return d.Skip() - - case errorResponseTagName: - return d.DecodeElement(&e.xmlErrorResponse, &start) - - default: - return fmt.Errorf("unknown error response tag, %v", start) - } -} - -// UnmarshalError unmarshals an error response for an AWS Query service. -func UnmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - var respErr xmlResponseError - err := xmlutil.UnmarshalXMLError(&respErr, r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, - "failed to unmarshal error message", err), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - return - } - - reqID := respErr.RequestID - if len(reqID) == 0 { - reqID = r.RequestID - } - - r.Error = awserr.NewRequestFailure( - awserr.New(strings.TrimSpace(respErr.Code), strings.TrimSpace(respErr.Message), nil), - r.HTTPResponse.StatusCode, - reqID, - ) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go deleted file mode 100644 index ecc521f88..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go +++ /dev/null @@ -1,353 +0,0 @@ -// Package rest provides RESTful serialization of AWS requests and responses. -package rest - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "math" - "net/http" - "net/url" - "path" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" -) - -const ( - floatNaN = "NaN" - floatInf = "Infinity" - floatNegInf = "-Infinity" -) - -// Whether the byte value can be sent without escaping in AWS URLs -var noEscape [256]bool - -var errValueNotSet = fmt.Errorf("value not set") - -var byteSliceType = reflect.TypeOf([]byte{}) - -func init() { - for i := 0; i < len(noEscape); i++ { - // AWS expects every character except these to be escaped - noEscape[i] = (i >= 'A' && i <= 'Z') || - (i >= 'a' && i <= 'z') || - (i >= '0' && i <= '9') || - i == '-' || - i == '.' || - i == '_' || - i == '~' - } -} - -// BuildHandler is a named request handler for building rest protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.rest.Build", Fn: Build} - -// Build builds the REST component of a service request. -func Build(r *request.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v, false) - buildBody(r, v) - } -} - -// BuildAsGET builds the REST component of a service request with the ability to hoist -// data from the body. -func BuildAsGET(r *request.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v, true) - buildBody(r, v) - } -} - -func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) { - query := r.HTTPRequest.URL.Query() - - // Setup the raw path to match the base path pattern. This is needed - // so that when the path is mutated a custom escaped version can be - // stored in RawPath that will be used by the Go client. - r.HTTPRequest.URL.RawPath = r.HTTPRequest.URL.Path - - for i := 0; i < v.NumField(); i++ { - m := v.Field(i) - if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - field := v.Type().Field(i) - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - if kind := m.Kind(); kind == reflect.Ptr { - m = m.Elem() - } else if kind == reflect.Interface { - if !m.Elem().IsValid() { - continue - } - } - if !m.IsValid() { - continue - } - if field.Tag.Get("ignore") != "" { - continue - } - - // Support the ability to customize values to be marshaled as a - // blob even though they were modeled as a string. Required for S3 - // API operations like SSECustomerKey is modeled as string but - // required to be base64 encoded in request. - if field.Tag.Get("marshal-as") == "blob" { - m = m.Convert(byteSliceType) - } - - var err error - switch field.Tag.Get("location") { - case "headers": // header maps - err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag) - case "header": - err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag) - case "uri": - err = buildURI(r.HTTPRequest.URL, m, name, field.Tag) - case "querystring": - err = buildQueryString(query, m, name, field.Tag) - default: - if buildGETQuery { - err = buildQueryString(query, m, name, field.Tag) - } - } - r.Error = err - } - if r.Error != nil { - return - } - } - - r.HTTPRequest.URL.RawQuery = query.Encode() - if !aws.BoolValue(r.Config.DisableRestProtocolURICleaning) { - cleanPath(r.HTTPRequest.URL) - } -} - -func buildBody(r *request.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := reflect.Indirect(v.FieldByName(payloadName)) - if payload.IsValid() && payload.Interface() != nil { - switch reader := payload.Interface().(type) { - case io.ReadSeeker: - r.SetReaderBody(reader) - case []byte: - r.SetBufferBody(reader) - case string: - r.SetStringBody(reader) - default: - r.Error = awserr.New(request.ErrCodeSerialization, - "failed to encode REST request", - fmt.Errorf("unknown payload type %s", payload.Type())) - } - } - } - } - } -} - -func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error { - str, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New(request.ErrCodeSerialization, "failed to encode REST request", err) - } - - name = strings.TrimSpace(name) - str = strings.TrimSpace(str) - - header.Add(name, str) - - return nil -} - -func buildHeaderMap(header *http.Header, v reflect.Value, tag reflect.StructTag) error { - prefix := tag.Get("locationName") - for _, key := range v.MapKeys() { - str, err := convertType(v.MapIndex(key), tag) - if err == errValueNotSet { - continue - } else if err != nil { - return awserr.New(request.ErrCodeSerialization, "failed to encode REST request", err) - - } - keyStr := strings.TrimSpace(key.String()) - str = strings.TrimSpace(str) - - header.Add(prefix+keyStr, str) - } - return nil -} - -func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error { - value, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New(request.ErrCodeSerialization, "failed to encode REST request", err) - } - - u.Path = strings.Replace(u.Path, "{"+name+"}", value, -1) - u.Path = strings.Replace(u.Path, "{"+name+"+}", value, -1) - - u.RawPath = strings.Replace(u.RawPath, "{"+name+"}", EscapePath(value, true), -1) - u.RawPath = strings.Replace(u.RawPath, "{"+name+"+}", EscapePath(value, false), -1) - - return nil -} - -func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error { - switch value := v.Interface().(type) { - case []*string: - for _, item := range value { - query.Add(name, *item) - } - case map[string]*string: - for key, item := range value { - query.Add(key, *item) - } - case map[string][]*string: - for key, items := range value { - for _, item := range items { - query.Add(key, *item) - } - } - default: - str, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New(request.ErrCodeSerialization, "failed to encode REST request", err) - } - query.Set(name, str) - } - - return nil -} - -func cleanPath(u *url.URL) { - hasSlash := strings.HasSuffix(u.Path, "/") - - // clean up path, removing duplicate `/` - u.Path = path.Clean(u.Path) - u.RawPath = path.Clean(u.RawPath) - - if hasSlash && !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - u.RawPath += "/" - } -} - -// EscapePath escapes part of a URL path in Amazon style -func EscapePath(path string, encodeSep bool) string { - var buf bytes.Buffer - for i := 0; i < len(path); i++ { - c := path[i] - if noEscape[c] || (c == '/' && !encodeSep) { - buf.WriteByte(c) - } else { - fmt.Fprintf(&buf, "%%%02X", c) - } - } - return buf.String() -} - -func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error) { - v = reflect.Indirect(v) - if !v.IsValid() { - return "", errValueNotSet - } - - switch value := v.Interface().(type) { - case string: - if tag.Get("suppressedJSONValue") == "true" && tag.Get("location") == "header" { - value = base64.StdEncoding.EncodeToString([]byte(value)) - } - str = value - case []*string: - if tag.Get("location") != "header" || tag.Get("enum") == "" { - return "", fmt.Errorf("%T is only supported with location header and enum shapes", value) - } - if len(value) == 0 { - return "", errValueNotSet - } - - buff := &bytes.Buffer{} - for i, sv := range value { - if sv == nil || len(*sv) == 0 { - continue - } - if i != 0 { - buff.WriteRune(',') - } - item := *sv - if strings.Index(item, `,`) != -1 || strings.Index(item, `"`) != -1 { - item = strconv.Quote(item) - } - buff.WriteString(item) - } - str = string(buff.Bytes()) - case []byte: - str = base64.StdEncoding.EncodeToString(value) - case bool: - str = strconv.FormatBool(value) - case int64: - str = strconv.FormatInt(value, 10) - case float64: - switch { - case math.IsNaN(value): - str = floatNaN - case math.IsInf(value, 1): - str = floatInf - case math.IsInf(value, -1): - str = floatNegInf - default: - str = strconv.FormatFloat(value, 'f', -1, 64) - } - case time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.RFC822TimeFormatName - if tag.Get("location") == "querystring" { - format = protocol.ISO8601TimeFormatName - } - } - str = protocol.FormatTime(format, value) - case aws.JSONValue: - if len(value) == 0 { - return "", errValueNotSet - } - escaping := protocol.NoEscape - if tag.Get("location") == "header" { - escaping = protocol.Base64Escape - } - str, err = protocol.EncodeJSONValue(value, escaping) - if err != nil { - return "", fmt.Errorf("unable to encode JSONValue, %v", err) - } - default: - err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type()) - return "", err - } - - return str, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go deleted file mode 100644 index b54c99eda..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go +++ /dev/null @@ -1,54 +0,0 @@ -package rest - -import "reflect" - -// PayloadMember returns the payload field member of i if there is one, or nil. -func PayloadMember(i interface{}) interface{} { - if i == nil { - return nil - } - - v := reflect.ValueOf(i).Elem() - if !v.IsValid() { - return nil - } - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - field, _ := v.Type().FieldByName(payloadName) - if field.Tag.Get("type") != "structure" { - return nil - } - - payload := v.FieldByName(payloadName) - if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) { - return payload.Interface() - } - } - } - return nil -} - -const nopayloadPayloadType = "nopayload" - -// PayloadType returns the type of a payload field member of i if there is one, -// or "". -func PayloadType(i interface{}) string { - v := reflect.Indirect(reflect.ValueOf(i)) - if !v.IsValid() { - return "" - } - - if field, ok := v.Type().FieldByName("_"); ok { - if noPayload := field.Tag.Get(nopayloadPayloadType); noPayload != "" { - return nopayloadPayloadType - } - - if payloadName := field.Tag.Get("payload"); payloadName != "" { - if member, ok := v.Type().FieldByName(payloadName); ok { - return member.Tag.Get("type") - } - } - } - - return "" -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go deleted file mode 100644 index 79fcf1699..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go +++ /dev/null @@ -1,276 +0,0 @@ -package rest - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "io/ioutil" - "math" - "net/http" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - awsStrings "github.com/aws/aws-sdk-go/internal/strings" - "github.com/aws/aws-sdk-go/private/protocol" -) - -// UnmarshalHandler is a named request handler for unmarshaling rest protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.rest.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling rest protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.rest.UnmarshalMeta", Fn: UnmarshalMeta} - -// Unmarshal unmarshals the REST component of a response in a REST service. -func Unmarshal(r *request.Request) { - if r.DataFilled() { - v := reflect.Indirect(reflect.ValueOf(r.Data)) - if err := unmarshalBody(r, v); err != nil { - r.Error = err - } - } -} - -// UnmarshalMeta unmarshals the REST metadata of a response in a REST service -func UnmarshalMeta(r *request.Request) { - r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") - if r.RequestID == "" { - // Alternative version of request id in the header - r.RequestID = r.HTTPResponse.Header.Get("X-Amz-Request-Id") - } - if r.DataFilled() { - if err := UnmarshalResponse(r.HTTPResponse, r.Data, aws.BoolValue(r.Config.LowerCaseHeaderMaps)); err != nil { - r.Error = err - } - } -} - -// UnmarshalResponse attempts to unmarshal the REST response headers to -// the data type passed in. The type must be a pointer. An error is returned -// with any error unmarshaling the response into the target datatype. -func UnmarshalResponse(resp *http.Response, data interface{}, lowerCaseHeaderMaps bool) error { - v := reflect.Indirect(reflect.ValueOf(data)) - return unmarshalLocationElements(resp, v, lowerCaseHeaderMaps) -} - -func unmarshalBody(r *request.Request, v reflect.Value) error { - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := v.FieldByName(payloadName) - if payload.IsValid() { - switch payload.Interface().(type) { - case []byte: - defer r.HTTPResponse.Body.Close() - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - return awserr.New(request.ErrCodeSerialization, "failed to decode REST response", err) - } - - payload.Set(reflect.ValueOf(b)) - - case *string: - defer r.HTTPResponse.Body.Close() - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - return awserr.New(request.ErrCodeSerialization, "failed to decode REST response", err) - } - - str := string(b) - payload.Set(reflect.ValueOf(&str)) - - default: - switch payload.Type().String() { - case "io.ReadCloser": - payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) - - case "io.ReadSeeker": - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - return awserr.New(request.ErrCodeSerialization, - "failed to read response body", err) - } - payload.Set(reflect.ValueOf(ioutil.NopCloser(bytes.NewReader(b)))) - - default: - io.Copy(ioutil.Discard, r.HTTPResponse.Body) - r.HTTPResponse.Body.Close() - return awserr.New(request.ErrCodeSerialization, - "failed to decode REST response", - fmt.Errorf("unknown payload type %s", payload.Type())) - } - } - } - } - } - } - - return nil -} - -func unmarshalLocationElements(resp *http.Response, v reflect.Value, lowerCaseHeaderMaps bool) error { - for i := 0; i < v.NumField(); i++ { - m, field := v.Field(i), v.Type().Field(i) - if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - - switch field.Tag.Get("location") { - case "statusCode": - unmarshalStatusCode(m, resp.StatusCode) - - case "header": - err := unmarshalHeader(m, resp.Header.Get(name), field.Tag) - if err != nil { - return awserr.New(request.ErrCodeSerialization, "failed to decode REST response", err) - } - - case "headers": - prefix := field.Tag.Get("locationName") - err := unmarshalHeaderMap(m, resp.Header, prefix, lowerCaseHeaderMaps) - if err != nil { - return awserr.New(request.ErrCodeSerialization, "failed to decode REST response", err) - } - } - } - } - - return nil -} - -func unmarshalStatusCode(v reflect.Value, statusCode int) { - if !v.IsValid() { - return - } - - switch v.Interface().(type) { - case *int64: - s := int64(statusCode) - v.Set(reflect.ValueOf(&s)) - } -} - -func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string, normalize bool) error { - if len(headers) == 0 { - return nil - } - switch r.Interface().(type) { - case map[string]*string: // we only support string map value types - out := map[string]*string{} - for k, v := range headers { - if awsStrings.HasPrefixFold(k, prefix) { - if normalize == true { - k = strings.ToLower(k) - } else { - k = http.CanonicalHeaderKey(k) - } - out[k[len(prefix):]] = &v[0] - } - } - if len(out) != 0 { - r.Set(reflect.ValueOf(out)) - } - - } - return nil -} - -func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) error { - switch tag.Get("type") { - case "jsonvalue": - if len(header) == 0 { - return nil - } - case "blob": - if len(header) == 0 { - return nil - } - default: - if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { - return nil - } - } - - switch v.Interface().(type) { - case *string: - if tag.Get("suppressedJSONValue") == "true" && tag.Get("location") == "header" { - b, err := base64.StdEncoding.DecodeString(header) - if err != nil { - return fmt.Errorf("failed to decode JSONValue, %v", err) - } - header = string(b) - } - v.Set(reflect.ValueOf(&header)) - case []byte: - b, err := base64.StdEncoding.DecodeString(header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(b)) - case *bool: - b, err := strconv.ParseBool(header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&b)) - case *int64: - i, err := strconv.ParseInt(header, 10, 64) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&i)) - case *float64: - var f float64 - switch { - case strings.EqualFold(header, floatNaN): - f = math.NaN() - case strings.EqualFold(header, floatInf): - f = math.Inf(1) - case strings.EqualFold(header, floatNegInf): - f = math.Inf(-1) - default: - var err error - f, err = strconv.ParseFloat(header, 64) - if err != nil { - return err - } - } - v.Set(reflect.ValueOf(&f)) - case *time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.RFC822TimeFormatName - } - t, err := protocol.ParseTime(format, header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&t)) - case aws.JSONValue: - escaping := protocol.NoEscape - if tag.Get("location") == "header" { - escaping = protocol.Base64Escape - } - m, err := protocol.DecodeJSONValue(header, escaping) - if err != nil { - return err - } - v.Set(reflect.ValueOf(m)) - default: - err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) - return err - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/restjson.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/restjson.go deleted file mode 100644 index 2e0e205af..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/restjson.go +++ /dev/null @@ -1,59 +0,0 @@ -// Package restjson provides RESTful JSON serialization of AWS -// requests and responses. -package restjson - -//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/input/rest-json.json build_test.go -//go:generate go run -tags codegen ../../../private/model/cli/gen-protocol-tests ../../../models/protocol_tests/output/rest-json.json unmarshal_test.go - -import ( - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -// BuildHandler is a named request handler for building restjson protocol -// requests -var BuildHandler = request.NamedHandler{ - Name: "awssdk.restjson.Build", - Fn: Build, -} - -// UnmarshalHandler is a named request handler for unmarshaling restjson -// protocol requests -var UnmarshalHandler = request.NamedHandler{ - Name: "awssdk.restjson.Unmarshal", - Fn: Unmarshal, -} - -// UnmarshalMetaHandler is a named request handler for unmarshaling restjson -// protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{ - Name: "awssdk.restjson.UnmarshalMeta", - Fn: UnmarshalMeta, -} - -// Build builds a request for the REST JSON protocol. -func Build(r *request.Request) { - rest.Build(r) - - if t := rest.PayloadType(r.Params); t == "structure" || t == "" { - if v := r.HTTPRequest.Header.Get("Content-Type"); len(v) == 0 { - r.HTTPRequest.Header.Set("Content-Type", "application/json") - } - jsonrpc.Build(r) - } -} - -// Unmarshal unmarshals a response body for the REST JSON protocol. -func Unmarshal(r *request.Request) { - if t := rest.PayloadType(r.Data); t == "structure" || t == "" { - jsonrpc.Unmarshal(r) - } else { - rest.Unmarshal(r) - } -} - -// UnmarshalMeta unmarshals response headers for the REST JSON protocol. -func UnmarshalMeta(r *request.Request) { - rest.UnmarshalMeta(r) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go deleted file mode 100644 index 5366a646d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go +++ /dev/null @@ -1,157 +0,0 @@ -package restjson - -import ( - "bytes" - "encoding/json" - "io" - "io/ioutil" - "net/http" - "strings" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -const ( - errorTypeHeader = "X-Amzn-Errortype" - errorMessageHeader = "X-Amzn-Errormessage" -) - -// UnmarshalTypedError provides unmarshaling errors API response errors -// for both typed and untyped errors. -type UnmarshalTypedError struct { - exceptions map[string]func(protocol.ResponseMetadata) error -} - -// NewUnmarshalTypedError returns an UnmarshalTypedError initialized for the -// set of exception names to the error unmarshalers -func NewUnmarshalTypedError(exceptions map[string]func(protocol.ResponseMetadata) error) *UnmarshalTypedError { - return &UnmarshalTypedError{ - exceptions: exceptions, - } -} - -// UnmarshalError attempts to unmarshal the HTTP response error as a known -// error type. If unable to unmarshal the error type, the generic SDK error -// type will be used. -func (u *UnmarshalTypedError) UnmarshalError( - resp *http.Response, - respMeta protocol.ResponseMetadata, -) (error, error) { - code, msg, err := unmarshalErrorInfo(resp) - if err != nil { - return nil, err - } - - fn, ok := u.exceptions[code] - if !ok { - return awserr.NewRequestFailure( - awserr.New(code, msg, nil), - respMeta.StatusCode, - respMeta.RequestID, - ), nil - } - - v := fn(respMeta) - if err := jsonutil.UnmarshalJSONCaseInsensitive(v, resp.Body); err != nil { - return nil, err - } - - if err := rest.UnmarshalResponse(resp, v, true); err != nil { - return nil, err - } - - return v, nil -} - -// UnmarshalErrorHandler is a named request handler for unmarshaling restjson -// protocol request errors -var UnmarshalErrorHandler = request.NamedHandler{ - Name: "awssdk.restjson.UnmarshalError", - Fn: UnmarshalError, -} - -// UnmarshalError unmarshals a response error for the REST JSON protocol. -func UnmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - code, msg, err := unmarshalErrorInfo(r.HTTPResponse) - if err != nil { - r.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, "failed to unmarshal response error", err), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - return - } - - r.Error = awserr.NewRequestFailure( - awserr.New(code, msg, nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ) -} - -type jsonErrorResponse struct { - Type string `json:"__type"` - Code string `json:"code"` - Message string `json:"message"` -} - -func (j *jsonErrorResponse) SanitizedCode() string { - code := j.Code - if len(j.Type) > 0 { - code = j.Type - } - return sanitizeCode(code) -} - -// Remove superfluous components from a restJson error code. -// - If a : character is present, then take only the contents before the -// first : character in the value. -// - If a # character is present, then take only the contents after the first -// # character in the value. -// -// All of the following error values resolve to FooError: -// - FooError -// - FooError:http://internal.amazon.com/coral/com.amazon.coral.validate/ -// - aws.protocoltests.restjson#FooError -// - aws.protocoltests.restjson#FooError:http://internal.amazon.com/coral/com.amazon.coral.validate/ -func sanitizeCode(code string) string { - noColon := strings.SplitN(code, ":", 2)[0] - hashSplit := strings.SplitN(noColon, "#", 2) - return hashSplit[len(hashSplit)-1] -} - -// attempt to garner error details from the response, preferring header values -// when present -func unmarshalErrorInfo(resp *http.Response) (code string, msg string, err error) { - code = sanitizeCode(resp.Header.Get(errorTypeHeader)) - msg = resp.Header.Get(errorMessageHeader) - if len(code) > 0 && len(msg) > 0 { - return - } - - // a modeled error will have to be re-deserialized later, so the body must - // be preserved - var buf bytes.Buffer - tee := io.TeeReader(resp.Body, &buf) - defer func() { resp.Body = ioutil.NopCloser(&buf) }() - - var jsonErr jsonErrorResponse - if decodeErr := json.NewDecoder(tee).Decode(&jsonErr); decodeErr != nil && decodeErr != io.EOF { - err = awserr.NewUnmarshalError(decodeErr, "failed to decode response body", buf.Bytes()) - return - } - - if len(code) == 0 { - code = jsonErr.SanitizedCode() - } - if len(msg) == 0 { - msg = jsonErr.Message - } - return -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go deleted file mode 100644 index d9a4e7649..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go +++ /dev/null @@ -1,134 +0,0 @@ -package protocol - -import ( - "bytes" - "fmt" - "math" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/internal/sdkmath" -) - -// Names of time formats supported by the SDK -const ( - RFC822TimeFormatName = "rfc822" - ISO8601TimeFormatName = "iso8601" - UnixTimeFormatName = "unixTimestamp" -) - -// Time formats supported by the SDK -// Output time is intended to not contain decimals -const ( - // RFC 7231#section-7.1.1.1 timetamp format. e.g Tue, 29 Apr 2014 18:30:38 GMT - RFC822TimeFormat = "Mon, 2 Jan 2006 15:04:05 GMT" - rfc822TimeFormatSingleDigitDay = "Mon, _2 Jan 2006 15:04:05 GMT" - rfc822TimeFormatSingleDigitDayTwoDigitYear = "Mon, _2 Jan 06 15:04:05 GMT" - - // This format is used for output time without seconds precision - RFC822OutputTimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" - - // RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z - ISO8601TimeFormat = "2006-01-02T15:04:05.999999999Z" - iso8601TimeFormatNoZ = "2006-01-02T15:04:05.999999999" - - // This format is used for output time with fractional second precision up to milliseconds - ISO8601OutputTimeFormat = "2006-01-02T15:04:05.999999999Z" -) - -// IsKnownTimestampFormat returns if the timestamp format name -// is know to the SDK's protocols. -func IsKnownTimestampFormat(name string) bool { - switch name { - case RFC822TimeFormatName: - fallthrough - case ISO8601TimeFormatName: - fallthrough - case UnixTimeFormatName: - return true - default: - return false - } -} - -// FormatTime returns a string value of the time. -func FormatTime(name string, t time.Time) string { - t = t.UTC().Truncate(time.Millisecond) - - switch name { - case RFC822TimeFormatName: - return t.Format(RFC822OutputTimeFormat) - case ISO8601TimeFormatName: - return t.Format(ISO8601OutputTimeFormat) - case UnixTimeFormatName: - ms := t.UnixNano() / int64(time.Millisecond) - return strconv.FormatFloat(float64(ms)/1e3, 'f', -1, 64) - default: - panic("unknown timestamp format name, " + name) - } -} - -// ParseTime attempts to parse the time given the format. Returns -// the time if it was able to be parsed, and fails otherwise. -func ParseTime(formatName, value string) (time.Time, error) { - switch formatName { - case RFC822TimeFormatName: // Smithy HTTPDate format - return tryParse(value, - RFC822TimeFormat, - rfc822TimeFormatSingleDigitDay, - rfc822TimeFormatSingleDigitDayTwoDigitYear, - time.RFC850, - time.ANSIC, - ) - case ISO8601TimeFormatName: // Smithy DateTime format - return tryParse(value, - ISO8601TimeFormat, - iso8601TimeFormatNoZ, - time.RFC3339Nano, - time.RFC3339, - ) - case UnixTimeFormatName: - v, err := strconv.ParseFloat(value, 64) - _, dec := math.Modf(v) - dec = sdkmath.Round(dec*1e3) / 1e3 //Rounds 0.1229999 to 0.123 - if err != nil { - return time.Time{}, err - } - return time.Unix(int64(v), int64(dec*(1e9))), nil - default: - panic("unknown timestamp format name, " + formatName) - } -} - -func tryParse(v string, formats ...string) (time.Time, error) { - var errs parseErrors - for _, f := range formats { - t, err := time.Parse(f, v) - if err != nil { - errs = append(errs, parseError{ - Format: f, - Err: err, - }) - continue - } - return t, nil - } - - return time.Time{}, fmt.Errorf("unable to parse time string, %v", errs) -} - -type parseErrors []parseError - -func (es parseErrors) Error() string { - var s bytes.Buffer - for _, e := range es { - fmt.Fprintf(&s, "\n * %q: %v", e.Format, e.Err) - } - - return "parse errors:" + s.String() -} - -type parseError struct { - Format string - Err error -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go deleted file mode 100644 index f614ef898..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go +++ /dev/null @@ -1,27 +0,0 @@ -package protocol - -import ( - "io" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/request" -) - -// UnmarshalDiscardBodyHandler is a named request handler to empty and close a response's body -var UnmarshalDiscardBodyHandler = request.NamedHandler{Name: "awssdk.shared.UnmarshalDiscardBody", Fn: UnmarshalDiscardBody} - -// UnmarshalDiscardBody is a request handler to empty a response's body and closing it. -func UnmarshalDiscardBody(r *request.Request) { - if r.HTTPResponse == nil || r.HTTPResponse.Body == nil { - return - } - - io.Copy(ioutil.Discard, r.HTTPResponse.Body) - r.HTTPResponse.Body.Close() -} - -// ResponseMetadata provides the SDK response metadata attributes. -type ResponseMetadata struct { - StatusCode int - RequestID string -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_error.go deleted file mode 100644 index cc857f136..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal_error.go +++ /dev/null @@ -1,65 +0,0 @@ -package protocol - -import ( - "net/http" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// UnmarshalErrorHandler provides unmarshaling errors API response errors for -// both typed and untyped errors. -type UnmarshalErrorHandler struct { - unmarshaler ErrorUnmarshaler -} - -// ErrorUnmarshaler is an abstract interface for concrete implementations to -// unmarshal protocol specific response errors. -type ErrorUnmarshaler interface { - UnmarshalError(*http.Response, ResponseMetadata) (error, error) -} - -// NewUnmarshalErrorHandler returns an UnmarshalErrorHandler -// initialized for the set of exception names to the error unmarshalers -func NewUnmarshalErrorHandler(unmarshaler ErrorUnmarshaler) *UnmarshalErrorHandler { - return &UnmarshalErrorHandler{ - unmarshaler: unmarshaler, - } -} - -// UnmarshalErrorHandlerName is the name of the named handler. -const UnmarshalErrorHandlerName = "awssdk.protocol.UnmarshalError" - -// NamedHandler returns a NamedHandler for the unmarshaler using the set of -// errors the unmarshaler was initialized for. -func (u *UnmarshalErrorHandler) NamedHandler() request.NamedHandler { - return request.NamedHandler{ - Name: UnmarshalErrorHandlerName, - Fn: u.UnmarshalError, - } -} - -// UnmarshalError will attempt to unmarshal the API response's error message -// into either a generic SDK error type, or a typed error corresponding to the -// errors exception name. -func (u *UnmarshalErrorHandler) UnmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - respMeta := ResponseMetadata{ - StatusCode: r.HTTPResponse.StatusCode, - RequestID: r.RequestID, - } - - v, err := u.unmarshaler.UnmarshalError(r.HTTPResponse, respMeta) - if err != nil { - r.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, - "failed to unmarshal response error", err), - respMeta.StatusCode, - respMeta.RequestID, - ) - return - } - - r.Error = v -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go deleted file mode 100644 index 58c12bd8c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go +++ /dev/null @@ -1,345 +0,0 @@ -// Package xmlutil provides XML serialization of AWS requests and responses. -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -const ( - floatNaN = "NaN" - floatInf = "Infinity" - floatNegInf = "-Infinity" -) - -// BuildXML will serialize params into an xml.Encoder. Error will be returned -// if the serialization of any of the params or nested values fails. -func BuildXML(params interface{}, e *xml.Encoder) error { - return buildXML(params, e, false) -} - -func buildXML(params interface{}, e *xml.Encoder, sorted bool) error { - b := xmlBuilder{encoder: e, namespaces: map[string]string{}} - root := NewXMLElement(xml.Name{}) - if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil { - return err - } - for _, c := range root.Children { - for _, v := range c { - return StructToXML(e, v, sorted) - } - } - return nil -} - -// Returns the reflection element of a value, if it is a pointer. -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -// A xmlBuilder serializes values from Go code to XML -type xmlBuilder struct { - encoder *xml.Encoder - namespaces map[string]string -} - -// buildValue generic XMLNode builder for any type. Will build value for their specific type -// struct, list, map, scalar. -// -// Also takes a "type" tag value to set what type a value should be converted to XMLNode as. If -// type is not provided reflect will be used to determine the value's type. -func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - value = elemOf(value) - if !value.IsValid() { // no need to handle zero values - return nil - } else if tag.Get("location") != "" { // don't handle non-body location values - return nil - } - - xml := tag.Get("xml") - if len(xml) != 0 { - name := strings.SplitAfterN(xml, ",", 2)[0] - if name == "-" { - return nil - } - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := value.Type().FieldByName("_"); ok { - tag = tag + reflect.StructTag(" ") + field.Tag - } - return b.buildStruct(value, current, tag) - case "list": - return b.buildList(value, current, tag) - case "map": - return b.buildMap(value, current, tag) - default: - return b.buildScalar(value, current, tag) - } -} - -// buildStruct adds a struct and its fields to the current XMLNode. All fields and any nested -// types are converted to XMLNodes also. -func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if !value.IsValid() { - return nil - } - - // unwrap payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := value.Type().FieldByName(payload) - tag = field.Tag - value = elemOf(value.FieldByName(payload)) - - if !value.IsValid() { - return nil - } - } - - child := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - - // there is an xmlNamespace associated with this struct - if prefix, uri := tag.Get("xmlPrefix"), tag.Get("xmlURI"); uri != "" { - ns := xml.Attr{ - Name: xml.Name{Local: "xmlns"}, - Value: uri, - } - if prefix != "" { - b.namespaces[prefix] = uri // register the namespace - ns.Name.Local = "xmlns:" + prefix - } - - child.Attr = append(child.Attr, ns) - } - - var payloadFields, nonPayloadFields int - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - member := elemOf(value.Field(i)) - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("ignore") != "" { - continue - } - - mTag := field.Tag - if mTag.Get("location") != "" { // skip non-body members - nonPayloadFields++ - continue - } - payloadFields++ - - if protocol.CanSetIdempotencyToken(value.Field(i), field) { - token := protocol.GetIdempotencyToken() - member = reflect.ValueOf(token) - } - - memberName := mTag.Get("locationName") - if memberName == "" { - memberName = field.Name - mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`) - } - if err := b.buildValue(member, child, mTag); err != nil { - return err - } - } - - // Only case where the child shape is not added is if the shape only contains - // non-payload fields, e.g headers/query. - if !(payloadFields == 0 && nonPayloadFields > 0) { - current.AddChild(child) - } - - return nil -} - -// buildList adds the value's list items to the current XMLNode as children nodes. All -// nested values in the list are converted to XMLNodes also. -func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted lists - return nil - } - - // check for unflattened list member - flattened := tag.Get("flattened") != "" - - xname := xml.Name{Local: tag.Get("locationName")} - if flattened { - for i := 0; i < value.Len(); i++ { - child := NewXMLElement(xname) - current.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } else { - list := NewXMLElement(xname) - current.AddChild(list) - - for i := 0; i < value.Len(); i++ { - iname := tag.Get("locationNameList") - if iname == "" { - iname = "member" - } - - child := NewXMLElement(xml.Name{Local: iname}) - list.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } - - return nil -} - -// buildMap adds the value's key/value pairs to the current XMLNode as children nodes. All -// nested values in the map are converted to XMLNodes also. -// -// Error will be returned if it is unable to build the map's values into XMLNodes -func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted maps - return nil - } - - maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - current.AddChild(maproot) - current = maproot - - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - // sorting is not required for compliance, but it makes testing easier - keys := make([]string, value.Len()) - for i, k := range value.MapKeys() { - keys[i] = k.String() - } - sort.Strings(keys) - - for _, k := range keys { - v := value.MapIndex(reflect.ValueOf(k)) - - mapcur := current - if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps - child := NewXMLElement(xml.Name{Local: "entry"}) - mapcur.AddChild(child) - mapcur = child - } - - kchild := NewXMLElement(xml.Name{Local: kname}) - kchild.Text = k - vchild := NewXMLElement(xml.Name{Local: vname}) - mapcur.AddChild(kchild) - mapcur.AddChild(vchild) - - if err := b.buildValue(v, vchild, ""); err != nil { - return err - } - } - - return nil -} - -// buildScalar will convert the value into a string and append it as a attribute or child -// of the current XMLNode. -// -// The value will be added as an attribute if tag contains a "xmlAttribute" attribute value. -// -// Error will be returned if the value type is unsupported. -func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - var str string - - switch converted := value.Interface().(type) { - case string: - str = converted - case []byte: - if !value.IsNil() { - str = base64.StdEncoding.EncodeToString(converted) - } - case bool: - str = strconv.FormatBool(converted) - case int64: - str = strconv.FormatInt(converted, 10) - case int: - str = strconv.Itoa(converted) - case float64: - switch { - case math.IsNaN(converted): - str = floatNaN - case math.IsInf(converted, 1): - str = floatInf - case math.IsInf(converted, -1): - str = floatNegInf - default: - str = strconv.FormatFloat(converted, 'f', -1, 64) - } - case float32: - // The SDK doesn't render float32 values in types, only float64. This case would never be hit currently. - asFloat64 := float64(converted) - switch { - case math.IsNaN(asFloat64): - str = floatNaN - case math.IsInf(asFloat64, 1): - str = floatInf - case math.IsInf(asFloat64, -1): - str = floatNegInf - default: - str = strconv.FormatFloat(asFloat64, 'f', -1, 32) - } - case time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.ISO8601TimeFormatName - } - - str = protocol.FormatTime(format, converted) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", - tag.Get("locationName"), value.Interface(), value.Type().Name()) - } - - xname := xml.Name{Local: tag.Get("locationName")} - if tag.Get("xmlAttribute") != "" { // put into current node's attribute list - attr := xml.Attr{Name: xname, Value: str} - current.Attr = append(current.Attr, attr) - } else if len(xname.Local) == 0 { - current.Text = str - } else { // regular text node - current.AddChild(&XMLNode{Name: xname, Text: str}) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/sort.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/sort.go deleted file mode 100644 index c1a511851..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/sort.go +++ /dev/null @@ -1,32 +0,0 @@ -package xmlutil - -import ( - "encoding/xml" - "strings" -) - -type xmlAttrSlice []xml.Attr - -func (x xmlAttrSlice) Len() int { - return len(x) -} - -func (x xmlAttrSlice) Less(i, j int) bool { - spaceI, spaceJ := x[i].Name.Space, x[j].Name.Space - localI, localJ := x[i].Name.Local, x[j].Name.Local - valueI, valueJ := x[i].Value, x[j].Value - - spaceCmp := strings.Compare(spaceI, spaceJ) - localCmp := strings.Compare(localI, localJ) - valueCmp := strings.Compare(valueI, valueJ) - - if spaceCmp == -1 || (spaceCmp == 0 && (localCmp == -1 || (localCmp == 0 && valueCmp == -1))) { - return true - } - - return false -} - -func (x xmlAttrSlice) Swap(i, j int) { - x[i], x[j] = x[j], x[i] -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go deleted file mode 100644 index 44a580a94..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go +++ /dev/null @@ -1,311 +0,0 @@ -package xmlutil - -import ( - "bytes" - "encoding/base64" - "encoding/xml" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/private/protocol" -) - -// UnmarshalXMLError unmarshals the XML error from the stream into the value -// type specified. The value must be a pointer. If the message fails to -// unmarshal, the message content will be included in the returned error as a -// awserr.UnmarshalError. -func UnmarshalXMLError(v interface{}, stream io.Reader) error { - var errBuf bytes.Buffer - body := io.TeeReader(stream, &errBuf) - - err := xml.NewDecoder(body).Decode(v) - if err != nil && err != io.EOF { - return awserr.NewUnmarshalError(err, - "failed to unmarshal error message", errBuf.Bytes()) - } - - return nil -} - -// UnmarshalXML deserializes an xml.Decoder into the container v. V -// needs to match the shape of the XML expected to be decoded. -// If the shape doesn't match unmarshaling will fail. -func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error { - n, err := XMLToStruct(d, nil) - if err != nil { - return err - } - if n.Children != nil { - for _, root := range n.Children { - for _, c := range root { - if wrappedChild, ok := c.Children[wrapper]; ok { - c = wrappedChild[0] // pull out wrapped element - } - - err = parse(reflect.ValueOf(v), c, "") - if err != nil { - if err == io.EOF { - return nil - } - return err - } - } - } - return nil - } - return nil -} - -// parse deserializes any value from the XMLNode. The type tag is used to infer the type, or reflect -// will be used to determine the type from r. -func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - xml := tag.Get("xml") - if len(xml) != 0 { - name := strings.SplitAfterN(xml, ",", 2)[0] - if name == "-" { - return nil - } - } - - rtype := r.Type() - if rtype.Kind() == reflect.Ptr { - rtype = rtype.Elem() // check kind of actual element type - } - - t := tag.Get("type") - if t == "" { - switch rtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if _, ok := r.Interface().(*time.Time); !ok { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := r.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := rtype.FieldByName("_"); ok { - tag = field.Tag - } - return parseStruct(r, node, tag) - case "list": - return parseList(r, node, tag) - case "map": - return parseMap(r, node, tag) - default: - return parseScalar(r, node, tag) - } -} - -// parseStruct deserializes a structure and its fields from an XMLNode. Any nested -// types in the structure will also be deserialized. -func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - if r.Kind() == reflect.Ptr { - if r.IsNil() { // create the structure if it's nil - s := reflect.New(r.Type().Elem()) - r.Set(s) - r = s - } - - r = r.Elem() - t = t.Elem() - } - - // unwrap any payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := t.FieldByName(payload) - return parseStruct(r.FieldByName(payload), node, field.Tag) - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if c := field.Name[0:1]; strings.ToLower(c) == c { - continue // ignore unexported fields - } - - // figure out what this field is called - name := field.Name - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - // try to find the field by name in elements - elems := node.Children[name] - - if elems == nil { // try to find the field in attributes - if val, ok := node.findElem(name); ok { - elems = []*XMLNode{{Text: val}} - } - } - - member := r.FieldByName(field.Name) - for _, elem := range elems { - err := parse(member, elem, field.Tag) - if err != nil { - return err - } - } - } - return nil -} - -// parseList deserializes a list of values from an XML node. Each list entry -// will also be deserialized. -func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - - if tag.Get("flattened") == "" { // look at all item entries - mname := "member" - if name := tag.Get("locationNameList"); name != "" { - mname = name - } - - if Children, ok := node.Children[mname]; ok { - if r.IsNil() { - r.Set(reflect.MakeSlice(t, len(Children), len(Children))) - } - - for i, c := range Children { - err := parse(r.Index(i), c, "") - if err != nil { - return err - } - } - } - } else { // flattened list means this is a single element - if r.IsNil() { - r.Set(reflect.MakeSlice(t, 0, 0)) - } - - childR := reflect.Zero(t.Elem()) - r.Set(reflect.Append(r, childR)) - err := parse(r.Index(r.Len()-1), node, "") - if err != nil { - return err - } - } - - return nil -} - -// parseMap deserializes a map from an XMLNode. The direct children of the XMLNode -// will also be deserialized as map entries. -func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - if r.IsNil() { - r.Set(reflect.MakeMap(r.Type())) - } - - if tag.Get("flattened") == "" { // look at all child entries - for _, entry := range node.Children["entry"] { - parseMapEntry(r, entry, tag) - } - } else { // this element is itself an entry - parseMapEntry(r, node, tag) - } - - return nil -} - -// parseMapEntry deserializes a map entry from a XML node. -func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - keys, ok := node.Children[kname] - values := node.Children[vname] - if ok { - for i, key := range keys { - keyR := reflect.ValueOf(key.Text) - value := values[i] - valueR := reflect.New(r.Type().Elem()).Elem() - - parse(valueR, value, "") - r.SetMapIndex(keyR, valueR) - } - } - return nil -} - -// parseScaller deserializes an XMLNode value into a concrete type based on the -// interface type of r. -// -// Error is returned if the deserialization fails due to invalid type conversion, -// or unsupported interface type. -func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - switch r.Interface().(type) { - case *string: - r.Set(reflect.ValueOf(&node.Text)) - return nil - case []byte: - b, err := base64.StdEncoding.DecodeString(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(b)) - case *bool: - v, err := strconv.ParseBool(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *int64: - v, err := strconv.ParseInt(node.Text, 10, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *float64: - var v float64 - switch { - case strings.EqualFold(node.Text, floatNaN): - v = math.NaN() - case strings.EqualFold(node.Text, floatInf): - v = math.Inf(1) - case strings.EqualFold(node.Text, floatNegInf): - v = math.Inf(-1) - default: - var err error - v, err = strconv.ParseFloat(node.Text, 64) - if err != nil { - return err - } - } - r.Set(reflect.ValueOf(&v)) - case *time.Time: - format := tag.Get("timestampFormat") - if len(format) == 0 { - format = protocol.ISO8601TimeFormatName - } - - t, err := protocol.ParseTime(format, node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&t)) - default: - return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type()) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go deleted file mode 100644 index c85b79fdd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go +++ /dev/null @@ -1,173 +0,0 @@ -package xmlutil - -import ( - "encoding/xml" - "fmt" - "io" - "sort" -) - -// A XMLNode contains the values to be encoded or decoded. -type XMLNode struct { - Name xml.Name `json:",omitempty"` - Children map[string][]*XMLNode `json:",omitempty"` - Text string `json:",omitempty"` - Attr []xml.Attr `json:",omitempty"` - - namespaces map[string]string - parent *XMLNode -} - -// textEncoder is a string type alias that implemnts the TextMarshaler interface. -// This alias type is used to ensure that the line feed (\n) (U+000A) is escaped. -type textEncoder string - -func (t textEncoder) MarshalText() ([]byte, error) { - return []byte(t), nil -} - -// NewXMLElement returns a pointer to a new XMLNode initialized to default values. -func NewXMLElement(name xml.Name) *XMLNode { - return &XMLNode{ - Name: name, - Children: map[string][]*XMLNode{}, - Attr: []xml.Attr{}, - } -} - -// AddChild adds child to the XMLNode. -func (n *XMLNode) AddChild(child *XMLNode) { - child.parent = n - if _, ok := n.Children[child.Name.Local]; !ok { - n.Children[child.Name.Local] = []*XMLNode{} - } - n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child) -} - -// XMLToStruct converts a xml.Decoder stream to XMLNode with nested values. -func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) { - out := &XMLNode{} - for { - tok, err := d.Token() - if err != nil { - if err == io.EOF { - break - } else { - return out, err - } - } - - if tok == nil { - break - } - - switch typed := tok.(type) { - case xml.CharData: - out.Text = string(typed.Copy()) - case xml.StartElement: - el := typed.Copy() - out.Attr = el.Attr - if out.Children == nil { - out.Children = map[string][]*XMLNode{} - } - - name := typed.Name.Local - slice := out.Children[name] - if slice == nil { - slice = []*XMLNode{} - } - node, e := XMLToStruct(d, &el) - out.findNamespaces() - if e != nil { - return out, e - } - node.Name = typed.Name - node.findNamespaces() - tempOut := *out - // Save into a temp variable, simply because out gets squashed during - // loop iterations - node.parent = &tempOut - slice = append(slice, node) - out.Children[name] = slice - case xml.EndElement: - if s != nil && s.Name.Local == typed.Name.Local { // matching end token - return out, nil - } - out = &XMLNode{} - } - } - return out, nil -} - -func (n *XMLNode) findNamespaces() { - ns := map[string]string{} - for _, a := range n.Attr { - if a.Name.Space == "xmlns" { - ns[a.Value] = a.Name.Local - } - } - - n.namespaces = ns -} - -func (n *XMLNode) findElem(name string) (string, bool) { - for node := n; node != nil; node = node.parent { - for _, a := range node.Attr { - namespace := a.Name.Space - if v, ok := node.namespaces[namespace]; ok { - namespace = v - } - if name == fmt.Sprintf("%s:%s", namespace, a.Name.Local) { - return a.Value, true - } - } - } - return "", false -} - -// StructToXML writes an XMLNode to a xml.Encoder as tokens. -func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error { - // Sort Attributes - attrs := node.Attr - if sorted { - sortedAttrs := make([]xml.Attr, len(attrs)) - for _, k := range node.Attr { - sortedAttrs = append(sortedAttrs, k) - } - sort.Sort(xmlAttrSlice(sortedAttrs)) - attrs = sortedAttrs - } - - startElement := xml.StartElement{Name: node.Name, Attr: attrs} - - if node.Text != "" { - e.EncodeElement(textEncoder(node.Text), startElement) - return e.Flush() - } - - e.EncodeToken(startElement) - - if sorted { - sortedNames := []string{} - for k := range node.Children { - sortedNames = append(sortedNames, k) - } - sort.Strings(sortedNames) - - for _, k := range sortedNames { - for _, v := range node.Children[k] { - StructToXML(e, v, sorted) - } - } - } else { - for _, c := range node.Children { - for _, v := range c { - StructToXML(e, v, sorted) - } - } - } - - e.EncodeToken(startElement.End()) - - return e.Flush() -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go deleted file mode 100644 index 93f1dca6f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/api.go +++ /dev/null @@ -1,21368 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package cloudwatchlogs - -import ( - "bytes" - "fmt" - "io" - "sync" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/eventstream" - "github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -const opAssociateKmsKey = "AssociateKmsKey" - -// AssociateKmsKeyRequest generates a "aws/request.Request" representing the -// client's request for the AssociateKmsKey operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssociateKmsKey for more information on using the AssociateKmsKey -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the AssociateKmsKeyRequest method. -// req, resp := client.AssociateKmsKeyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/AssociateKmsKey -func (c *CloudWatchLogs) AssociateKmsKeyRequest(input *AssociateKmsKeyInput) (req *request.Request, output *AssociateKmsKeyOutput) { - op := &request.Operation{ - Name: opAssociateKmsKey, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssociateKmsKeyInput{} - } - - output = &AssociateKmsKeyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// AssociateKmsKey API operation for Amazon CloudWatch Logs. -// -// Associates the specified KMS key with either one log group in the account, -// or with all stored CloudWatch Logs query insights results in the account. -// -// When you use AssociateKmsKey, you specify either the logGroupName parameter -// or the resourceIdentifier parameter. You can't specify both of those parameters -// in the same operation. -// -// - Specify the logGroupName parameter to cause all log events stored in -// the log group to be encrypted with that key. Only the log events ingested -// after the key is associated are encrypted with that key. Associating a -// KMS key with a log group overrides any existing associations between the -// log group and a KMS key. After a KMS key is associated with a log group, -// all newly ingested data for the log group is encrypted using the KMS key. -// This association is stored as long as the data encrypted with the KMS -// key is still within CloudWatch Logs. This enables CloudWatch Logs to decrypt -// this data whenever it is requested. Associating a key with a log group -// does not cause the results of queries of that log group to be encrypted -// with that key. To have query results encrypted with a KMS key, you must -// use an AssociateKmsKey operation with the resourceIdentifier parameter -// that specifies a query-result resource. -// -// - Specify the resourceIdentifier parameter with a query-result resource, -// to use that key to encrypt the stored results of all future StartQuery -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html) -// operations in the account. The response from a GetQueryResults (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetQueryResults.html) -// operation will still return the query results in plain text. Even if you -// have not associated a key with your query results, the query results are -// encrypted when stored, using the default CloudWatch Logs method. If you -// run a query from a monitoring account that queries logs in a source account, -// the query results key from the monitoring account, if any, is used. -// -// If you delete the key that is used to encrypt log events or log group query -// results, then all the associated stored log events or query results that -// were encrypted with that key will be unencryptable and unusable. -// -// CloudWatch Logs supports only symmetric KMS keys. Do not use an associate -// an asymmetric KMS key with your log group or query results. For more information, -// see Using Symmetric and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html). -// -// It can take up to 5 minutes for this operation to take effect. -// -// If you attempt to associate a KMS key with a log group but the KMS key does -// not exist or the KMS key is disabled, you receive an InvalidParameterException -// error. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation AssociateKmsKey for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/AssociateKmsKey -func (c *CloudWatchLogs) AssociateKmsKey(input *AssociateKmsKeyInput) (*AssociateKmsKeyOutput, error) { - req, out := c.AssociateKmsKeyRequest(input) - return out, req.Send() -} - -// AssociateKmsKeyWithContext is the same as AssociateKmsKey with the addition of -// the ability to pass a context and additional request options. -// -// See AssociateKmsKey for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) AssociateKmsKeyWithContext(ctx aws.Context, input *AssociateKmsKeyInput, opts ...request.Option) (*AssociateKmsKeyOutput, error) { - req, out := c.AssociateKmsKeyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCancelExportTask = "CancelExportTask" - -// CancelExportTaskRequest generates a "aws/request.Request" representing the -// client's request for the CancelExportTask operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CancelExportTask for more information on using the CancelExportTask -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the CancelExportTaskRequest method. -// req, resp := client.CancelExportTaskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CancelExportTask -func (c *CloudWatchLogs) CancelExportTaskRequest(input *CancelExportTaskInput) (req *request.Request, output *CancelExportTaskOutput) { - op := &request.Operation{ - Name: opCancelExportTask, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CancelExportTaskInput{} - } - - output = &CancelExportTaskOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// CancelExportTask API operation for Amazon CloudWatch Logs. -// -// Cancels the specified export task. -// -// The task must be in the PENDING or RUNNING state. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation CancelExportTask for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - InvalidOperationException -// The operation is not valid on the specified resource. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CancelExportTask -func (c *CloudWatchLogs) CancelExportTask(input *CancelExportTaskInput) (*CancelExportTaskOutput, error) { - req, out := c.CancelExportTaskRequest(input) - return out, req.Send() -} - -// CancelExportTaskWithContext is the same as CancelExportTask with the addition of -// the ability to pass a context and additional request options. -// -// See CancelExportTask for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) CancelExportTaskWithContext(ctx aws.Context, input *CancelExportTaskInput, opts ...request.Option) (*CancelExportTaskOutput, error) { - req, out := c.CancelExportTaskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDelivery = "CreateDelivery" - -// CreateDeliveryRequest generates a "aws/request.Request" representing the -// client's request for the CreateDelivery operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDelivery for more information on using the CreateDelivery -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the CreateDeliveryRequest method. -// req, resp := client.CreateDeliveryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateDelivery -func (c *CloudWatchLogs) CreateDeliveryRequest(input *CreateDeliveryInput) (req *request.Request, output *CreateDeliveryOutput) { - op := &request.Operation{ - Name: opCreateDelivery, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDeliveryInput{} - } - - output = &CreateDeliveryOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDelivery API operation for Amazon CloudWatch Logs. -// -// Creates a delivery. A delivery is a connection between a logical delivery -// source and a logical delivery destination that you have already created. -// -// Only some Amazon Web Services services support being configured as a delivery -// source using this operation. These services are listed as Supported [V2 Permissions] -// in the table at Enabling logging from Amazon Web Services services. (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html) -// -// A delivery destination can represent a log group in CloudWatch Logs, an Amazon -// S3 bucket, or a delivery stream in Firehose. -// -// To configure logs delivery between a supported Amazon Web Services service -// and a destination, you must do the following: -// -// - Create a delivery source, which is a logical object that represents -// the resource that is actually sending the logs. For more information, -// see PutDeliverySource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliverySource.html). -// -// - Create a delivery destination, which is a logical object that represents -// the actual delivery destination. For more information, see PutDeliveryDestination -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestination.html). -// -// - If you are delivering logs cross-account, you must use PutDeliveryDestinationPolicy -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestinationPolicy.html) -// in the destination account to assign an IAM policy to the destination. -// This policy allows delivery to that destination. -// -// - Use CreateDelivery to create a delivery by pairing exactly one delivery -// source and one delivery destination. -// -// You can configure a single delivery source to send logs to multiple destinations -// by creating multiple deliveries. You can also create multiple deliveries -// to configure multiple delivery sources to send logs to the same delivery -// destination. -// -// You can't update an existing delivery. You can only create and delete deliveries. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation CreateDelivery for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ConflictException -// This operation attempted to create a resource that already exists. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - AccessDeniedException -// You don't have sufficient permissions to perform this action. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateDelivery -func (c *CloudWatchLogs) CreateDelivery(input *CreateDeliveryInput) (*CreateDeliveryOutput, error) { - req, out := c.CreateDeliveryRequest(input) - return out, req.Send() -} - -// CreateDeliveryWithContext is the same as CreateDelivery with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDelivery for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) CreateDeliveryWithContext(ctx aws.Context, input *CreateDeliveryInput, opts ...request.Option) (*CreateDeliveryOutput, error) { - req, out := c.CreateDeliveryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateExportTask = "CreateExportTask" - -// CreateExportTaskRequest generates a "aws/request.Request" representing the -// client's request for the CreateExportTask operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateExportTask for more information on using the CreateExportTask -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the CreateExportTaskRequest method. -// req, resp := client.CreateExportTaskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateExportTask -func (c *CloudWatchLogs) CreateExportTaskRequest(input *CreateExportTaskInput) (req *request.Request, output *CreateExportTaskOutput) { - op := &request.Operation{ - Name: opCreateExportTask, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateExportTaskInput{} - } - - output = &CreateExportTaskOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateExportTask API operation for Amazon CloudWatch Logs. -// -// Creates an export task so that you can efficiently export data from a log -// group to an Amazon S3 bucket. When you perform a CreateExportTask operation, -// you must use credentials that have permission to write to the S3 bucket that -// you specify as the destination. -// -// Exporting log data to S3 buckets that are encrypted by KMS is supported. -// Exporting log data to Amazon S3 buckets that have S3 Object Lock enabled -// with a retention period is also supported. -// -// Exporting to S3 buckets that are encrypted with AES-256 is supported. -// -// This is an asynchronous call. If all the required information is provided, -// this operation initiates an export task and responds with the ID of the task. -// After the task has started, you can use DescribeExportTasks (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeExportTasks.html) -// to get the status of the export task. Each account can only have one active -// (RUNNING or PENDING) export task at a time. To cancel an export task, use -// CancelExportTask (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CancelExportTask.html). -// -// You can export logs from multiple log groups or multiple time ranges to the -// same S3 bucket. To separate log data for each export task, specify a prefix -// to be used as the Amazon S3 key prefix for all exported objects. -// -// Time-based sorting on chunks of log data inside an exported file is not guaranteed. -// You can sort the exported log field data by using Linux utilities. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation CreateExportTask for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ResourceAlreadyExistsException -// The specified resource already exists. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateExportTask -func (c *CloudWatchLogs) CreateExportTask(input *CreateExportTaskInput) (*CreateExportTaskOutput, error) { - req, out := c.CreateExportTaskRequest(input) - return out, req.Send() -} - -// CreateExportTaskWithContext is the same as CreateExportTask with the addition of -// the ability to pass a context and additional request options. -// -// See CreateExportTask for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) CreateExportTaskWithContext(ctx aws.Context, input *CreateExportTaskInput, opts ...request.Option) (*CreateExportTaskOutput, error) { - req, out := c.CreateExportTaskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateLogAnomalyDetector = "CreateLogAnomalyDetector" - -// CreateLogAnomalyDetectorRequest generates a "aws/request.Request" representing the -// client's request for the CreateLogAnomalyDetector operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateLogAnomalyDetector for more information on using the CreateLogAnomalyDetector -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the CreateLogAnomalyDetectorRequest method. -// req, resp := client.CreateLogAnomalyDetectorRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateLogAnomalyDetector -func (c *CloudWatchLogs) CreateLogAnomalyDetectorRequest(input *CreateLogAnomalyDetectorInput) (req *request.Request, output *CreateLogAnomalyDetectorOutput) { - op := &request.Operation{ - Name: opCreateLogAnomalyDetector, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateLogAnomalyDetectorInput{} - } - - output = &CreateLogAnomalyDetectorOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateLogAnomalyDetector API operation for Amazon CloudWatch Logs. -// -// Creates an anomaly detector that regularly scans one or more log groups and -// look for patterns and anomalies in the logs. -// -// An anomaly detector can help surface issues by automatically discovering -// anomalies in your log event traffic. An anomaly detector uses machine learning -// algorithms to scan log events and find patterns. A pattern is a shared text -// structure that recurs among your log fields. Patterns provide a useful tool -// for analyzing large sets of logs because a large number of log events can -// often be compressed into a few patterns. -// -// The anomaly detector uses pattern recognition to find anomalies, which are -// unusual log events. It uses the evaluationFrequency to compare current log -// events and patterns with trained baselines. -// -// Fields within a pattern are called tokens. Fields that vary within a pattern, -// such as a request ID or timestamp, are referred to as dynamic tokens and -// represented by <*>. -// -// The following is an example of a pattern: -// -// [INFO] Request time: <*> ms -// -// This pattern represents log events like [INFO] Request time: 327 ms and other -// similar log events that differ only by the number, in this csse 327. When -// the pattern is displayed, the different numbers are replaced by <*> -// -// Any parts of log events that are masked as sensitive data are not scanned -// for anomalies. For more information about masking sensitive data, see Help -// protect sensitive log data with masking (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation CreateLogAnomalyDetector for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateLogAnomalyDetector -func (c *CloudWatchLogs) CreateLogAnomalyDetector(input *CreateLogAnomalyDetectorInput) (*CreateLogAnomalyDetectorOutput, error) { - req, out := c.CreateLogAnomalyDetectorRequest(input) - return out, req.Send() -} - -// CreateLogAnomalyDetectorWithContext is the same as CreateLogAnomalyDetector with the addition of -// the ability to pass a context and additional request options. -// -// See CreateLogAnomalyDetector for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) CreateLogAnomalyDetectorWithContext(ctx aws.Context, input *CreateLogAnomalyDetectorInput, opts ...request.Option) (*CreateLogAnomalyDetectorOutput, error) { - req, out := c.CreateLogAnomalyDetectorRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateLogGroup = "CreateLogGroup" - -// CreateLogGroupRequest generates a "aws/request.Request" representing the -// client's request for the CreateLogGroup operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateLogGroup for more information on using the CreateLogGroup -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the CreateLogGroupRequest method. -// req, resp := client.CreateLogGroupRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateLogGroup -func (c *CloudWatchLogs) CreateLogGroupRequest(input *CreateLogGroupInput) (req *request.Request, output *CreateLogGroupOutput) { - op := &request.Operation{ - Name: opCreateLogGroup, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateLogGroupInput{} - } - - output = &CreateLogGroupOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// CreateLogGroup API operation for Amazon CloudWatch Logs. -// -// Creates a log group with the specified name. You can create up to 1,000,000 -// log groups per Region per account. -// -// You must use the following guidelines when naming a log group: -// -// - Log group names must be unique within a Region for an Amazon Web Services -// account. -// -// - Log group names can be between 1 and 512 characters long. -// -// - Log group names consist of the following characters: a-z, A-Z, 0-9, -// '_' (underscore), '-' (hyphen), '/' (forward slash), '.' (period), and -// '#' (number sign) -// -// - Log group names can't start with the string aws/ -// -// When you create a log group, by default the log events in the log group do -// not expire. To set a retention policy so that events expire and are deleted -// after a specified time, use PutRetentionPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutRetentionPolicy.html). -// -// If you associate an KMS key with the log group, ingested data is encrypted -// using the KMS key. This association is stored as long as the data encrypted -// with the KMS key is still within CloudWatch Logs. This enables CloudWatch -// Logs to decrypt this data whenever it is requested. -// -// If you attempt to associate a KMS key with the log group but the KMS key -// does not exist or the KMS key is disabled, you receive an InvalidParameterException -// error. -// -// CloudWatch Logs supports only symmetric KMS keys. Do not associate an asymmetric -// KMS key with your log group. For more information, see Using Symmetric and -// Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation CreateLogGroup for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceAlreadyExistsException -// The specified resource already exists. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateLogGroup -func (c *CloudWatchLogs) CreateLogGroup(input *CreateLogGroupInput) (*CreateLogGroupOutput, error) { - req, out := c.CreateLogGroupRequest(input) - return out, req.Send() -} - -// CreateLogGroupWithContext is the same as CreateLogGroup with the addition of -// the ability to pass a context and additional request options. -// -// See CreateLogGroup for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) CreateLogGroupWithContext(ctx aws.Context, input *CreateLogGroupInput, opts ...request.Option) (*CreateLogGroupOutput, error) { - req, out := c.CreateLogGroupRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateLogStream = "CreateLogStream" - -// CreateLogStreamRequest generates a "aws/request.Request" representing the -// client's request for the CreateLogStream operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateLogStream for more information on using the CreateLogStream -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the CreateLogStreamRequest method. -// req, resp := client.CreateLogStreamRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateLogStream -func (c *CloudWatchLogs) CreateLogStreamRequest(input *CreateLogStreamInput) (req *request.Request, output *CreateLogStreamOutput) { - op := &request.Operation{ - Name: opCreateLogStream, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateLogStreamInput{} - } - - output = &CreateLogStreamOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// CreateLogStream API operation for Amazon CloudWatch Logs. -// -// Creates a log stream for the specified log group. A log stream is a sequence -// of log events that originate from a single source, such as an application -// instance or a resource that is being monitored. -// -// There is no limit on the number of log streams that you can create for a -// log group. There is a limit of 50 TPS on CreateLogStream operations, after -// which transactions are throttled. -// -// You must use the following guidelines when naming a log stream: -// -// - Log stream names must be unique within the log group. -// -// - Log stream names can be between 1 and 512 characters long. -// -// - Don't use ':' (colon) or '*' (asterisk) characters. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation CreateLogStream for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceAlreadyExistsException -// The specified resource already exists. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/CreateLogStream -func (c *CloudWatchLogs) CreateLogStream(input *CreateLogStreamInput) (*CreateLogStreamOutput, error) { - req, out := c.CreateLogStreamRequest(input) - return out, req.Send() -} - -// CreateLogStreamWithContext is the same as CreateLogStream with the addition of -// the ability to pass a context and additional request options. -// -// See CreateLogStream for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) CreateLogStreamWithContext(ctx aws.Context, input *CreateLogStreamInput, opts ...request.Option) (*CreateLogStreamOutput, error) { - req, out := c.CreateLogStreamRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteAccountPolicy = "DeleteAccountPolicy" - -// DeleteAccountPolicyRequest generates a "aws/request.Request" representing the -// client's request for the DeleteAccountPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteAccountPolicy for more information on using the DeleteAccountPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteAccountPolicyRequest method. -// req, resp := client.DeleteAccountPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteAccountPolicy -func (c *CloudWatchLogs) DeleteAccountPolicyRequest(input *DeleteAccountPolicyInput) (req *request.Request, output *DeleteAccountPolicyOutput) { - op := &request.Operation{ - Name: opDeleteAccountPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteAccountPolicyInput{} - } - - output = &DeleteAccountPolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteAccountPolicy API operation for Amazon CloudWatch Logs. -// -// Deletes a CloudWatch Logs account policy. This stops the policy from applying -// to all log groups or a subset of log groups in the account. Log-group level -// policies will still be in effect. -// -// To use this operation, you must be signed on with the correct permissions -// depending on the type of policy that you are deleting. -// -// - To delete a data protection policy, you must have the logs:DeleteDataProtectionPolicy -// and logs:DeleteAccountPolicy permissions. -// -// - To delete a subscription filter policy, you must have the logs:DeleteSubscriptionFilter -// and logs:DeleteAccountPolicy permissions. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteAccountPolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteAccountPolicy -func (c *CloudWatchLogs) DeleteAccountPolicy(input *DeleteAccountPolicyInput) (*DeleteAccountPolicyOutput, error) { - req, out := c.DeleteAccountPolicyRequest(input) - return out, req.Send() -} - -// DeleteAccountPolicyWithContext is the same as DeleteAccountPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteAccountPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteAccountPolicyWithContext(ctx aws.Context, input *DeleteAccountPolicyInput, opts ...request.Option) (*DeleteAccountPolicyOutput, error) { - req, out := c.DeleteAccountPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDataProtectionPolicy = "DeleteDataProtectionPolicy" - -// DeleteDataProtectionPolicyRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDataProtectionPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDataProtectionPolicy for more information on using the DeleteDataProtectionPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteDataProtectionPolicyRequest method. -// req, resp := client.DeleteDataProtectionPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDataProtectionPolicy -func (c *CloudWatchLogs) DeleteDataProtectionPolicyRequest(input *DeleteDataProtectionPolicyInput) (req *request.Request, output *DeleteDataProtectionPolicyOutput) { - op := &request.Operation{ - Name: opDeleteDataProtectionPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDataProtectionPolicyInput{} - } - - output = &DeleteDataProtectionPolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteDataProtectionPolicy API operation for Amazon CloudWatch Logs. -// -// Deletes the data protection policy from the specified log group. -// -// For more information about data protection policies, see PutDataProtectionPolicy -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDataProtectionPolicy.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteDataProtectionPolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDataProtectionPolicy -func (c *CloudWatchLogs) DeleteDataProtectionPolicy(input *DeleteDataProtectionPolicyInput) (*DeleteDataProtectionPolicyOutput, error) { - req, out := c.DeleteDataProtectionPolicyRequest(input) - return out, req.Send() -} - -// DeleteDataProtectionPolicyWithContext is the same as DeleteDataProtectionPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDataProtectionPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteDataProtectionPolicyWithContext(ctx aws.Context, input *DeleteDataProtectionPolicyInput, opts ...request.Option) (*DeleteDataProtectionPolicyOutput, error) { - req, out := c.DeleteDataProtectionPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDelivery = "DeleteDelivery" - -// DeleteDeliveryRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDelivery operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDelivery for more information on using the DeleteDelivery -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteDeliveryRequest method. -// req, resp := client.DeleteDeliveryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDelivery -func (c *CloudWatchLogs) DeleteDeliveryRequest(input *DeleteDeliveryInput) (req *request.Request, output *DeleteDeliveryOutput) { - op := &request.Operation{ - Name: opDeleteDelivery, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDeliveryInput{} - } - - output = &DeleteDeliveryOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteDelivery API operation for Amazon CloudWatch Logs. -// -// Deletes s delivery. A delivery is a connection between a logical delivery -// source and a logical delivery destination. Deleting a delivery only deletes -// the connection between the delivery source and delivery destination. It does -// not delete the delivery destination or the delivery source. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteDelivery for usage and error information. -// -// Returned Error Types: -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ConflictException -// This operation attempted to create a resource that already exists. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDelivery -func (c *CloudWatchLogs) DeleteDelivery(input *DeleteDeliveryInput) (*DeleteDeliveryOutput, error) { - req, out := c.DeleteDeliveryRequest(input) - return out, req.Send() -} - -// DeleteDeliveryWithContext is the same as DeleteDelivery with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDelivery for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteDeliveryWithContext(ctx aws.Context, input *DeleteDeliveryInput, opts ...request.Option) (*DeleteDeliveryOutput, error) { - req, out := c.DeleteDeliveryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDeliveryDestination = "DeleteDeliveryDestination" - -// DeleteDeliveryDestinationRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDeliveryDestination operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDeliveryDestination for more information on using the DeleteDeliveryDestination -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteDeliveryDestinationRequest method. -// req, resp := client.DeleteDeliveryDestinationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDeliveryDestination -func (c *CloudWatchLogs) DeleteDeliveryDestinationRequest(input *DeleteDeliveryDestinationInput) (req *request.Request, output *DeleteDeliveryDestinationOutput) { - op := &request.Operation{ - Name: opDeleteDeliveryDestination, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDeliveryDestinationInput{} - } - - output = &DeleteDeliveryDestinationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteDeliveryDestination API operation for Amazon CloudWatch Logs. -// -// Deletes a delivery destination. A delivery is a connection between a logical -// delivery source and a logical delivery destination. -// -// You can't delete a delivery destination if any current deliveries are associated -// with it. To find whether any deliveries are associated with this delivery -// destination, use the DescribeDeliveries (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeDeliveries.html) -// operation and check the deliveryDestinationArn field in the results. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteDeliveryDestination for usage and error information. -// -// Returned Error Types: -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ConflictException -// This operation attempted to create a resource that already exists. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDeliveryDestination -func (c *CloudWatchLogs) DeleteDeliveryDestination(input *DeleteDeliveryDestinationInput) (*DeleteDeliveryDestinationOutput, error) { - req, out := c.DeleteDeliveryDestinationRequest(input) - return out, req.Send() -} - -// DeleteDeliveryDestinationWithContext is the same as DeleteDeliveryDestination with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDeliveryDestination for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteDeliveryDestinationWithContext(ctx aws.Context, input *DeleteDeliveryDestinationInput, opts ...request.Option) (*DeleteDeliveryDestinationOutput, error) { - req, out := c.DeleteDeliveryDestinationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDeliveryDestinationPolicy = "DeleteDeliveryDestinationPolicy" - -// DeleteDeliveryDestinationPolicyRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDeliveryDestinationPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDeliveryDestinationPolicy for more information on using the DeleteDeliveryDestinationPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteDeliveryDestinationPolicyRequest method. -// req, resp := client.DeleteDeliveryDestinationPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDeliveryDestinationPolicy -func (c *CloudWatchLogs) DeleteDeliveryDestinationPolicyRequest(input *DeleteDeliveryDestinationPolicyInput) (req *request.Request, output *DeleteDeliveryDestinationPolicyOutput) { - op := &request.Operation{ - Name: opDeleteDeliveryDestinationPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDeliveryDestinationPolicyInput{} - } - - output = &DeleteDeliveryDestinationPolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteDeliveryDestinationPolicy API operation for Amazon CloudWatch Logs. -// -// Deletes a delivery destination policy. For more information about these policies, -// see PutDeliveryDestinationPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestinationPolicy.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteDeliveryDestinationPolicy for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ConflictException -// This operation attempted to create a resource that already exists. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDeliveryDestinationPolicy -func (c *CloudWatchLogs) DeleteDeliveryDestinationPolicy(input *DeleteDeliveryDestinationPolicyInput) (*DeleteDeliveryDestinationPolicyOutput, error) { - req, out := c.DeleteDeliveryDestinationPolicyRequest(input) - return out, req.Send() -} - -// DeleteDeliveryDestinationPolicyWithContext is the same as DeleteDeliveryDestinationPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDeliveryDestinationPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteDeliveryDestinationPolicyWithContext(ctx aws.Context, input *DeleteDeliveryDestinationPolicyInput, opts ...request.Option) (*DeleteDeliveryDestinationPolicyOutput, error) { - req, out := c.DeleteDeliveryDestinationPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDeliverySource = "DeleteDeliverySource" - -// DeleteDeliverySourceRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDeliverySource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDeliverySource for more information on using the DeleteDeliverySource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteDeliverySourceRequest method. -// req, resp := client.DeleteDeliverySourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDeliverySource -func (c *CloudWatchLogs) DeleteDeliverySourceRequest(input *DeleteDeliverySourceInput) (req *request.Request, output *DeleteDeliverySourceOutput) { - op := &request.Operation{ - Name: opDeleteDeliverySource, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDeliverySourceInput{} - } - - output = &DeleteDeliverySourceOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteDeliverySource API operation for Amazon CloudWatch Logs. -// -// Deletes a delivery source. A delivery is a connection between a logical delivery -// source and a logical delivery destination. -// -// You can't delete a delivery source if any current deliveries are associated -// with it. To find whether any deliveries are associated with this delivery -// source, use the DescribeDeliveries (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeDeliveries.html) -// operation and check the deliverySourceName field in the results. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteDeliverySource for usage and error information. -// -// Returned Error Types: -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ConflictException -// This operation attempted to create a resource that already exists. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDeliverySource -func (c *CloudWatchLogs) DeleteDeliverySource(input *DeleteDeliverySourceInput) (*DeleteDeliverySourceOutput, error) { - req, out := c.DeleteDeliverySourceRequest(input) - return out, req.Send() -} - -// DeleteDeliverySourceWithContext is the same as DeleteDeliverySource with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDeliverySource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteDeliverySourceWithContext(ctx aws.Context, input *DeleteDeliverySourceInput, opts ...request.Option) (*DeleteDeliverySourceOutput, error) { - req, out := c.DeleteDeliverySourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDestination = "DeleteDestination" - -// DeleteDestinationRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDestination operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDestination for more information on using the DeleteDestination -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteDestinationRequest method. -// req, resp := client.DeleteDestinationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDestination -func (c *CloudWatchLogs) DeleteDestinationRequest(input *DeleteDestinationInput) (req *request.Request, output *DeleteDestinationOutput) { - op := &request.Operation{ - Name: opDeleteDestination, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDestinationInput{} - } - - output = &DeleteDestinationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteDestination API operation for Amazon CloudWatch Logs. -// -// Deletes the specified destination, and eventually disables all the subscription -// filters that publish to it. This operation does not delete the physical resource -// encapsulated by the destination. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteDestination for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteDestination -func (c *CloudWatchLogs) DeleteDestination(input *DeleteDestinationInput) (*DeleteDestinationOutput, error) { - req, out := c.DeleteDestinationRequest(input) - return out, req.Send() -} - -// DeleteDestinationWithContext is the same as DeleteDestination with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDestination for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteDestinationWithContext(ctx aws.Context, input *DeleteDestinationInput, opts ...request.Option) (*DeleteDestinationOutput, error) { - req, out := c.DeleteDestinationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteLogAnomalyDetector = "DeleteLogAnomalyDetector" - -// DeleteLogAnomalyDetectorRequest generates a "aws/request.Request" representing the -// client's request for the DeleteLogAnomalyDetector operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteLogAnomalyDetector for more information on using the DeleteLogAnomalyDetector -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteLogAnomalyDetectorRequest method. -// req, resp := client.DeleteLogAnomalyDetectorRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteLogAnomalyDetector -func (c *CloudWatchLogs) DeleteLogAnomalyDetectorRequest(input *DeleteLogAnomalyDetectorInput) (req *request.Request, output *DeleteLogAnomalyDetectorOutput) { - op := &request.Operation{ - Name: opDeleteLogAnomalyDetector, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteLogAnomalyDetectorInput{} - } - - output = &DeleteLogAnomalyDetectorOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteLogAnomalyDetector API operation for Amazon CloudWatch Logs. -// -// Deletes the specified CloudWatch Logs anomaly detector. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteLogAnomalyDetector for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteLogAnomalyDetector -func (c *CloudWatchLogs) DeleteLogAnomalyDetector(input *DeleteLogAnomalyDetectorInput) (*DeleteLogAnomalyDetectorOutput, error) { - req, out := c.DeleteLogAnomalyDetectorRequest(input) - return out, req.Send() -} - -// DeleteLogAnomalyDetectorWithContext is the same as DeleteLogAnomalyDetector with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteLogAnomalyDetector for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteLogAnomalyDetectorWithContext(ctx aws.Context, input *DeleteLogAnomalyDetectorInput, opts ...request.Option) (*DeleteLogAnomalyDetectorOutput, error) { - req, out := c.DeleteLogAnomalyDetectorRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteLogGroup = "DeleteLogGroup" - -// DeleteLogGroupRequest generates a "aws/request.Request" representing the -// client's request for the DeleteLogGroup operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteLogGroup for more information on using the DeleteLogGroup -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteLogGroupRequest method. -// req, resp := client.DeleteLogGroupRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteLogGroup -func (c *CloudWatchLogs) DeleteLogGroupRequest(input *DeleteLogGroupInput) (req *request.Request, output *DeleteLogGroupOutput) { - op := &request.Operation{ - Name: opDeleteLogGroup, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteLogGroupInput{} - } - - output = &DeleteLogGroupOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteLogGroup API operation for Amazon CloudWatch Logs. -// -// Deletes the specified log group and permanently deletes all the archived -// log events associated with the log group. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteLogGroup for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteLogGroup -func (c *CloudWatchLogs) DeleteLogGroup(input *DeleteLogGroupInput) (*DeleteLogGroupOutput, error) { - req, out := c.DeleteLogGroupRequest(input) - return out, req.Send() -} - -// DeleteLogGroupWithContext is the same as DeleteLogGroup with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteLogGroup for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteLogGroupWithContext(ctx aws.Context, input *DeleteLogGroupInput, opts ...request.Option) (*DeleteLogGroupOutput, error) { - req, out := c.DeleteLogGroupRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteLogStream = "DeleteLogStream" - -// DeleteLogStreamRequest generates a "aws/request.Request" representing the -// client's request for the DeleteLogStream operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteLogStream for more information on using the DeleteLogStream -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteLogStreamRequest method. -// req, resp := client.DeleteLogStreamRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteLogStream -func (c *CloudWatchLogs) DeleteLogStreamRequest(input *DeleteLogStreamInput) (req *request.Request, output *DeleteLogStreamOutput) { - op := &request.Operation{ - Name: opDeleteLogStream, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteLogStreamInput{} - } - - output = &DeleteLogStreamOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteLogStream API operation for Amazon CloudWatch Logs. -// -// Deletes the specified log stream and permanently deletes all the archived -// log events associated with the log stream. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteLogStream for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteLogStream -func (c *CloudWatchLogs) DeleteLogStream(input *DeleteLogStreamInput) (*DeleteLogStreamOutput, error) { - req, out := c.DeleteLogStreamRequest(input) - return out, req.Send() -} - -// DeleteLogStreamWithContext is the same as DeleteLogStream with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteLogStream for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteLogStreamWithContext(ctx aws.Context, input *DeleteLogStreamInput, opts ...request.Option) (*DeleteLogStreamOutput, error) { - req, out := c.DeleteLogStreamRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteMetricFilter = "DeleteMetricFilter" - -// DeleteMetricFilterRequest generates a "aws/request.Request" representing the -// client's request for the DeleteMetricFilter operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteMetricFilter for more information on using the DeleteMetricFilter -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteMetricFilterRequest method. -// req, resp := client.DeleteMetricFilterRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteMetricFilter -func (c *CloudWatchLogs) DeleteMetricFilterRequest(input *DeleteMetricFilterInput) (req *request.Request, output *DeleteMetricFilterOutput) { - op := &request.Operation{ - Name: opDeleteMetricFilter, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteMetricFilterInput{} - } - - output = &DeleteMetricFilterOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteMetricFilter API operation for Amazon CloudWatch Logs. -// -// Deletes the specified metric filter. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteMetricFilter for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteMetricFilter -func (c *CloudWatchLogs) DeleteMetricFilter(input *DeleteMetricFilterInput) (*DeleteMetricFilterOutput, error) { - req, out := c.DeleteMetricFilterRequest(input) - return out, req.Send() -} - -// DeleteMetricFilterWithContext is the same as DeleteMetricFilter with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteMetricFilter for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteMetricFilterWithContext(ctx aws.Context, input *DeleteMetricFilterInput, opts ...request.Option) (*DeleteMetricFilterOutput, error) { - req, out := c.DeleteMetricFilterRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteQueryDefinition = "DeleteQueryDefinition" - -// DeleteQueryDefinitionRequest generates a "aws/request.Request" representing the -// client's request for the DeleteQueryDefinition operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteQueryDefinition for more information on using the DeleteQueryDefinition -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteQueryDefinitionRequest method. -// req, resp := client.DeleteQueryDefinitionRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteQueryDefinition -func (c *CloudWatchLogs) DeleteQueryDefinitionRequest(input *DeleteQueryDefinitionInput) (req *request.Request, output *DeleteQueryDefinitionOutput) { - op := &request.Operation{ - Name: opDeleteQueryDefinition, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteQueryDefinitionInput{} - } - - output = &DeleteQueryDefinitionOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteQueryDefinition API operation for Amazon CloudWatch Logs. -// -// Deletes a saved CloudWatch Logs Insights query definition. A query definition -// contains details about a saved CloudWatch Logs Insights query. -// -// Each DeleteQueryDefinition operation can delete one query definition. -// -// You must have the logs:DeleteQueryDefinition permission to be able to perform -// this operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteQueryDefinition for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteQueryDefinition -func (c *CloudWatchLogs) DeleteQueryDefinition(input *DeleteQueryDefinitionInput) (*DeleteQueryDefinitionOutput, error) { - req, out := c.DeleteQueryDefinitionRequest(input) - return out, req.Send() -} - -// DeleteQueryDefinitionWithContext is the same as DeleteQueryDefinition with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteQueryDefinition for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteQueryDefinitionWithContext(ctx aws.Context, input *DeleteQueryDefinitionInput, opts ...request.Option) (*DeleteQueryDefinitionOutput, error) { - req, out := c.DeleteQueryDefinitionRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteResourcePolicy = "DeleteResourcePolicy" - -// DeleteResourcePolicyRequest generates a "aws/request.Request" representing the -// client's request for the DeleteResourcePolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteResourcePolicy for more information on using the DeleteResourcePolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteResourcePolicyRequest method. -// req, resp := client.DeleteResourcePolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteResourcePolicy -func (c *CloudWatchLogs) DeleteResourcePolicyRequest(input *DeleteResourcePolicyInput) (req *request.Request, output *DeleteResourcePolicyOutput) { - op := &request.Operation{ - Name: opDeleteResourcePolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteResourcePolicyInput{} - } - - output = &DeleteResourcePolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteResourcePolicy API operation for Amazon CloudWatch Logs. -// -// Deletes a resource policy from this account. This revokes the access of the -// identities in that policy to put log events to this account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteResourcePolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteResourcePolicy -func (c *CloudWatchLogs) DeleteResourcePolicy(input *DeleteResourcePolicyInput) (*DeleteResourcePolicyOutput, error) { - req, out := c.DeleteResourcePolicyRequest(input) - return out, req.Send() -} - -// DeleteResourcePolicyWithContext is the same as DeleteResourcePolicy with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteResourcePolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteResourcePolicyWithContext(ctx aws.Context, input *DeleteResourcePolicyInput, opts ...request.Option) (*DeleteResourcePolicyOutput, error) { - req, out := c.DeleteResourcePolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteRetentionPolicy = "DeleteRetentionPolicy" - -// DeleteRetentionPolicyRequest generates a "aws/request.Request" representing the -// client's request for the DeleteRetentionPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteRetentionPolicy for more information on using the DeleteRetentionPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteRetentionPolicyRequest method. -// req, resp := client.DeleteRetentionPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteRetentionPolicy -func (c *CloudWatchLogs) DeleteRetentionPolicyRequest(input *DeleteRetentionPolicyInput) (req *request.Request, output *DeleteRetentionPolicyOutput) { - op := &request.Operation{ - Name: opDeleteRetentionPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteRetentionPolicyInput{} - } - - output = &DeleteRetentionPolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteRetentionPolicy API operation for Amazon CloudWatch Logs. -// -// Deletes the specified retention policy. -// -// Log events do not expire if they belong to log groups without a retention -// policy. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteRetentionPolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteRetentionPolicy -func (c *CloudWatchLogs) DeleteRetentionPolicy(input *DeleteRetentionPolicyInput) (*DeleteRetentionPolicyOutput, error) { - req, out := c.DeleteRetentionPolicyRequest(input) - return out, req.Send() -} - -// DeleteRetentionPolicyWithContext is the same as DeleteRetentionPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteRetentionPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteRetentionPolicyWithContext(ctx aws.Context, input *DeleteRetentionPolicyInput, opts ...request.Option) (*DeleteRetentionPolicyOutput, error) { - req, out := c.DeleteRetentionPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteSubscriptionFilter = "DeleteSubscriptionFilter" - -// DeleteSubscriptionFilterRequest generates a "aws/request.Request" representing the -// client's request for the DeleteSubscriptionFilter operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteSubscriptionFilter for more information on using the DeleteSubscriptionFilter -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DeleteSubscriptionFilterRequest method. -// req, resp := client.DeleteSubscriptionFilterRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteSubscriptionFilter -func (c *CloudWatchLogs) DeleteSubscriptionFilterRequest(input *DeleteSubscriptionFilterInput) (req *request.Request, output *DeleteSubscriptionFilterOutput) { - op := &request.Operation{ - Name: opDeleteSubscriptionFilter, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteSubscriptionFilterInput{} - } - - output = &DeleteSubscriptionFilterOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteSubscriptionFilter API operation for Amazon CloudWatch Logs. -// -// Deletes the specified subscription filter. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DeleteSubscriptionFilter for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteSubscriptionFilter -func (c *CloudWatchLogs) DeleteSubscriptionFilter(input *DeleteSubscriptionFilterInput) (*DeleteSubscriptionFilterOutput, error) { - req, out := c.DeleteSubscriptionFilterRequest(input) - return out, req.Send() -} - -// DeleteSubscriptionFilterWithContext is the same as DeleteSubscriptionFilter with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteSubscriptionFilter for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DeleteSubscriptionFilterWithContext(ctx aws.Context, input *DeleteSubscriptionFilterInput, opts ...request.Option) (*DeleteSubscriptionFilterOutput, error) { - req, out := c.DeleteSubscriptionFilterRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDescribeAccountPolicies = "DescribeAccountPolicies" - -// DescribeAccountPoliciesRequest generates a "aws/request.Request" representing the -// client's request for the DescribeAccountPolicies operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeAccountPolicies for more information on using the DescribeAccountPolicies -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeAccountPoliciesRequest method. -// req, resp := client.DescribeAccountPoliciesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeAccountPolicies -func (c *CloudWatchLogs) DescribeAccountPoliciesRequest(input *DescribeAccountPoliciesInput) (req *request.Request, output *DescribeAccountPoliciesOutput) { - op := &request.Operation{ - Name: opDescribeAccountPolicies, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DescribeAccountPoliciesInput{} - } - - output = &DescribeAccountPoliciesOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeAccountPolicies API operation for Amazon CloudWatch Logs. -// -// Returns a list of all CloudWatch Logs account policies in the account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeAccountPolicies for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeAccountPolicies -func (c *CloudWatchLogs) DescribeAccountPolicies(input *DescribeAccountPoliciesInput) (*DescribeAccountPoliciesOutput, error) { - req, out := c.DescribeAccountPoliciesRequest(input) - return out, req.Send() -} - -// DescribeAccountPoliciesWithContext is the same as DescribeAccountPolicies with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeAccountPolicies for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeAccountPoliciesWithContext(ctx aws.Context, input *DescribeAccountPoliciesInput, opts ...request.Option) (*DescribeAccountPoliciesOutput, error) { - req, out := c.DescribeAccountPoliciesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDescribeDeliveries = "DescribeDeliveries" - -// DescribeDeliveriesRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDeliveries operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeDeliveries for more information on using the DescribeDeliveries -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeDeliveriesRequest method. -// req, resp := client.DescribeDeliveriesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDeliveries -func (c *CloudWatchLogs) DescribeDeliveriesRequest(input *DescribeDeliveriesInput) (req *request.Request, output *DescribeDeliveriesOutput) { - op := &request.Operation{ - Name: opDescribeDeliveries, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &DescribeDeliveriesInput{} - } - - output = &DescribeDeliveriesOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeDeliveries API operation for Amazon CloudWatch Logs. -// -// Retrieves a list of the deliveries that have been created in the account. -// -// A delivery is a connection between a delivery source (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliverySource.html) -// and a delivery destination (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestination.html). -// -// A delivery source represents an Amazon Web Services resource that sends logs -// to an logs delivery destination. The destination can be CloudWatch Logs, -// Amazon S3, or Firehose. Only some Amazon Web Services services support being -// configured as a delivery source. These services are listed in Enable logging -// from Amazon Web Services services. (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html) -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeDeliveries for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDeliveries -func (c *CloudWatchLogs) DescribeDeliveries(input *DescribeDeliveriesInput) (*DescribeDeliveriesOutput, error) { - req, out := c.DescribeDeliveriesRequest(input) - return out, req.Send() -} - -// DescribeDeliveriesWithContext is the same as DescribeDeliveries with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeDeliveries for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeDeliveriesWithContext(ctx aws.Context, input *DescribeDeliveriesInput, opts ...request.Option) (*DescribeDeliveriesOutput, error) { - req, out := c.DescribeDeliveriesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// DescribeDeliveriesPages iterates over the pages of a DescribeDeliveries operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See DescribeDeliveries method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a DescribeDeliveries operation. -// pageNum := 0 -// err := client.DescribeDeliveriesPages(params, -// func(page *cloudwatchlogs.DescribeDeliveriesOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) DescribeDeliveriesPages(input *DescribeDeliveriesInput, fn func(*DescribeDeliveriesOutput, bool) bool) error { - return c.DescribeDeliveriesPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// DescribeDeliveriesPagesWithContext same as DescribeDeliveriesPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeDeliveriesPagesWithContext(ctx aws.Context, input *DescribeDeliveriesInput, fn func(*DescribeDeliveriesOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *DescribeDeliveriesInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.DescribeDeliveriesRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*DescribeDeliveriesOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opDescribeDeliveryDestinations = "DescribeDeliveryDestinations" - -// DescribeDeliveryDestinationsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDeliveryDestinations operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeDeliveryDestinations for more information on using the DescribeDeliveryDestinations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeDeliveryDestinationsRequest method. -// req, resp := client.DescribeDeliveryDestinationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDeliveryDestinations -func (c *CloudWatchLogs) DescribeDeliveryDestinationsRequest(input *DescribeDeliveryDestinationsInput) (req *request.Request, output *DescribeDeliveryDestinationsOutput) { - op := &request.Operation{ - Name: opDescribeDeliveryDestinations, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &DescribeDeliveryDestinationsInput{} - } - - output = &DescribeDeliveryDestinationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeDeliveryDestinations API operation for Amazon CloudWatch Logs. -// -// Retrieves a list of the delivery destinations that have been created in the -// account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeDeliveryDestinations for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDeliveryDestinations -func (c *CloudWatchLogs) DescribeDeliveryDestinations(input *DescribeDeliveryDestinationsInput) (*DescribeDeliveryDestinationsOutput, error) { - req, out := c.DescribeDeliveryDestinationsRequest(input) - return out, req.Send() -} - -// DescribeDeliveryDestinationsWithContext is the same as DescribeDeliveryDestinations with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeDeliveryDestinations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeDeliveryDestinationsWithContext(ctx aws.Context, input *DescribeDeliveryDestinationsInput, opts ...request.Option) (*DescribeDeliveryDestinationsOutput, error) { - req, out := c.DescribeDeliveryDestinationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// DescribeDeliveryDestinationsPages iterates over the pages of a DescribeDeliveryDestinations operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See DescribeDeliveryDestinations method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a DescribeDeliveryDestinations operation. -// pageNum := 0 -// err := client.DescribeDeliveryDestinationsPages(params, -// func(page *cloudwatchlogs.DescribeDeliveryDestinationsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) DescribeDeliveryDestinationsPages(input *DescribeDeliveryDestinationsInput, fn func(*DescribeDeliveryDestinationsOutput, bool) bool) error { - return c.DescribeDeliveryDestinationsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// DescribeDeliveryDestinationsPagesWithContext same as DescribeDeliveryDestinationsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeDeliveryDestinationsPagesWithContext(ctx aws.Context, input *DescribeDeliveryDestinationsInput, fn func(*DescribeDeliveryDestinationsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *DescribeDeliveryDestinationsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.DescribeDeliveryDestinationsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*DescribeDeliveryDestinationsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opDescribeDeliverySources = "DescribeDeliverySources" - -// DescribeDeliverySourcesRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDeliverySources operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeDeliverySources for more information on using the DescribeDeliverySources -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeDeliverySourcesRequest method. -// req, resp := client.DescribeDeliverySourcesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDeliverySources -func (c *CloudWatchLogs) DescribeDeliverySourcesRequest(input *DescribeDeliverySourcesInput) (req *request.Request, output *DescribeDeliverySourcesOutput) { - op := &request.Operation{ - Name: opDescribeDeliverySources, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &DescribeDeliverySourcesInput{} - } - - output = &DescribeDeliverySourcesOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeDeliverySources API operation for Amazon CloudWatch Logs. -// -// Retrieves a list of the delivery sources that have been created in the account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeDeliverySources for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDeliverySources -func (c *CloudWatchLogs) DescribeDeliverySources(input *DescribeDeliverySourcesInput) (*DescribeDeliverySourcesOutput, error) { - req, out := c.DescribeDeliverySourcesRequest(input) - return out, req.Send() -} - -// DescribeDeliverySourcesWithContext is the same as DescribeDeliverySources with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeDeliverySources for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeDeliverySourcesWithContext(ctx aws.Context, input *DescribeDeliverySourcesInput, opts ...request.Option) (*DescribeDeliverySourcesOutput, error) { - req, out := c.DescribeDeliverySourcesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// DescribeDeliverySourcesPages iterates over the pages of a DescribeDeliverySources operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See DescribeDeliverySources method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a DescribeDeliverySources operation. -// pageNum := 0 -// err := client.DescribeDeliverySourcesPages(params, -// func(page *cloudwatchlogs.DescribeDeliverySourcesOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) DescribeDeliverySourcesPages(input *DescribeDeliverySourcesInput, fn func(*DescribeDeliverySourcesOutput, bool) bool) error { - return c.DescribeDeliverySourcesPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// DescribeDeliverySourcesPagesWithContext same as DescribeDeliverySourcesPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeDeliverySourcesPagesWithContext(ctx aws.Context, input *DescribeDeliverySourcesInput, fn func(*DescribeDeliverySourcesOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *DescribeDeliverySourcesInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.DescribeDeliverySourcesRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*DescribeDeliverySourcesOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opDescribeDestinations = "DescribeDestinations" - -// DescribeDestinationsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDestinations operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeDestinations for more information on using the DescribeDestinations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeDestinationsRequest method. -// req, resp := client.DescribeDestinationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDestinations -func (c *CloudWatchLogs) DescribeDestinationsRequest(input *DescribeDestinationsInput) (req *request.Request, output *DescribeDestinationsOutput) { - op := &request.Operation{ - Name: opDescribeDestinations, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &DescribeDestinationsInput{} - } - - output = &DescribeDestinationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeDestinations API operation for Amazon CloudWatch Logs. -// -// Lists all your destinations. The results are ASCII-sorted by destination -// name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeDestinations for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeDestinations -func (c *CloudWatchLogs) DescribeDestinations(input *DescribeDestinationsInput) (*DescribeDestinationsOutput, error) { - req, out := c.DescribeDestinationsRequest(input) - return out, req.Send() -} - -// DescribeDestinationsWithContext is the same as DescribeDestinations with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeDestinations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeDestinationsWithContext(ctx aws.Context, input *DescribeDestinationsInput, opts ...request.Option) (*DescribeDestinationsOutput, error) { - req, out := c.DescribeDestinationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// DescribeDestinationsPages iterates over the pages of a DescribeDestinations operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See DescribeDestinations method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a DescribeDestinations operation. -// pageNum := 0 -// err := client.DescribeDestinationsPages(params, -// func(page *cloudwatchlogs.DescribeDestinationsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) DescribeDestinationsPages(input *DescribeDestinationsInput, fn func(*DescribeDestinationsOutput, bool) bool) error { - return c.DescribeDestinationsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// DescribeDestinationsPagesWithContext same as DescribeDestinationsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeDestinationsPagesWithContext(ctx aws.Context, input *DescribeDestinationsInput, fn func(*DescribeDestinationsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *DescribeDestinationsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.DescribeDestinationsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*DescribeDestinationsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opDescribeExportTasks = "DescribeExportTasks" - -// DescribeExportTasksRequest generates a "aws/request.Request" representing the -// client's request for the DescribeExportTasks operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeExportTasks for more information on using the DescribeExportTasks -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeExportTasksRequest method. -// req, resp := client.DescribeExportTasksRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeExportTasks -func (c *CloudWatchLogs) DescribeExportTasksRequest(input *DescribeExportTasksInput) (req *request.Request, output *DescribeExportTasksOutput) { - op := &request.Operation{ - Name: opDescribeExportTasks, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DescribeExportTasksInput{} - } - - output = &DescribeExportTasksOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeExportTasks API operation for Amazon CloudWatch Logs. -// -// Lists the specified export tasks. You can list all your export tasks or filter -// the results based on task ID or task status. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeExportTasks for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeExportTasks -func (c *CloudWatchLogs) DescribeExportTasks(input *DescribeExportTasksInput) (*DescribeExportTasksOutput, error) { - req, out := c.DescribeExportTasksRequest(input) - return out, req.Send() -} - -// DescribeExportTasksWithContext is the same as DescribeExportTasks with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeExportTasks for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeExportTasksWithContext(ctx aws.Context, input *DescribeExportTasksInput, opts ...request.Option) (*DescribeExportTasksOutput, error) { - req, out := c.DescribeExportTasksRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDescribeLogGroups = "DescribeLogGroups" - -// DescribeLogGroupsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeLogGroups operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeLogGroups for more information on using the DescribeLogGroups -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeLogGroupsRequest method. -// req, resp := client.DescribeLogGroupsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeLogGroups -func (c *CloudWatchLogs) DescribeLogGroupsRequest(input *DescribeLogGroupsInput) (req *request.Request, output *DescribeLogGroupsOutput) { - op := &request.Operation{ - Name: opDescribeLogGroups, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &DescribeLogGroupsInput{} - } - - output = &DescribeLogGroupsOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeLogGroups API operation for Amazon CloudWatch Logs. -// -// Lists the specified log groups. You can list all your log groups or filter -// the results by prefix. The results are ASCII-sorted by log group name. -// -// CloudWatch Logs doesn’t support IAM policies that control access to the -// DescribeLogGroups action by using the aws:ResourceTag/key-name condition -// key. Other CloudWatch Logs actions do support the use of the aws:ResourceTag/key-name -// condition key to control access. For more information about using tags to -// control access, see Controlling access to Amazon Web Services resources using -// tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html). -// -// If you are using CloudWatch cross-account observability, you can use this -// operation in a monitoring account and view data from the linked source accounts. -// For more information, see CloudWatch cross-account observability (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeLogGroups for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeLogGroups -func (c *CloudWatchLogs) DescribeLogGroups(input *DescribeLogGroupsInput) (*DescribeLogGroupsOutput, error) { - req, out := c.DescribeLogGroupsRequest(input) - return out, req.Send() -} - -// DescribeLogGroupsWithContext is the same as DescribeLogGroups with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeLogGroups for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeLogGroupsWithContext(ctx aws.Context, input *DescribeLogGroupsInput, opts ...request.Option) (*DescribeLogGroupsOutput, error) { - req, out := c.DescribeLogGroupsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// DescribeLogGroupsPages iterates over the pages of a DescribeLogGroups operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See DescribeLogGroups method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a DescribeLogGroups operation. -// pageNum := 0 -// err := client.DescribeLogGroupsPages(params, -// func(page *cloudwatchlogs.DescribeLogGroupsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) DescribeLogGroupsPages(input *DescribeLogGroupsInput, fn func(*DescribeLogGroupsOutput, bool) bool) error { - return c.DescribeLogGroupsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// DescribeLogGroupsPagesWithContext same as DescribeLogGroupsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeLogGroupsPagesWithContext(ctx aws.Context, input *DescribeLogGroupsInput, fn func(*DescribeLogGroupsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *DescribeLogGroupsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.DescribeLogGroupsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*DescribeLogGroupsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opDescribeLogStreams = "DescribeLogStreams" - -// DescribeLogStreamsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeLogStreams operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeLogStreams for more information on using the DescribeLogStreams -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeLogStreamsRequest method. -// req, resp := client.DescribeLogStreamsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeLogStreams -func (c *CloudWatchLogs) DescribeLogStreamsRequest(input *DescribeLogStreamsInput) (req *request.Request, output *DescribeLogStreamsOutput) { - op := &request.Operation{ - Name: opDescribeLogStreams, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &DescribeLogStreamsInput{} - } - - output = &DescribeLogStreamsOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeLogStreams API operation for Amazon CloudWatch Logs. -// -// Lists the log streams for the specified log group. You can list all the log -// streams or filter the results by prefix. You can also control how the results -// are ordered. -// -// You can specify the log group to search by using either logGroupIdentifier -// or logGroupName. You must include one of these two parameters, but you can't -// include both. -// -// This operation has a limit of five transactions per second, after which transactions -// are throttled. -// -// If you are using CloudWatch cross-account observability, you can use this -// operation in a monitoring account and view data from the linked source accounts. -// For more information, see CloudWatch cross-account observability (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeLogStreams for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeLogStreams -func (c *CloudWatchLogs) DescribeLogStreams(input *DescribeLogStreamsInput) (*DescribeLogStreamsOutput, error) { - req, out := c.DescribeLogStreamsRequest(input) - return out, req.Send() -} - -// DescribeLogStreamsWithContext is the same as DescribeLogStreams with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeLogStreams for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeLogStreamsWithContext(ctx aws.Context, input *DescribeLogStreamsInput, opts ...request.Option) (*DescribeLogStreamsOutput, error) { - req, out := c.DescribeLogStreamsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// DescribeLogStreamsPages iterates over the pages of a DescribeLogStreams operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See DescribeLogStreams method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a DescribeLogStreams operation. -// pageNum := 0 -// err := client.DescribeLogStreamsPages(params, -// func(page *cloudwatchlogs.DescribeLogStreamsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) DescribeLogStreamsPages(input *DescribeLogStreamsInput, fn func(*DescribeLogStreamsOutput, bool) bool) error { - return c.DescribeLogStreamsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// DescribeLogStreamsPagesWithContext same as DescribeLogStreamsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeLogStreamsPagesWithContext(ctx aws.Context, input *DescribeLogStreamsInput, fn func(*DescribeLogStreamsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *DescribeLogStreamsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.DescribeLogStreamsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*DescribeLogStreamsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opDescribeMetricFilters = "DescribeMetricFilters" - -// DescribeMetricFiltersRequest generates a "aws/request.Request" representing the -// client's request for the DescribeMetricFilters operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeMetricFilters for more information on using the DescribeMetricFilters -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeMetricFiltersRequest method. -// req, resp := client.DescribeMetricFiltersRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeMetricFilters -func (c *CloudWatchLogs) DescribeMetricFiltersRequest(input *DescribeMetricFiltersInput) (req *request.Request, output *DescribeMetricFiltersOutput) { - op := &request.Operation{ - Name: opDescribeMetricFilters, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &DescribeMetricFiltersInput{} - } - - output = &DescribeMetricFiltersOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeMetricFilters API operation for Amazon CloudWatch Logs. -// -// Lists the specified metric filters. You can list all of the metric filters -// or filter the results by log name, prefix, metric name, or metric namespace. -// The results are ASCII-sorted by filter name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeMetricFilters for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeMetricFilters -func (c *CloudWatchLogs) DescribeMetricFilters(input *DescribeMetricFiltersInput) (*DescribeMetricFiltersOutput, error) { - req, out := c.DescribeMetricFiltersRequest(input) - return out, req.Send() -} - -// DescribeMetricFiltersWithContext is the same as DescribeMetricFilters with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeMetricFilters for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeMetricFiltersWithContext(ctx aws.Context, input *DescribeMetricFiltersInput, opts ...request.Option) (*DescribeMetricFiltersOutput, error) { - req, out := c.DescribeMetricFiltersRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// DescribeMetricFiltersPages iterates over the pages of a DescribeMetricFilters operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See DescribeMetricFilters method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a DescribeMetricFilters operation. -// pageNum := 0 -// err := client.DescribeMetricFiltersPages(params, -// func(page *cloudwatchlogs.DescribeMetricFiltersOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) DescribeMetricFiltersPages(input *DescribeMetricFiltersInput, fn func(*DescribeMetricFiltersOutput, bool) bool) error { - return c.DescribeMetricFiltersPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// DescribeMetricFiltersPagesWithContext same as DescribeMetricFiltersPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeMetricFiltersPagesWithContext(ctx aws.Context, input *DescribeMetricFiltersInput, fn func(*DescribeMetricFiltersOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *DescribeMetricFiltersInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.DescribeMetricFiltersRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*DescribeMetricFiltersOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opDescribeQueries = "DescribeQueries" - -// DescribeQueriesRequest generates a "aws/request.Request" representing the -// client's request for the DescribeQueries operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeQueries for more information on using the DescribeQueries -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeQueriesRequest method. -// req, resp := client.DescribeQueriesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeQueries -func (c *CloudWatchLogs) DescribeQueriesRequest(input *DescribeQueriesInput) (req *request.Request, output *DescribeQueriesOutput) { - op := &request.Operation{ - Name: opDescribeQueries, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DescribeQueriesInput{} - } - - output = &DescribeQueriesOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeQueries API operation for Amazon CloudWatch Logs. -// -// Returns a list of CloudWatch Logs Insights queries that are scheduled, running, -// or have been run recently in this account. You can request all queries or -// limit it to queries of a specific log group or queries with a certain status. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeQueries for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeQueries -func (c *CloudWatchLogs) DescribeQueries(input *DescribeQueriesInput) (*DescribeQueriesOutput, error) { - req, out := c.DescribeQueriesRequest(input) - return out, req.Send() -} - -// DescribeQueriesWithContext is the same as DescribeQueries with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeQueries for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeQueriesWithContext(ctx aws.Context, input *DescribeQueriesInput, opts ...request.Option) (*DescribeQueriesOutput, error) { - req, out := c.DescribeQueriesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDescribeQueryDefinitions = "DescribeQueryDefinitions" - -// DescribeQueryDefinitionsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeQueryDefinitions operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeQueryDefinitions for more information on using the DescribeQueryDefinitions -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeQueryDefinitionsRequest method. -// req, resp := client.DescribeQueryDefinitionsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeQueryDefinitions -func (c *CloudWatchLogs) DescribeQueryDefinitionsRequest(input *DescribeQueryDefinitionsInput) (req *request.Request, output *DescribeQueryDefinitionsOutput) { - op := &request.Operation{ - Name: opDescribeQueryDefinitions, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DescribeQueryDefinitionsInput{} - } - - output = &DescribeQueryDefinitionsOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeQueryDefinitions API operation for Amazon CloudWatch Logs. -// -// This operation returns a paginated list of your saved CloudWatch Logs Insights -// query definitions. You can retrieve query definitions from the current account -// or from a source account that is linked to the current account. -// -// You can use the queryDefinitionNamePrefix parameter to limit the results -// to only the query definitions that have names that start with a certain string. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeQueryDefinitions for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeQueryDefinitions -func (c *CloudWatchLogs) DescribeQueryDefinitions(input *DescribeQueryDefinitionsInput) (*DescribeQueryDefinitionsOutput, error) { - req, out := c.DescribeQueryDefinitionsRequest(input) - return out, req.Send() -} - -// DescribeQueryDefinitionsWithContext is the same as DescribeQueryDefinitions with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeQueryDefinitions for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeQueryDefinitionsWithContext(ctx aws.Context, input *DescribeQueryDefinitionsInput, opts ...request.Option) (*DescribeQueryDefinitionsOutput, error) { - req, out := c.DescribeQueryDefinitionsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDescribeResourcePolicies = "DescribeResourcePolicies" - -// DescribeResourcePoliciesRequest generates a "aws/request.Request" representing the -// client's request for the DescribeResourcePolicies operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeResourcePolicies for more information on using the DescribeResourcePolicies -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeResourcePoliciesRequest method. -// req, resp := client.DescribeResourcePoliciesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeResourcePolicies -func (c *CloudWatchLogs) DescribeResourcePoliciesRequest(input *DescribeResourcePoliciesInput) (req *request.Request, output *DescribeResourcePoliciesOutput) { - op := &request.Operation{ - Name: opDescribeResourcePolicies, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DescribeResourcePoliciesInput{} - } - - output = &DescribeResourcePoliciesOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeResourcePolicies API operation for Amazon CloudWatch Logs. -// -// Lists the resource policies in this account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeResourcePolicies for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeResourcePolicies -func (c *CloudWatchLogs) DescribeResourcePolicies(input *DescribeResourcePoliciesInput) (*DescribeResourcePoliciesOutput, error) { - req, out := c.DescribeResourcePoliciesRequest(input) - return out, req.Send() -} - -// DescribeResourcePoliciesWithContext is the same as DescribeResourcePolicies with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeResourcePolicies for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeResourcePoliciesWithContext(ctx aws.Context, input *DescribeResourcePoliciesInput, opts ...request.Option) (*DescribeResourcePoliciesOutput, error) { - req, out := c.DescribeResourcePoliciesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDescribeSubscriptionFilters = "DescribeSubscriptionFilters" - -// DescribeSubscriptionFiltersRequest generates a "aws/request.Request" representing the -// client's request for the DescribeSubscriptionFilters operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DescribeSubscriptionFilters for more information on using the DescribeSubscriptionFilters -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DescribeSubscriptionFiltersRequest method. -// req, resp := client.DescribeSubscriptionFiltersRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeSubscriptionFilters -func (c *CloudWatchLogs) DescribeSubscriptionFiltersRequest(input *DescribeSubscriptionFiltersInput) (req *request.Request, output *DescribeSubscriptionFiltersOutput) { - op := &request.Operation{ - Name: opDescribeSubscriptionFilters, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &DescribeSubscriptionFiltersInput{} - } - - output = &DescribeSubscriptionFiltersOutput{} - req = c.newRequest(op, input, output) - return -} - -// DescribeSubscriptionFilters API operation for Amazon CloudWatch Logs. -// -// Lists the subscription filters for the specified log group. You can list -// all the subscription filters or filter the results by prefix. The results -// are ASCII-sorted by filter name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DescribeSubscriptionFilters for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeSubscriptionFilters -func (c *CloudWatchLogs) DescribeSubscriptionFilters(input *DescribeSubscriptionFiltersInput) (*DescribeSubscriptionFiltersOutput, error) { - req, out := c.DescribeSubscriptionFiltersRequest(input) - return out, req.Send() -} - -// DescribeSubscriptionFiltersWithContext is the same as DescribeSubscriptionFilters with the addition of -// the ability to pass a context and additional request options. -// -// See DescribeSubscriptionFilters for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeSubscriptionFiltersWithContext(ctx aws.Context, input *DescribeSubscriptionFiltersInput, opts ...request.Option) (*DescribeSubscriptionFiltersOutput, error) { - req, out := c.DescribeSubscriptionFiltersRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// DescribeSubscriptionFiltersPages iterates over the pages of a DescribeSubscriptionFilters operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See DescribeSubscriptionFilters method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a DescribeSubscriptionFilters operation. -// pageNum := 0 -// err := client.DescribeSubscriptionFiltersPages(params, -// func(page *cloudwatchlogs.DescribeSubscriptionFiltersOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) DescribeSubscriptionFiltersPages(input *DescribeSubscriptionFiltersInput, fn func(*DescribeSubscriptionFiltersOutput, bool) bool) error { - return c.DescribeSubscriptionFiltersPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// DescribeSubscriptionFiltersPagesWithContext same as DescribeSubscriptionFiltersPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DescribeSubscriptionFiltersPagesWithContext(ctx aws.Context, input *DescribeSubscriptionFiltersInput, fn func(*DescribeSubscriptionFiltersOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *DescribeSubscriptionFiltersInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.DescribeSubscriptionFiltersRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*DescribeSubscriptionFiltersOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opDisassociateKmsKey = "DisassociateKmsKey" - -// DisassociateKmsKeyRequest generates a "aws/request.Request" representing the -// client's request for the DisassociateKmsKey operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DisassociateKmsKey for more information on using the DisassociateKmsKey -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DisassociateKmsKeyRequest method. -// req, resp := client.DisassociateKmsKeyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DisassociateKmsKey -func (c *CloudWatchLogs) DisassociateKmsKeyRequest(input *DisassociateKmsKeyInput) (req *request.Request, output *DisassociateKmsKeyOutput) { - op := &request.Operation{ - Name: opDisassociateKmsKey, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DisassociateKmsKeyInput{} - } - - output = &DisassociateKmsKeyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// DisassociateKmsKey API operation for Amazon CloudWatch Logs. -// -// Disassociates the specified KMS key from the specified log group or from -// all CloudWatch Logs Insights query results in the account. -// -// When you use DisassociateKmsKey, you specify either the logGroupName parameter -// or the resourceIdentifier parameter. You can't specify both of those parameters -// in the same operation. -// -// - Specify the logGroupName parameter to stop using the KMS key to encrypt -// future log events ingested and stored in the log group. Instead, they -// will be encrypted with the default CloudWatch Logs method. The log events -// that were ingested while the key was associated with the log group are -// still encrypted with that key. Therefore, CloudWatch Logs will need permissions -// for the key whenever that data is accessed. -// -// - Specify the resourceIdentifier parameter with the query-result resource -// to stop using the KMS key to encrypt the results of all future StartQuery -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html) -// operations in the account. They will instead be encrypted with the default -// CloudWatch Logs method. The results from queries that ran while the key -// was associated with the account are still encrypted with that key. Therefore, -// CloudWatch Logs will need permissions for the key whenever that data is -// accessed. -// -// It can take up to 5 minutes for this operation to take effect. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation DisassociateKmsKey for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DisassociateKmsKey -func (c *CloudWatchLogs) DisassociateKmsKey(input *DisassociateKmsKeyInput) (*DisassociateKmsKeyOutput, error) { - req, out := c.DisassociateKmsKeyRequest(input) - return out, req.Send() -} - -// DisassociateKmsKeyWithContext is the same as DisassociateKmsKey with the addition of -// the ability to pass a context and additional request options. -// -// See DisassociateKmsKey for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) DisassociateKmsKeyWithContext(ctx aws.Context, input *DisassociateKmsKeyInput, opts ...request.Option) (*DisassociateKmsKeyOutput, error) { - req, out := c.DisassociateKmsKeyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opFilterLogEvents = "FilterLogEvents" - -// FilterLogEventsRequest generates a "aws/request.Request" representing the -// client's request for the FilterLogEvents operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See FilterLogEvents for more information on using the FilterLogEvents -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the FilterLogEventsRequest method. -// req, resp := client.FilterLogEventsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/FilterLogEvents -func (c *CloudWatchLogs) FilterLogEventsRequest(input *FilterLogEventsInput) (req *request.Request, output *FilterLogEventsOutput) { - op := &request.Operation{ - Name: opFilterLogEvents, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &FilterLogEventsInput{} - } - - output = &FilterLogEventsOutput{} - req = c.newRequest(op, input, output) - return -} - -// FilterLogEvents API operation for Amazon CloudWatch Logs. -// -// Lists log events from the specified log group. You can list all the log events -// or filter the results using a filter pattern, a time range, and the name -// of the log stream. -// -// You must have the logs:FilterLogEvents permission to perform this operation. -// -// You can specify the log group to search by using either logGroupIdentifier -// or logGroupName. You must include one of these two parameters, but you can't -// include both. -// -// By default, this operation returns as many log events as can fit in 1 MB -// (up to 10,000 log events) or all the events found within the specified time -// range. If the results include a token, that means there are more log events -// available. You can get additional results by specifying the token in a subsequent -// call. This operation can return empty results while there are more log events -// available through the token. -// -// The returned log events are sorted by event timestamp, the timestamp when -// the event was ingested by CloudWatch Logs, and the ID of the PutLogEvents -// request. -// -// If you are using CloudWatch cross-account observability, you can use this -// operation in a monitoring account and view data from the linked source accounts. -// For more information, see CloudWatch cross-account observability (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation FilterLogEvents for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/FilterLogEvents -func (c *CloudWatchLogs) FilterLogEvents(input *FilterLogEventsInput) (*FilterLogEventsOutput, error) { - req, out := c.FilterLogEventsRequest(input) - return out, req.Send() -} - -// FilterLogEventsWithContext is the same as FilterLogEvents with the addition of -// the ability to pass a context and additional request options. -// -// See FilterLogEvents for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) FilterLogEventsWithContext(ctx aws.Context, input *FilterLogEventsInput, opts ...request.Option) (*FilterLogEventsOutput, error) { - req, out := c.FilterLogEventsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// FilterLogEventsPages iterates over the pages of a FilterLogEvents operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See FilterLogEvents method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a FilterLogEvents operation. -// pageNum := 0 -// err := client.FilterLogEventsPages(params, -// func(page *cloudwatchlogs.FilterLogEventsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) FilterLogEventsPages(input *FilterLogEventsInput, fn func(*FilterLogEventsOutput, bool) bool) error { - return c.FilterLogEventsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// FilterLogEventsPagesWithContext same as FilterLogEventsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) FilterLogEventsPagesWithContext(ctx aws.Context, input *FilterLogEventsInput, fn func(*FilterLogEventsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *FilterLogEventsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.FilterLogEventsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*FilterLogEventsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opGetDataProtectionPolicy = "GetDataProtectionPolicy" - -// GetDataProtectionPolicyRequest generates a "aws/request.Request" representing the -// client's request for the GetDataProtectionPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDataProtectionPolicy for more information on using the GetDataProtectionPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetDataProtectionPolicyRequest method. -// req, resp := client.GetDataProtectionPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDataProtectionPolicy -func (c *CloudWatchLogs) GetDataProtectionPolicyRequest(input *GetDataProtectionPolicyInput) (req *request.Request, output *GetDataProtectionPolicyOutput) { - op := &request.Operation{ - Name: opGetDataProtectionPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDataProtectionPolicyInput{} - } - - output = &GetDataProtectionPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDataProtectionPolicy API operation for Amazon CloudWatch Logs. -// -// Returns information about a log group data protection policy. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetDataProtectionPolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDataProtectionPolicy -func (c *CloudWatchLogs) GetDataProtectionPolicy(input *GetDataProtectionPolicyInput) (*GetDataProtectionPolicyOutput, error) { - req, out := c.GetDataProtectionPolicyRequest(input) - return out, req.Send() -} - -// GetDataProtectionPolicyWithContext is the same as GetDataProtectionPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See GetDataProtectionPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetDataProtectionPolicyWithContext(ctx aws.Context, input *GetDataProtectionPolicyInput, opts ...request.Option) (*GetDataProtectionPolicyOutput, error) { - req, out := c.GetDataProtectionPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDelivery = "GetDelivery" - -// GetDeliveryRequest generates a "aws/request.Request" representing the -// client's request for the GetDelivery operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDelivery for more information on using the GetDelivery -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetDeliveryRequest method. -// req, resp := client.GetDeliveryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDelivery -func (c *CloudWatchLogs) GetDeliveryRequest(input *GetDeliveryInput) (req *request.Request, output *GetDeliveryOutput) { - op := &request.Operation{ - Name: opGetDelivery, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDeliveryInput{} - } - - output = &GetDeliveryOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDelivery API operation for Amazon CloudWatch Logs. -// -// Returns complete information about one logical delivery. A delivery is a -// connection between a delivery source (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliverySource.html) -// and a delivery destination (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestination.html). -// -// A delivery source represents an Amazon Web Services resource that sends logs -// to an logs delivery destination. The destination can be CloudWatch Logs, -// Amazon S3, or Firehose. Only some Amazon Web Services services support being -// configured as a delivery source. These services are listed in Enable logging -// from Amazon Web Services services. (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html) -// -// You need to specify the delivery id in this operation. You can find the IDs -// of the deliveries in your account with the DescribeDeliveries (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeDeliveries.html) -// operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetDelivery for usage and error information. -// -// Returned Error Types: -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDelivery -func (c *CloudWatchLogs) GetDelivery(input *GetDeliveryInput) (*GetDeliveryOutput, error) { - req, out := c.GetDeliveryRequest(input) - return out, req.Send() -} - -// GetDeliveryWithContext is the same as GetDelivery with the addition of -// the ability to pass a context and additional request options. -// -// See GetDelivery for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetDeliveryWithContext(ctx aws.Context, input *GetDeliveryInput, opts ...request.Option) (*GetDeliveryOutput, error) { - req, out := c.GetDeliveryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDeliveryDestination = "GetDeliveryDestination" - -// GetDeliveryDestinationRequest generates a "aws/request.Request" representing the -// client's request for the GetDeliveryDestination operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDeliveryDestination for more information on using the GetDeliveryDestination -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetDeliveryDestinationRequest method. -// req, resp := client.GetDeliveryDestinationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDeliveryDestination -func (c *CloudWatchLogs) GetDeliveryDestinationRequest(input *GetDeliveryDestinationInput) (req *request.Request, output *GetDeliveryDestinationOutput) { - op := &request.Operation{ - Name: opGetDeliveryDestination, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDeliveryDestinationInput{} - } - - output = &GetDeliveryDestinationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDeliveryDestination API operation for Amazon CloudWatch Logs. -// -// Retrieves complete information about one delivery destination. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetDeliveryDestination for usage and error information. -// -// Returned Error Types: -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDeliveryDestination -func (c *CloudWatchLogs) GetDeliveryDestination(input *GetDeliveryDestinationInput) (*GetDeliveryDestinationOutput, error) { - req, out := c.GetDeliveryDestinationRequest(input) - return out, req.Send() -} - -// GetDeliveryDestinationWithContext is the same as GetDeliveryDestination with the addition of -// the ability to pass a context and additional request options. -// -// See GetDeliveryDestination for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetDeliveryDestinationWithContext(ctx aws.Context, input *GetDeliveryDestinationInput, opts ...request.Option) (*GetDeliveryDestinationOutput, error) { - req, out := c.GetDeliveryDestinationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDeliveryDestinationPolicy = "GetDeliveryDestinationPolicy" - -// GetDeliveryDestinationPolicyRequest generates a "aws/request.Request" representing the -// client's request for the GetDeliveryDestinationPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDeliveryDestinationPolicy for more information on using the GetDeliveryDestinationPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetDeliveryDestinationPolicyRequest method. -// req, resp := client.GetDeliveryDestinationPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDeliveryDestinationPolicy -func (c *CloudWatchLogs) GetDeliveryDestinationPolicyRequest(input *GetDeliveryDestinationPolicyInput) (req *request.Request, output *GetDeliveryDestinationPolicyOutput) { - op := &request.Operation{ - Name: opGetDeliveryDestinationPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDeliveryDestinationPolicyInput{} - } - - output = &GetDeliveryDestinationPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDeliveryDestinationPolicy API operation for Amazon CloudWatch Logs. -// -// Retrieves the delivery destination policy assigned to the delivery destination -// that you specify. For more information about delivery destinations and their -// policies, see PutDeliveryDestinationPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestinationPolicy.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetDeliveryDestinationPolicy for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDeliveryDestinationPolicy -func (c *CloudWatchLogs) GetDeliveryDestinationPolicy(input *GetDeliveryDestinationPolicyInput) (*GetDeliveryDestinationPolicyOutput, error) { - req, out := c.GetDeliveryDestinationPolicyRequest(input) - return out, req.Send() -} - -// GetDeliveryDestinationPolicyWithContext is the same as GetDeliveryDestinationPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See GetDeliveryDestinationPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetDeliveryDestinationPolicyWithContext(ctx aws.Context, input *GetDeliveryDestinationPolicyInput, opts ...request.Option) (*GetDeliveryDestinationPolicyOutput, error) { - req, out := c.GetDeliveryDestinationPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDeliverySource = "GetDeliverySource" - -// GetDeliverySourceRequest generates a "aws/request.Request" representing the -// client's request for the GetDeliverySource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDeliverySource for more information on using the GetDeliverySource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetDeliverySourceRequest method. -// req, resp := client.GetDeliverySourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDeliverySource -func (c *CloudWatchLogs) GetDeliverySourceRequest(input *GetDeliverySourceInput) (req *request.Request, output *GetDeliverySourceOutput) { - op := &request.Operation{ - Name: opGetDeliverySource, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDeliverySourceInput{} - } - - output = &GetDeliverySourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDeliverySource API operation for Amazon CloudWatch Logs. -// -// Retrieves complete information about one delivery source. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetDeliverySource for usage and error information. -// -// Returned Error Types: -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetDeliverySource -func (c *CloudWatchLogs) GetDeliverySource(input *GetDeliverySourceInput) (*GetDeliverySourceOutput, error) { - req, out := c.GetDeliverySourceRequest(input) - return out, req.Send() -} - -// GetDeliverySourceWithContext is the same as GetDeliverySource with the addition of -// the ability to pass a context and additional request options. -// -// See GetDeliverySource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetDeliverySourceWithContext(ctx aws.Context, input *GetDeliverySourceInput, opts ...request.Option) (*GetDeliverySourceOutput, error) { - req, out := c.GetDeliverySourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLogAnomalyDetector = "GetLogAnomalyDetector" - -// GetLogAnomalyDetectorRequest generates a "aws/request.Request" representing the -// client's request for the GetLogAnomalyDetector operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLogAnomalyDetector for more information on using the GetLogAnomalyDetector -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetLogAnomalyDetectorRequest method. -// req, resp := client.GetLogAnomalyDetectorRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogAnomalyDetector -func (c *CloudWatchLogs) GetLogAnomalyDetectorRequest(input *GetLogAnomalyDetectorInput) (req *request.Request, output *GetLogAnomalyDetectorOutput) { - op := &request.Operation{ - Name: opGetLogAnomalyDetector, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLogAnomalyDetectorInput{} - } - - output = &GetLogAnomalyDetectorOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLogAnomalyDetector API operation for Amazon CloudWatch Logs. -// -// Retrieves information about the log anomaly detector that you specify. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetLogAnomalyDetector for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogAnomalyDetector -func (c *CloudWatchLogs) GetLogAnomalyDetector(input *GetLogAnomalyDetectorInput) (*GetLogAnomalyDetectorOutput, error) { - req, out := c.GetLogAnomalyDetectorRequest(input) - return out, req.Send() -} - -// GetLogAnomalyDetectorWithContext is the same as GetLogAnomalyDetector with the addition of -// the ability to pass a context and additional request options. -// -// See GetLogAnomalyDetector for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetLogAnomalyDetectorWithContext(ctx aws.Context, input *GetLogAnomalyDetectorInput, opts ...request.Option) (*GetLogAnomalyDetectorOutput, error) { - req, out := c.GetLogAnomalyDetectorRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLogEvents = "GetLogEvents" - -// GetLogEventsRequest generates a "aws/request.Request" representing the -// client's request for the GetLogEvents operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLogEvents for more information on using the GetLogEvents -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetLogEventsRequest method. -// req, resp := client.GetLogEventsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogEvents -func (c *CloudWatchLogs) GetLogEventsRequest(input *GetLogEventsInput) (req *request.Request, output *GetLogEventsOutput) { - op := &request.Operation{ - Name: opGetLogEvents, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextForwardToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &GetLogEventsInput{} - } - - output = &GetLogEventsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLogEvents API operation for Amazon CloudWatch Logs. -// -// Lists log events from the specified log stream. You can list all of the log -// events or filter using a time range. -// -// By default, this operation returns as many log events as can fit in a response -// size of 1MB (up to 10,000 log events). You can get additional log events -// by specifying one of the tokens in a subsequent call. This operation can -// return empty results while there are more log events available through the -// token. -// -// If you are using CloudWatch cross-account observability, you can use this -// operation in a monitoring account and view data from the linked source accounts. -// For more information, see CloudWatch cross-account observability (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html). -// -// You can specify the log group to search by using either logGroupIdentifier -// or logGroupName. You must include one of these two parameters, but you can't -// include both. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetLogEvents for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogEvents -func (c *CloudWatchLogs) GetLogEvents(input *GetLogEventsInput) (*GetLogEventsOutput, error) { - req, out := c.GetLogEventsRequest(input) - return out, req.Send() -} - -// GetLogEventsWithContext is the same as GetLogEvents with the addition of -// the ability to pass a context and additional request options. -// -// See GetLogEvents for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetLogEventsWithContext(ctx aws.Context, input *GetLogEventsInput, opts ...request.Option) (*GetLogEventsOutput, error) { - req, out := c.GetLogEventsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// GetLogEventsPages iterates over the pages of a GetLogEvents operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See GetLogEvents method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a GetLogEvents operation. -// pageNum := 0 -// err := client.GetLogEventsPages(params, -// func(page *cloudwatchlogs.GetLogEventsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) GetLogEventsPages(input *GetLogEventsInput, fn func(*GetLogEventsOutput, bool) bool) error { - return c.GetLogEventsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// GetLogEventsPagesWithContext same as GetLogEventsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetLogEventsPagesWithContext(ctx aws.Context, input *GetLogEventsInput, fn func(*GetLogEventsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *GetLogEventsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.GetLogEventsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*GetLogEventsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opGetLogGroupFields = "GetLogGroupFields" - -// GetLogGroupFieldsRequest generates a "aws/request.Request" representing the -// client's request for the GetLogGroupFields operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLogGroupFields for more information on using the GetLogGroupFields -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetLogGroupFieldsRequest method. -// req, resp := client.GetLogGroupFieldsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogGroupFields -func (c *CloudWatchLogs) GetLogGroupFieldsRequest(input *GetLogGroupFieldsInput) (req *request.Request, output *GetLogGroupFieldsOutput) { - op := &request.Operation{ - Name: opGetLogGroupFields, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLogGroupFieldsInput{} - } - - output = &GetLogGroupFieldsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLogGroupFields API operation for Amazon CloudWatch Logs. -// -// Returns a list of the fields that are included in log events in the specified -// log group. Includes the percentage of log events that contain each field. -// The search is limited to a time period that you specify. -// -// You can specify the log group to search by using either logGroupIdentifier -// or logGroupName. You must specify one of these parameters, but you can't -// specify both. -// -// In the results, fields that start with @ are fields generated by CloudWatch -// Logs. For example, @timestamp is the timestamp of each log event. For more -// information about the fields that are generated by CloudWatch logs, see Supported -// Logs and Discovered Fields (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_AnalyzeLogData-discoverable-fields.html). -// -// The response results are sorted by the frequency percentage, starting with -// the highest percentage. -// -// If you are using CloudWatch cross-account observability, you can use this -// operation in a monitoring account and view data from the linked source accounts. -// For more information, see CloudWatch cross-account observability (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetLogGroupFields for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogGroupFields -func (c *CloudWatchLogs) GetLogGroupFields(input *GetLogGroupFieldsInput) (*GetLogGroupFieldsOutput, error) { - req, out := c.GetLogGroupFieldsRequest(input) - return out, req.Send() -} - -// GetLogGroupFieldsWithContext is the same as GetLogGroupFields with the addition of -// the ability to pass a context and additional request options. -// -// See GetLogGroupFields for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetLogGroupFieldsWithContext(ctx aws.Context, input *GetLogGroupFieldsInput, opts ...request.Option) (*GetLogGroupFieldsOutput, error) { - req, out := c.GetLogGroupFieldsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLogRecord = "GetLogRecord" - -// GetLogRecordRequest generates a "aws/request.Request" representing the -// client's request for the GetLogRecord operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLogRecord for more information on using the GetLogRecord -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetLogRecordRequest method. -// req, resp := client.GetLogRecordRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogRecord -func (c *CloudWatchLogs) GetLogRecordRequest(input *GetLogRecordInput) (req *request.Request, output *GetLogRecordOutput) { - op := &request.Operation{ - Name: opGetLogRecord, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLogRecordInput{} - } - - output = &GetLogRecordOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLogRecord API operation for Amazon CloudWatch Logs. -// -// Retrieves all of the fields and values of a single log event. All fields -// are retrieved, even if the original query that produced the logRecordPointer -// retrieved only a subset of fields. Fields are returned as field name/field -// value pairs. -// -// The full unparsed log event is returned within @message. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetLogRecord for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetLogRecord -func (c *CloudWatchLogs) GetLogRecord(input *GetLogRecordInput) (*GetLogRecordOutput, error) { - req, out := c.GetLogRecordRequest(input) - return out, req.Send() -} - -// GetLogRecordWithContext is the same as GetLogRecord with the addition of -// the ability to pass a context and additional request options. -// -// See GetLogRecord for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetLogRecordWithContext(ctx aws.Context, input *GetLogRecordInput, opts ...request.Option) (*GetLogRecordOutput, error) { - req, out := c.GetLogRecordRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetQueryResults = "GetQueryResults" - -// GetQueryResultsRequest generates a "aws/request.Request" representing the -// client's request for the GetQueryResults operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetQueryResults for more information on using the GetQueryResults -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetQueryResultsRequest method. -// req, resp := client.GetQueryResultsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetQueryResults -func (c *CloudWatchLogs) GetQueryResultsRequest(input *GetQueryResultsInput) (req *request.Request, output *GetQueryResultsOutput) { - op := &request.Operation{ - Name: opGetQueryResults, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetQueryResultsInput{} - } - - output = &GetQueryResultsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetQueryResults API operation for Amazon CloudWatch Logs. -// -// Returns the results from the specified query. -// -// Only the fields requested in the query are returned, along with a @ptr field, -// which is the identifier for the log record. You can use the value of @ptr -// in a GetLogRecord (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogRecord.html) -// operation to get the full log record. -// -// GetQueryResults does not start running a query. To run a query, use StartQuery -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html). -// For more information about how long results of previous queries are available, -// see CloudWatch Logs quotas (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html). -// -// If the value of the Status field in the output is Running, this operation -// returns only partial results. If you see a value of Scheduled or Running -// for the status, you can retry the operation later to see the final results. -// -// If you are using CloudWatch cross-account observability, you can use this -// operation in a monitoring account to start queries in linked source accounts. -// For more information, see CloudWatch cross-account observability (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation GetQueryResults for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/GetQueryResults -func (c *CloudWatchLogs) GetQueryResults(input *GetQueryResultsInput) (*GetQueryResultsOutput, error) { - req, out := c.GetQueryResultsRequest(input) - return out, req.Send() -} - -// GetQueryResultsWithContext is the same as GetQueryResults with the addition of -// the ability to pass a context and additional request options. -// -// See GetQueryResults for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) GetQueryResultsWithContext(ctx aws.Context, input *GetQueryResultsInput, opts ...request.Option) (*GetQueryResultsOutput, error) { - req, out := c.GetQueryResultsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListAnomalies = "ListAnomalies" - -// ListAnomaliesRequest generates a "aws/request.Request" representing the -// client's request for the ListAnomalies operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListAnomalies for more information on using the ListAnomalies -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the ListAnomaliesRequest method. -// req, resp := client.ListAnomaliesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListAnomalies -func (c *CloudWatchLogs) ListAnomaliesRequest(input *ListAnomaliesInput) (req *request.Request, output *ListAnomaliesOutput) { - op := &request.Operation{ - Name: opListAnomalies, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &ListAnomaliesInput{} - } - - output = &ListAnomaliesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListAnomalies API operation for Amazon CloudWatch Logs. -// -// Returns a list of anomalies that log anomaly detectors have found. For details -// about the structure format of each anomaly object that is returned, see the -// example in this section. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation ListAnomalies for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListAnomalies -func (c *CloudWatchLogs) ListAnomalies(input *ListAnomaliesInput) (*ListAnomaliesOutput, error) { - req, out := c.ListAnomaliesRequest(input) - return out, req.Send() -} - -// ListAnomaliesWithContext is the same as ListAnomalies with the addition of -// the ability to pass a context and additional request options. -// -// See ListAnomalies for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) ListAnomaliesWithContext(ctx aws.Context, input *ListAnomaliesInput, opts ...request.Option) (*ListAnomaliesOutput, error) { - req, out := c.ListAnomaliesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListAnomaliesPages iterates over the pages of a ListAnomalies operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListAnomalies method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListAnomalies operation. -// pageNum := 0 -// err := client.ListAnomaliesPages(params, -// func(page *cloudwatchlogs.ListAnomaliesOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) ListAnomaliesPages(input *ListAnomaliesInput, fn func(*ListAnomaliesOutput, bool) bool) error { - return c.ListAnomaliesPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListAnomaliesPagesWithContext same as ListAnomaliesPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) ListAnomaliesPagesWithContext(ctx aws.Context, input *ListAnomaliesInput, fn func(*ListAnomaliesOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *ListAnomaliesInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListAnomaliesRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListAnomaliesOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListLogAnomalyDetectors = "ListLogAnomalyDetectors" - -// ListLogAnomalyDetectorsRequest generates a "aws/request.Request" representing the -// client's request for the ListLogAnomalyDetectors operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListLogAnomalyDetectors for more information on using the ListLogAnomalyDetectors -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the ListLogAnomalyDetectorsRequest method. -// req, resp := client.ListLogAnomalyDetectorsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListLogAnomalyDetectors -func (c *CloudWatchLogs) ListLogAnomalyDetectorsRequest(input *ListLogAnomalyDetectorsInput) (req *request.Request, output *ListLogAnomalyDetectorsOutput) { - op := &request.Operation{ - Name: opListLogAnomalyDetectors, - HTTPMethod: "POST", - HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "limit", - TruncationToken: "", - }, - } - - if input == nil { - input = &ListLogAnomalyDetectorsInput{} - } - - output = &ListLogAnomalyDetectorsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListLogAnomalyDetectors API operation for Amazon CloudWatch Logs. -// -// Retrieves a list of the log anomaly detectors in the account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation ListLogAnomalyDetectors for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListLogAnomalyDetectors -func (c *CloudWatchLogs) ListLogAnomalyDetectors(input *ListLogAnomalyDetectorsInput) (*ListLogAnomalyDetectorsOutput, error) { - req, out := c.ListLogAnomalyDetectorsRequest(input) - return out, req.Send() -} - -// ListLogAnomalyDetectorsWithContext is the same as ListLogAnomalyDetectors with the addition of -// the ability to pass a context and additional request options. -// -// See ListLogAnomalyDetectors for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) ListLogAnomalyDetectorsWithContext(ctx aws.Context, input *ListLogAnomalyDetectorsInput, opts ...request.Option) (*ListLogAnomalyDetectorsOutput, error) { - req, out := c.ListLogAnomalyDetectorsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListLogAnomalyDetectorsPages iterates over the pages of a ListLogAnomalyDetectors operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListLogAnomalyDetectors method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListLogAnomalyDetectors operation. -// pageNum := 0 -// err := client.ListLogAnomalyDetectorsPages(params, -// func(page *cloudwatchlogs.ListLogAnomalyDetectorsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *CloudWatchLogs) ListLogAnomalyDetectorsPages(input *ListLogAnomalyDetectorsInput, fn func(*ListLogAnomalyDetectorsOutput, bool) bool) error { - return c.ListLogAnomalyDetectorsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListLogAnomalyDetectorsPagesWithContext same as ListLogAnomalyDetectorsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) ListLogAnomalyDetectorsPagesWithContext(ctx aws.Context, input *ListLogAnomalyDetectorsInput, fn func(*ListLogAnomalyDetectorsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - EndPageOnSameToken: true, - NewRequest: func() (*request.Request, error) { - var inCpy *ListLogAnomalyDetectorsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListLogAnomalyDetectorsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListLogAnomalyDetectorsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListTagsForResource = "ListTagsForResource" - -// ListTagsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsForResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTagsForResource for more information on using the ListTagsForResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the ListTagsForResourceRequest method. -// req, resp := client.ListTagsForResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListTagsForResource -func (c *CloudWatchLogs) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { - op := &request.Operation{ - Name: opListTagsForResource, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &ListTagsForResourceInput{} - } - - output = &ListTagsForResourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTagsForResource API operation for Amazon CloudWatch Logs. -// -// Displays the tags associated with a CloudWatch Logs resource. Currently, -// log groups and destinations support tagging. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation ListTagsForResource for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListTagsForResource -func (c *CloudWatchLogs) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) - return out, req.Send() -} - -// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of -// the ability to pass a context and additional request options. -// -// See ListTagsForResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTagsLogGroup = "ListTagsLogGroup" - -// ListTagsLogGroupRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsLogGroup operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTagsLogGroup for more information on using the ListTagsLogGroup -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the ListTagsLogGroupRequest method. -// req, resp := client.ListTagsLogGroupRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListTagsLogGroup -// -// Deprecated: Please use the generic tagging API ListTagsForResource -func (c *CloudWatchLogs) ListTagsLogGroupRequest(input *ListTagsLogGroupInput) (req *request.Request, output *ListTagsLogGroupOutput) { - if c.Client.Config.Logger != nil { - c.Client.Config.Logger.Log("This operation, ListTagsLogGroup, has been deprecated") - } - op := &request.Operation{ - Name: opListTagsLogGroup, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &ListTagsLogGroupInput{} - } - - output = &ListTagsLogGroupOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTagsLogGroup API operation for Amazon CloudWatch Logs. -// -// The ListTagsLogGroup operation is on the path to deprecation. We recommend -// that you use ListTagsForResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListTagsForResource.html) -// instead. -// -// Lists the tags for the specified log group. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation ListTagsLogGroup for usage and error information. -// -// Returned Error Types: -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/ListTagsLogGroup -// -// Deprecated: Please use the generic tagging API ListTagsForResource -func (c *CloudWatchLogs) ListTagsLogGroup(input *ListTagsLogGroupInput) (*ListTagsLogGroupOutput, error) { - req, out := c.ListTagsLogGroupRequest(input) - return out, req.Send() -} - -// ListTagsLogGroupWithContext is the same as ListTagsLogGroup with the addition of -// the ability to pass a context and additional request options. -// -// See ListTagsLogGroup for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -// -// Deprecated: Please use the generic tagging API ListTagsForResource -func (c *CloudWatchLogs) ListTagsLogGroupWithContext(ctx aws.Context, input *ListTagsLogGroupInput, opts ...request.Option) (*ListTagsLogGroupOutput, error) { - req, out := c.ListTagsLogGroupRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutAccountPolicy = "PutAccountPolicy" - -// PutAccountPolicyRequest generates a "aws/request.Request" representing the -// client's request for the PutAccountPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutAccountPolicy for more information on using the PutAccountPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutAccountPolicyRequest method. -// req, resp := client.PutAccountPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutAccountPolicy -func (c *CloudWatchLogs) PutAccountPolicyRequest(input *PutAccountPolicyInput) (req *request.Request, output *PutAccountPolicyOutput) { - op := &request.Operation{ - Name: opPutAccountPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutAccountPolicyInput{} - } - - output = &PutAccountPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutAccountPolicy API operation for Amazon CloudWatch Logs. -// -// Creates an account-level data protection policy or subscription filter policy -// that applies to all log groups or a subset of log groups in the account. -// -// # Data protection policy -// -// A data protection policy can help safeguard sensitive data that's ingested -// by your log groups by auditing and masking the sensitive log data. Each account -// can have only one account-level data protection policy. -// -// Sensitive data is detected and masked when it is ingested into a log group. -// When you set a data protection policy, log events ingested into the log groups -// before that time are not masked. -// -// If you use PutAccountPolicy to create a data protection policy for your whole -// account, it applies to both existing log groups and all log groups that are -// created later in this account. The account-level policy is applied to existing -// log groups with eventual consistency. It might take up to 5 minutes before -// sensitive data in existing log groups begins to be masked. -// -// By default, when a user views a log event that includes masked data, the -// sensitive data is replaced by asterisks. A user who has the logs:Unmask permission -// can use a GetLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html) -// or FilterLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_FilterLogEvents.html) -// operation with the unmask parameter set to true to view the unmasked log -// events. Users with the logs:Unmask can also view unmasked data in the CloudWatch -// Logs console by running a CloudWatch Logs Insights query with the unmask -// query command. -// -// For more information, including a list of types of data that can be audited -// and masked, see Protect sensitive log data with masking (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html). -// -// To use the PutAccountPolicy operation for a data protection policy, you must -// be signed on with the logs:PutDataProtectionPolicy and logs:PutAccountPolicy -// permissions. -// -// The PutAccountPolicy operation applies to all log groups in the account. -// You can use PutDataProtectionPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDataProtectionPolicy.html) -// to create a data protection policy that applies to just one log group. If -// a log group has its own data protection policy and the account also has an -// account-level data protection policy, then the two policies are cumulative. -// Any sensitive term specified in either policy is masked. -// -// # Subscription filter policy -// -// A subscription filter policy sets up a real-time feed of log events from -// CloudWatch Logs to other Amazon Web Services services. Account-level subscription -// filter policies apply to both existing log groups and log groups that are -// created later in this account. Supported destinations are Kinesis Data Streams, -// Firehose, and Lambda. When log events are sent to the receiving service, -// they are Base64 encoded and compressed with the GZIP format. -// -// The following destinations are supported for subscription filters: -// -// - An Kinesis Data Streams data stream in the same account as the subscription -// policy, for same-account delivery. -// -// - An Firehose data stream in the same account as the subscription policy, -// for same-account delivery. -// -// - A Lambda function in the same account as the subscription policy, for -// same-account delivery. -// -// - A logical destination in a different account created with PutDestination -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDestination.html), -// for cross-account delivery. Kinesis Data Streams and Firehose are supported -// as logical destinations. -// -// Each account can have one account-level subscription filter policy. If you -// are updating an existing filter, you must specify the correct name in PolicyName. -// To perform a PutAccountPolicy subscription filter operation for any destination -// except a Lambda function, you must also have the iam:PassRole permission. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutAccountPolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutAccountPolicy -func (c *CloudWatchLogs) PutAccountPolicy(input *PutAccountPolicyInput) (*PutAccountPolicyOutput, error) { - req, out := c.PutAccountPolicyRequest(input) - return out, req.Send() -} - -// PutAccountPolicyWithContext is the same as PutAccountPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See PutAccountPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutAccountPolicyWithContext(ctx aws.Context, input *PutAccountPolicyInput, opts ...request.Option) (*PutAccountPolicyOutput, error) { - req, out := c.PutAccountPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutDataProtectionPolicy = "PutDataProtectionPolicy" - -// PutDataProtectionPolicyRequest generates a "aws/request.Request" representing the -// client's request for the PutDataProtectionPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutDataProtectionPolicy for more information on using the PutDataProtectionPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutDataProtectionPolicyRequest method. -// req, resp := client.PutDataProtectionPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDataProtectionPolicy -func (c *CloudWatchLogs) PutDataProtectionPolicyRequest(input *PutDataProtectionPolicyInput) (req *request.Request, output *PutDataProtectionPolicyOutput) { - op := &request.Operation{ - Name: opPutDataProtectionPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutDataProtectionPolicyInput{} - } - - output = &PutDataProtectionPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutDataProtectionPolicy API operation for Amazon CloudWatch Logs. -// -// Creates a data protection policy for the specified log group. A data protection -// policy can help safeguard sensitive data that's ingested by the log group -// by auditing and masking the sensitive log data. -// -// Sensitive data is detected and masked when it is ingested into the log group. -// When you set a data protection policy, log events ingested into the log group -// before that time are not masked. -// -// By default, when a user views a log event that includes masked data, the -// sensitive data is replaced by asterisks. A user who has the logs:Unmask permission -// can use a GetLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html) -// or FilterLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_FilterLogEvents.html) -// operation with the unmask parameter set to true to view the unmasked log -// events. Users with the logs:Unmask can also view unmasked data in the CloudWatch -// Logs console by running a CloudWatch Logs Insights query with the unmask -// query command. -// -// For more information, including a list of types of data that can be audited -// and masked, see Protect sensitive log data with masking (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html). -// -// The PutDataProtectionPolicy operation applies to only the specified log group. -// You can also use PutAccountPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutAccountPolicy.html) -// to create an account-level data protection policy that applies to all log -// groups in the account, including both existing log groups and log groups -// that are created level. If a log group has its own data protection policy -// and the account also has an account-level data protection policy, then the -// two policies are cumulative. Any sensitive term specified in either policy -// is masked. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutDataProtectionPolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDataProtectionPolicy -func (c *CloudWatchLogs) PutDataProtectionPolicy(input *PutDataProtectionPolicyInput) (*PutDataProtectionPolicyOutput, error) { - req, out := c.PutDataProtectionPolicyRequest(input) - return out, req.Send() -} - -// PutDataProtectionPolicyWithContext is the same as PutDataProtectionPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See PutDataProtectionPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutDataProtectionPolicyWithContext(ctx aws.Context, input *PutDataProtectionPolicyInput, opts ...request.Option) (*PutDataProtectionPolicyOutput, error) { - req, out := c.PutDataProtectionPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutDeliveryDestination = "PutDeliveryDestination" - -// PutDeliveryDestinationRequest generates a "aws/request.Request" representing the -// client's request for the PutDeliveryDestination operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutDeliveryDestination for more information on using the PutDeliveryDestination -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutDeliveryDestinationRequest method. -// req, resp := client.PutDeliveryDestinationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDeliveryDestination -func (c *CloudWatchLogs) PutDeliveryDestinationRequest(input *PutDeliveryDestinationInput) (req *request.Request, output *PutDeliveryDestinationOutput) { - op := &request.Operation{ - Name: opPutDeliveryDestination, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutDeliveryDestinationInput{} - } - - output = &PutDeliveryDestinationOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutDeliveryDestination API operation for Amazon CloudWatch Logs. -// -// Creates or updates a logical delivery destination. A delivery destination -// is an Amazon Web Services resource that represents an Amazon Web Services -// service that logs can be sent to. CloudWatch Logs, Amazon S3, and Firehose -// are supported as logs delivery destinations. -// -// To configure logs delivery between a supported Amazon Web Services service -// and a destination, you must do the following: -// -// - Create a delivery source, which is a logical object that represents -// the resource that is actually sending the logs. For more information, -// see PutDeliverySource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliverySource.html). -// -// - Use PutDeliveryDestination to create a delivery destination, which is -// a logical object that represents the actual delivery destination. -// -// - If you are delivering logs cross-account, you must use PutDeliveryDestinationPolicy -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestinationPolicy.html) -// in the destination account to assign an IAM policy to the destination. -// This policy allows delivery to that destination. -// -// - Use CreateDelivery to create a delivery by pairing exactly one delivery -// source and one delivery destination. For more information, see CreateDelivery -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateDelivery.html). -// -// You can configure a single delivery source to send logs to multiple destinations -// by creating multiple deliveries. You can also create multiple deliveries -// to configure multiple delivery sources to send logs to the same delivery -// destination. -// -// Only some Amazon Web Services services support being configured as a delivery -// source. These services are listed as Supported [V2 Permissions] in the table -// at Enabling logging from Amazon Web Services services. (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html) -// -// If you use this operation to update an existing delivery destination, all -// the current delivery destination parameters are overwritten with the new -// parameter values that you specify. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutDeliveryDestination for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ConflictException -// This operation attempted to create a resource that already exists. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDeliveryDestination -func (c *CloudWatchLogs) PutDeliveryDestination(input *PutDeliveryDestinationInput) (*PutDeliveryDestinationOutput, error) { - req, out := c.PutDeliveryDestinationRequest(input) - return out, req.Send() -} - -// PutDeliveryDestinationWithContext is the same as PutDeliveryDestination with the addition of -// the ability to pass a context and additional request options. -// -// See PutDeliveryDestination for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutDeliveryDestinationWithContext(ctx aws.Context, input *PutDeliveryDestinationInput, opts ...request.Option) (*PutDeliveryDestinationOutput, error) { - req, out := c.PutDeliveryDestinationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutDeliveryDestinationPolicy = "PutDeliveryDestinationPolicy" - -// PutDeliveryDestinationPolicyRequest generates a "aws/request.Request" representing the -// client's request for the PutDeliveryDestinationPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutDeliveryDestinationPolicy for more information on using the PutDeliveryDestinationPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutDeliveryDestinationPolicyRequest method. -// req, resp := client.PutDeliveryDestinationPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDeliveryDestinationPolicy -func (c *CloudWatchLogs) PutDeliveryDestinationPolicyRequest(input *PutDeliveryDestinationPolicyInput) (req *request.Request, output *PutDeliveryDestinationPolicyOutput) { - op := &request.Operation{ - Name: opPutDeliveryDestinationPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutDeliveryDestinationPolicyInput{} - } - - output = &PutDeliveryDestinationPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutDeliveryDestinationPolicy API operation for Amazon CloudWatch Logs. -// -// Creates and assigns an IAM policy that grants permissions to CloudWatch Logs -// to deliver logs cross-account to a specified destination in this account. -// To configure the delivery of logs from an Amazon Web Services service in -// another account to a logs delivery destination in the current account, you -// must do the following: -// -// - Create a delivery source, which is a logical object that represents -// the resource that is actually sending the logs. For more information, -// see PutDeliverySource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliverySource.html). -// -// - Create a delivery destination, which is a logical object that represents -// the actual delivery destination. For more information, see PutDeliveryDestination -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestination.html). -// -// - Use this operation in the destination account to assign an IAM policy -// to the destination. This policy allows delivery to that destination. -// -// - Create a delivery by pairing exactly one delivery source and one delivery -// destination. For more information, see CreateDelivery (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateDelivery.html). -// -// Only some Amazon Web Services services support being configured as a delivery -// source. These services are listed as Supported [V2 Permissions] in the table -// at Enabling logging from Amazon Web Services services. (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html) -// -// The contents of the policy must include two statements. One statement enables -// general logs delivery, and the other allows delivery to the chosen destination. -// See the examples for the needed policies. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutDeliveryDestinationPolicy for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ConflictException -// This operation attempted to create a resource that already exists. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDeliveryDestinationPolicy -func (c *CloudWatchLogs) PutDeliveryDestinationPolicy(input *PutDeliveryDestinationPolicyInput) (*PutDeliveryDestinationPolicyOutput, error) { - req, out := c.PutDeliveryDestinationPolicyRequest(input) - return out, req.Send() -} - -// PutDeliveryDestinationPolicyWithContext is the same as PutDeliveryDestinationPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See PutDeliveryDestinationPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutDeliveryDestinationPolicyWithContext(ctx aws.Context, input *PutDeliveryDestinationPolicyInput, opts ...request.Option) (*PutDeliveryDestinationPolicyOutput, error) { - req, out := c.PutDeliveryDestinationPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutDeliverySource = "PutDeliverySource" - -// PutDeliverySourceRequest generates a "aws/request.Request" representing the -// client's request for the PutDeliverySource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutDeliverySource for more information on using the PutDeliverySource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutDeliverySourceRequest method. -// req, resp := client.PutDeliverySourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDeliverySource -func (c *CloudWatchLogs) PutDeliverySourceRequest(input *PutDeliverySourceInput) (req *request.Request, output *PutDeliverySourceOutput) { - op := &request.Operation{ - Name: opPutDeliverySource, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutDeliverySourceInput{} - } - - output = &PutDeliverySourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutDeliverySource API operation for Amazon CloudWatch Logs. -// -// Creates or updates a logical delivery source. A delivery source represents -// an Amazon Web Services resource that sends logs to an logs delivery destination. -// The destination can be CloudWatch Logs, Amazon S3, or Firehose. -// -// To configure logs delivery between a delivery destination and an Amazon Web -// Services service that is supported as a delivery source, you must do the -// following: -// -// - Use PutDeliverySource to create a delivery source, which is a logical -// object that represents the resource that is actually sending the logs. -// -// - Use PutDeliveryDestination to create a delivery destination, which is -// a logical object that represents the actual delivery destination. For -// more information, see PutDeliveryDestination (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestination.html). -// -// - If you are delivering logs cross-account, you must use PutDeliveryDestinationPolicy -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestinationPolicy.html) -// in the destination account to assign an IAM policy to the destination. -// This policy allows delivery to that destination. -// -// - Use CreateDelivery to create a delivery by pairing exactly one delivery -// source and one delivery destination. For more information, see CreateDelivery -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateDelivery.html). -// -// You can configure a single delivery source to send logs to multiple destinations -// by creating multiple deliveries. You can also create multiple deliveries -// to configure multiple delivery sources to send logs to the same delivery -// destination. -// -// Only some Amazon Web Services services support being configured as a delivery -// source. These services are listed as Supported [V2 Permissions] in the table -// at Enabling logging from Amazon Web Services services. (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html) -// -// If you use this operation to update an existing delivery source, all the -// current delivery source parameters are overwritten with the new parameter -// values that you specify. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutDeliverySource for usage and error information. -// -// Returned Error Types: -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - ConflictException -// This operation attempted to create a resource that already exists. -// -// - ValidationException -// One of the parameters for the request is not valid. -// -// - ServiceQuotaExceededException -// This request exceeds a service quota. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ThrottlingException -// The request was throttled because of quota limits. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDeliverySource -func (c *CloudWatchLogs) PutDeliverySource(input *PutDeliverySourceInput) (*PutDeliverySourceOutput, error) { - req, out := c.PutDeliverySourceRequest(input) - return out, req.Send() -} - -// PutDeliverySourceWithContext is the same as PutDeliverySource with the addition of -// the ability to pass a context and additional request options. -// -// See PutDeliverySource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutDeliverySourceWithContext(ctx aws.Context, input *PutDeliverySourceInput, opts ...request.Option) (*PutDeliverySourceOutput, error) { - req, out := c.PutDeliverySourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutDestination = "PutDestination" - -// PutDestinationRequest generates a "aws/request.Request" representing the -// client's request for the PutDestination operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutDestination for more information on using the PutDestination -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutDestinationRequest method. -// req, resp := client.PutDestinationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDestination -func (c *CloudWatchLogs) PutDestinationRequest(input *PutDestinationInput) (req *request.Request, output *PutDestinationOutput) { - op := &request.Operation{ - Name: opPutDestination, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutDestinationInput{} - } - - output = &PutDestinationOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutDestination API operation for Amazon CloudWatch Logs. -// -// Creates or updates a destination. This operation is used only to create destinations -// for cross-account subscriptions. -// -// A destination encapsulates a physical resource (such as an Amazon Kinesis -// stream). With a destination, you can subscribe to a real-time stream of log -// events for a different account, ingested using PutLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html). -// -// Through an access policy, a destination controls what is written to it. By -// default, PutDestination does not set any access policy with the destination, -// which means a cross-account user cannot call PutSubscriptionFilter (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutSubscriptionFilter.html) -// against this destination. To enable this, the destination owner must call -// PutDestinationPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDestinationPolicy.html) -// after PutDestination. -// -// To perform a PutDestination operation, you must also have the iam:PassRole -// permission. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutDestination for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDestination -func (c *CloudWatchLogs) PutDestination(input *PutDestinationInput) (*PutDestinationOutput, error) { - req, out := c.PutDestinationRequest(input) - return out, req.Send() -} - -// PutDestinationWithContext is the same as PutDestination with the addition of -// the ability to pass a context and additional request options. -// -// See PutDestination for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutDestinationWithContext(ctx aws.Context, input *PutDestinationInput, opts ...request.Option) (*PutDestinationOutput, error) { - req, out := c.PutDestinationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutDestinationPolicy = "PutDestinationPolicy" - -// PutDestinationPolicyRequest generates a "aws/request.Request" representing the -// client's request for the PutDestinationPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutDestinationPolicy for more information on using the PutDestinationPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutDestinationPolicyRequest method. -// req, resp := client.PutDestinationPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDestinationPolicy -func (c *CloudWatchLogs) PutDestinationPolicyRequest(input *PutDestinationPolicyInput) (req *request.Request, output *PutDestinationPolicyOutput) { - op := &request.Operation{ - Name: opPutDestinationPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutDestinationPolicyInput{} - } - - output = &PutDestinationPolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutDestinationPolicy API operation for Amazon CloudWatch Logs. -// -// Creates or updates an access policy associated with an existing destination. -// An access policy is an IAM policy document (https://docs.aws.amazon.com/IAM/latest/UserGuide/policies_overview.html) -// that is used to authorize claims to register a subscription filter against -// a given destination. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutDestinationPolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutDestinationPolicy -func (c *CloudWatchLogs) PutDestinationPolicy(input *PutDestinationPolicyInput) (*PutDestinationPolicyOutput, error) { - req, out := c.PutDestinationPolicyRequest(input) - return out, req.Send() -} - -// PutDestinationPolicyWithContext is the same as PutDestinationPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See PutDestinationPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutDestinationPolicyWithContext(ctx aws.Context, input *PutDestinationPolicyInput, opts ...request.Option) (*PutDestinationPolicyOutput, error) { - req, out := c.PutDestinationPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutLogEvents = "PutLogEvents" - -// PutLogEventsRequest generates a "aws/request.Request" representing the -// client's request for the PutLogEvents operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutLogEvents for more information on using the PutLogEvents -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutLogEventsRequest method. -// req, resp := client.PutLogEventsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutLogEvents -func (c *CloudWatchLogs) PutLogEventsRequest(input *PutLogEventsInput) (req *request.Request, output *PutLogEventsOutput) { - op := &request.Operation{ - Name: opPutLogEvents, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutLogEventsInput{} - } - - output = &PutLogEventsOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutLogEvents API operation for Amazon CloudWatch Logs. -// -// Uploads a batch of log events to the specified log stream. -// -// The sequence token is now ignored in PutLogEvents actions. PutLogEvents actions -// are always accepted and never return InvalidSequenceTokenException or DataAlreadyAcceptedException -// even if the sequence token is not valid. You can use parallel PutLogEvents -// actions on the same log stream. -// -// The batch of events must satisfy the following constraints: -// -// - The maximum batch size is 1,048,576 bytes. This size is calculated as -// the sum of all event messages in UTF-8, plus 26 bytes for each log event. -// -// - None of the log events in the batch can be more than 2 hours in the -// future. -// -// - None of the log events in the batch can be more than 14 days in the -// past. Also, none of the log events can be from earlier than the retention -// period of the log group. -// -// - The log events in the batch must be in chronological order by their -// timestamp. The timestamp is the time that the event occurred, expressed -// as the number of milliseconds after Jan 1, 1970 00:00:00 UTC. (In Amazon -// Web Services Tools for PowerShell and the Amazon Web Services SDK for -// .NET, the timestamp is specified in .NET format: yyyy-mm-ddThh:mm:ss. -// For example, 2017-09-15T13:45:30.) -// -// - A batch of log events in a single request cannot span more than 24 hours. -// Otherwise, the operation fails. -// -// - Each log event can be no larger than 256 KB. -// -// - The maximum number of log events in a batch is 10,000. -// -// - The quota of five requests per second per log stream has been removed. -// Instead, PutLogEvents actions are throttled based on a per-second per-account -// quota. You can request an increase to the per-second throttling quota -// by using the Service Quotas service. -// -// If a call to PutLogEvents returns "UnrecognizedClientException" the most -// likely cause is a non-valid Amazon Web Services access key ID or secret key. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutLogEvents for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - InvalidSequenceTokenException -// The sequence token is not valid. You can get the correct sequence token in -// the expectedSequenceToken field in the InvalidSequenceTokenException message. -// -// PutLogEvents actions are now always accepted and never return InvalidSequenceTokenException -// regardless of receiving an invalid sequence token. -// -// - DataAlreadyAcceptedException -// The event was already logged. -// -// PutLogEvents actions are now always accepted and never return DataAlreadyAcceptedException -// regardless of whether a given batch of log events has already been accepted. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - UnrecognizedClientException -// The most likely cause is an Amazon Web Services access key ID or secret key -// that's not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutLogEvents -func (c *CloudWatchLogs) PutLogEvents(input *PutLogEventsInput) (*PutLogEventsOutput, error) { - req, out := c.PutLogEventsRequest(input) - return out, req.Send() -} - -// PutLogEventsWithContext is the same as PutLogEvents with the addition of -// the ability to pass a context and additional request options. -// -// See PutLogEvents for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutLogEventsWithContext(ctx aws.Context, input *PutLogEventsInput, opts ...request.Option) (*PutLogEventsOutput, error) { - req, out := c.PutLogEventsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutMetricFilter = "PutMetricFilter" - -// PutMetricFilterRequest generates a "aws/request.Request" representing the -// client's request for the PutMetricFilter operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutMetricFilter for more information on using the PutMetricFilter -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutMetricFilterRequest method. -// req, resp := client.PutMetricFilterRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutMetricFilter -func (c *CloudWatchLogs) PutMetricFilterRequest(input *PutMetricFilterInput) (req *request.Request, output *PutMetricFilterOutput) { - op := &request.Operation{ - Name: opPutMetricFilter, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutMetricFilterInput{} - } - - output = &PutMetricFilterOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutMetricFilter API operation for Amazon CloudWatch Logs. -// -// Creates or updates a metric filter and associates it with the specified log -// group. With metric filters, you can configure rules to extract metric data -// from log events ingested through PutLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html). -// -// The maximum number of metric filters that can be associated with a log group -// is 100. -// -// When you create a metric filter, you can also optionally assign a unit and -// dimensions to the metric that is created. -// -// Metrics extracted from log events are charged as custom metrics. To prevent -// unexpected high charges, do not specify high-cardinality fields such as IPAddress -// or requestID as dimensions. Each different value found for a dimension is -// treated as a separate metric and accrues charges as a separate custom metric. -// -// CloudWatch Logs might disable a metric filter if it generates 1,000 different -// name/value pairs for your specified dimensions within one hour. -// -// You can also set up a billing alarm to alert you if your charges are higher -// than expected. For more information, see Creating a Billing Alarm to Monitor -// Your Estimated Amazon Web Services Charges (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutMetricFilter for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutMetricFilter -func (c *CloudWatchLogs) PutMetricFilter(input *PutMetricFilterInput) (*PutMetricFilterOutput, error) { - req, out := c.PutMetricFilterRequest(input) - return out, req.Send() -} - -// PutMetricFilterWithContext is the same as PutMetricFilter with the addition of -// the ability to pass a context and additional request options. -// -// See PutMetricFilter for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutMetricFilterWithContext(ctx aws.Context, input *PutMetricFilterInput, opts ...request.Option) (*PutMetricFilterOutput, error) { - req, out := c.PutMetricFilterRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutQueryDefinition = "PutQueryDefinition" - -// PutQueryDefinitionRequest generates a "aws/request.Request" representing the -// client's request for the PutQueryDefinition operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutQueryDefinition for more information on using the PutQueryDefinition -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutQueryDefinitionRequest method. -// req, resp := client.PutQueryDefinitionRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutQueryDefinition -func (c *CloudWatchLogs) PutQueryDefinitionRequest(input *PutQueryDefinitionInput) (req *request.Request, output *PutQueryDefinitionOutput) { - op := &request.Operation{ - Name: opPutQueryDefinition, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutQueryDefinitionInput{} - } - - output = &PutQueryDefinitionOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutQueryDefinition API operation for Amazon CloudWatch Logs. -// -// Creates or updates a query definition for CloudWatch Logs Insights. For more -// information, see Analyzing Log Data with CloudWatch Logs Insights (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html). -// -// To update a query definition, specify its queryDefinitionId in your request. -// The values of name, queryString, and logGroupNames are changed to the values -// that you specify in your update operation. No current values are retained -// from the current query definition. For example, imagine updating a current -// query definition that includes log groups. If you don't specify the logGroupNames -// parameter in your update operation, the query definition changes to contain -// no log groups. -// -// You must have the logs:PutQueryDefinition permission to be able to perform -// this operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutQueryDefinition for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutQueryDefinition -func (c *CloudWatchLogs) PutQueryDefinition(input *PutQueryDefinitionInput) (*PutQueryDefinitionOutput, error) { - req, out := c.PutQueryDefinitionRequest(input) - return out, req.Send() -} - -// PutQueryDefinitionWithContext is the same as PutQueryDefinition with the addition of -// the ability to pass a context and additional request options. -// -// See PutQueryDefinition for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutQueryDefinitionWithContext(ctx aws.Context, input *PutQueryDefinitionInput, opts ...request.Option) (*PutQueryDefinitionOutput, error) { - req, out := c.PutQueryDefinitionRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutResourcePolicy = "PutResourcePolicy" - -// PutResourcePolicyRequest generates a "aws/request.Request" representing the -// client's request for the PutResourcePolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutResourcePolicy for more information on using the PutResourcePolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutResourcePolicyRequest method. -// req, resp := client.PutResourcePolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutResourcePolicy -func (c *CloudWatchLogs) PutResourcePolicyRequest(input *PutResourcePolicyInput) (req *request.Request, output *PutResourcePolicyOutput) { - op := &request.Operation{ - Name: opPutResourcePolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutResourcePolicyInput{} - } - - output = &PutResourcePolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutResourcePolicy API operation for Amazon CloudWatch Logs. -// -// Creates or updates a resource policy allowing other Amazon Web Services services -// to put log events to this account, such as Amazon Route 53. An account can -// have up to 10 resource policies per Amazon Web Services Region. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutResourcePolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutResourcePolicy -func (c *CloudWatchLogs) PutResourcePolicy(input *PutResourcePolicyInput) (*PutResourcePolicyOutput, error) { - req, out := c.PutResourcePolicyRequest(input) - return out, req.Send() -} - -// PutResourcePolicyWithContext is the same as PutResourcePolicy with the addition of -// the ability to pass a context and additional request options. -// -// See PutResourcePolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutResourcePolicyWithContext(ctx aws.Context, input *PutResourcePolicyInput, opts ...request.Option) (*PutResourcePolicyOutput, error) { - req, out := c.PutResourcePolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutRetentionPolicy = "PutRetentionPolicy" - -// PutRetentionPolicyRequest generates a "aws/request.Request" representing the -// client's request for the PutRetentionPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutRetentionPolicy for more information on using the PutRetentionPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutRetentionPolicyRequest method. -// req, resp := client.PutRetentionPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutRetentionPolicy -func (c *CloudWatchLogs) PutRetentionPolicyRequest(input *PutRetentionPolicyInput) (req *request.Request, output *PutRetentionPolicyOutput) { - op := &request.Operation{ - Name: opPutRetentionPolicy, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutRetentionPolicyInput{} - } - - output = &PutRetentionPolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutRetentionPolicy API operation for Amazon CloudWatch Logs. -// -// Sets the retention of the specified log group. With a retention policy, you -// can configure the number of days for which to retain log events in the specified -// log group. -// -// CloudWatch Logs doesn’t immediately delete log events when they reach their -// retention setting. It typically takes up to 72 hours after that before log -// events are deleted, but in rare situations might take longer. -// -// To illustrate, imagine that you change a log group to have a longer retention -// setting when it contains log events that are past the expiration date, but -// haven’t been deleted. Those log events will take up to 72 hours to be deleted -// after the new retention date is reached. To make sure that log data is deleted -// permanently, keep a log group at its lower retention setting until 72 hours -// after the previous retention period ends. Alternatively, wait to change the -// retention setting until you confirm that the earlier log events are deleted. -// -// When log events reach their retention setting they are marked for deletion. -// After they are marked for deletion, they do not add to your archival storage -// costs anymore, even if they are not actually deleted until later. These log -// events marked for deletion are also not included when you use an API to retrieve -// the storedBytes value to see how many bytes a log group is storing. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutRetentionPolicy for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutRetentionPolicy -func (c *CloudWatchLogs) PutRetentionPolicy(input *PutRetentionPolicyInput) (*PutRetentionPolicyOutput, error) { - req, out := c.PutRetentionPolicyRequest(input) - return out, req.Send() -} - -// PutRetentionPolicyWithContext is the same as PutRetentionPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See PutRetentionPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutRetentionPolicyWithContext(ctx aws.Context, input *PutRetentionPolicyInput, opts ...request.Option) (*PutRetentionPolicyOutput, error) { - req, out := c.PutRetentionPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutSubscriptionFilter = "PutSubscriptionFilter" - -// PutSubscriptionFilterRequest generates a "aws/request.Request" representing the -// client's request for the PutSubscriptionFilter operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutSubscriptionFilter for more information on using the PutSubscriptionFilter -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the PutSubscriptionFilterRequest method. -// req, resp := client.PutSubscriptionFilterRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutSubscriptionFilter -func (c *CloudWatchLogs) PutSubscriptionFilterRequest(input *PutSubscriptionFilterInput) (req *request.Request, output *PutSubscriptionFilterOutput) { - op := &request.Operation{ - Name: opPutSubscriptionFilter, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutSubscriptionFilterInput{} - } - - output = &PutSubscriptionFilterOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutSubscriptionFilter API operation for Amazon CloudWatch Logs. -// -// Creates or updates a subscription filter and associates it with the specified -// log group. With subscription filters, you can subscribe to a real-time stream -// of log events ingested through PutLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html) -// and have them delivered to a specific destination. When log events are sent -// to the receiving service, they are Base64 encoded and compressed with the -// GZIP format. -// -// The following destinations are supported for subscription filters: -// -// - An Amazon Kinesis data stream belonging to the same account as the subscription -// filter, for same-account delivery. -// -// - A logical destination created with PutDestination (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDestination.html) -// that belongs to a different account, for cross-account delivery. We currently -// support Kinesis Data Streams and Firehose as logical destinations. -// -// - An Amazon Kinesis Data Firehose delivery stream that belongs to the -// same account as the subscription filter, for same-account delivery. -// -// - An Lambda function that belongs to the same account as the subscription -// filter, for same-account delivery. -// -// Each log group can have up to two subscription filters associated with it. -// If you are updating an existing filter, you must specify the correct name -// in filterName. -// -// To perform a PutSubscriptionFilter operation for any destination except a -// Lambda function, you must also have the iam:PassRole permission. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation PutSubscriptionFilter for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutSubscriptionFilter -func (c *CloudWatchLogs) PutSubscriptionFilter(input *PutSubscriptionFilterInput) (*PutSubscriptionFilterOutput, error) { - req, out := c.PutSubscriptionFilterRequest(input) - return out, req.Send() -} - -// PutSubscriptionFilterWithContext is the same as PutSubscriptionFilter with the addition of -// the ability to pass a context and additional request options. -// -// See PutSubscriptionFilter for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) PutSubscriptionFilterWithContext(ctx aws.Context, input *PutSubscriptionFilterInput, opts ...request.Option) (*PutSubscriptionFilterOutput, error) { - req, out := c.PutSubscriptionFilterRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opStartLiveTail = "StartLiveTail" - -// StartLiveTailRequest generates a "aws/request.Request" representing the -// client's request for the StartLiveTail operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See StartLiveTail for more information on using the StartLiveTail -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the StartLiveTailRequest method. -// req, resp := client.StartLiveTailRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/StartLiveTail -func (c *CloudWatchLogs) StartLiveTailRequest(input *StartLiveTailInput) (req *request.Request, output *StartLiveTailOutput) { - op := &request.Operation{ - Name: opStartLiveTail, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &StartLiveTailInput{} - } - - output = &StartLiveTailOutput{} - req = c.newRequest(op, input, output) - - es := NewStartLiveTailEventStream() - output.eventStream = es - - req.Handlers.Send.Swap(client.LogHTTPResponseHandler.Name, client.LogHTTPResponseHeaderHandler) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, rest.UnmarshalHandler) - req.Handlers.Unmarshal.PushBack(es.runOutputStream) - es.output = output - req.Handlers.Unmarshal.PushBack(es.recvInitialEvent) - req.Handlers.Unmarshal.PushBack(es.runOnStreamPartClose) - req.Handlers.Build.PushBackNamed(protocol.NewHostPrefixHandler("streaming-", nil)) - req.Handlers.Build.PushBackNamed(protocol.ValidateEndpointHostHandler) - return -} - -// StartLiveTail API operation for Amazon CloudWatch Logs. -// -// Starts a Live Tail streaming session for one or more log groups. A Live Tail -// session returns a stream of log events that have been recently ingested in -// the log groups. For more information, see Use Live Tail to view logs in near -// real time (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatchLogs_LiveTail.html). -// -// The response to this operation is a response stream, over which the server -// sends live log events and the client receives them. -// -// The following objects are sent over the stream: -// -// - A single LiveTailSessionStart (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_LiveTailSessionStart.html) -// object is sent at the start of the session. -// -// - Every second, a LiveTailSessionUpdate (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_LiveTailSessionUpdate.html) -// object is sent. Each of these objects contains an array of the actual -// log events. If no new log events were ingested in the past second, the -// LiveTailSessionUpdate object will contain an empty array. The array of -// log events contained in a LiveTailSessionUpdate can include as many as -// 500 log events. If the number of log events matching the request exceeds -// 500 per second, the log events are sampled down to 500 log events to be -// included in each LiveTailSessionUpdate object. If your client consumes -// the log events slower than the server produces them, CloudWatch Logs buffers -// up to 10 LiveTailSessionUpdate events or 5000 log events, after which -// it starts dropping the oldest events. -// -// - A SessionStreamingException (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_SessionStreamingException.html) -// object is returned if an unknown error occurs on the server side. -// -// - A SessionTimeoutException (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_SessionTimeoutException.html) -// object is returned when the session times out, after it has been kept -// open for three hours. -// -// You can end a session before it times out by closing the session stream or -// by closing the client that is receiving the stream. The session also ends -// if the established connection between the client and the server breaks. -// -// For examples of using an SDK to start a Live Tail session, see Start a Live -// Tail session using an Amazon Web Services SDK (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/example_cloudwatch-logs_StartLiveTail_section.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation StartLiveTail for usage and error information. -// -// Returned Error Types: -// -// - AccessDeniedException -// You don't have sufficient permissions to perform this action. -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - InvalidOperationException -// The operation is not valid on the specified resource. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/StartLiveTail -func (c *CloudWatchLogs) StartLiveTail(input *StartLiveTailInput) (*StartLiveTailOutput, error) { - req, out := c.StartLiveTailRequest(input) - return out, req.Send() -} - -// StartLiveTailWithContext is the same as StartLiveTail with the addition of -// the ability to pass a context and additional request options. -// -// See StartLiveTail for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) StartLiveTailWithContext(ctx aws.Context, input *StartLiveTailInput, opts ...request.Option) (*StartLiveTailOutput, error) { - req, out := c.StartLiveTailRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -var _ awserr.Error -var _ time.Time - -// StartLiveTailEventStream provides the event stream handling for the StartLiveTail. -// -// For testing and mocking the event stream this type should be initialized via -// the NewStartLiveTailEventStream constructor function. Using the functional options -// to pass in nested mock behavior. -type StartLiveTailEventStream struct { - - // Reader is the EventStream reader for the StartLiveTailResponseStream - // events. This value is automatically set by the SDK when the API call is made - // Use this member when unit testing your code with the SDK to mock out the - // EventStream Reader. - // - // Must not be nil. - Reader StartLiveTailResponseStreamReader - - outputReader io.ReadCloser - output *StartLiveTailOutput - - done chan struct{} - closeOnce sync.Once - err *eventstreamapi.OnceError -} - -// NewStartLiveTailEventStream initializes an StartLiveTailEventStream. -// This function should only be used for testing and mocking the StartLiveTailEventStream -// stream within your application. -// -// The Reader member must be set before reading events from the stream. -// -// es := NewStartLiveTailEventStream(func(o *StartLiveTailEventStream){ -// es.Reader = myMockStreamReader -// }) -func NewStartLiveTailEventStream(opts ...func(*StartLiveTailEventStream)) *StartLiveTailEventStream { - es := &StartLiveTailEventStream{ - done: make(chan struct{}), - err: eventstreamapi.NewOnceError(), - } - - for _, fn := range opts { - fn(es) - } - - return es -} - -func (es *StartLiveTailEventStream) runOnStreamPartClose(r *request.Request) { - if es.done == nil { - return - } - go es.waitStreamPartClose() - -} - -func (es *StartLiveTailEventStream) waitStreamPartClose() { - var outputErrCh <-chan struct{} - if v, ok := es.Reader.(interface{ ErrorSet() <-chan struct{} }); ok { - outputErrCh = v.ErrorSet() - } - var outputClosedCh <-chan struct{} - if v, ok := es.Reader.(interface{ Closed() <-chan struct{} }); ok { - outputClosedCh = v.Closed() - } - - select { - case <-es.done: - case <-outputErrCh: - es.err.SetError(es.Reader.Err()) - es.Close() - case <-outputClosedCh: - if err := es.Reader.Err(); err != nil { - es.err.SetError(es.Reader.Err()) - } - es.Close() - } -} - -type eventTypeForStartLiveTailEventStreamOutputEvent struct { - unmarshalerForEvent func(string) (eventstreamapi.Unmarshaler, error) - output *StartLiveTailOutput -} - -func (e eventTypeForStartLiveTailEventStreamOutputEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) { - if eventType == "initial-response" { - return e.output, nil - } - return e.unmarshalerForEvent(eventType) -} - -// Events returns a channel to read events from. -// -// These events are: -// -// - LiveTailSessionStart -// - LiveTailSessionUpdate -// - StartLiveTailResponseStreamUnknownEvent -func (es *StartLiveTailEventStream) Events() <-chan StartLiveTailResponseStreamEvent { - return es.Reader.Events() -} - -func (es *StartLiveTailEventStream) runOutputStream(r *request.Request) { - var opts []func(*eventstream.Decoder) - if r.Config.Logger != nil && r.Config.LogLevel.Matches(aws.LogDebugWithEventStreamBody) { - opts = append(opts, eventstream.DecodeWithLogger(r.Config.Logger)) - } - - unmarshalerForEvent := unmarshalerForStartLiveTailResponseStreamEvent{ - metadata: protocol.ResponseMetadata{ - StatusCode: r.HTTPResponse.StatusCode, - RequestID: r.RequestID, - }, - }.UnmarshalerForEventName - unmarshalerForEvent = eventTypeForStartLiveTailEventStreamOutputEvent{ - unmarshalerForEvent: unmarshalerForEvent, - output: es.output, - }.UnmarshalerForEventName - - decoder := eventstream.NewDecoder(r.HTTPResponse.Body, opts...) - eventReader := eventstreamapi.NewEventReader(decoder, - protocol.HandlerPayloadUnmarshal{ - Unmarshalers: r.Handlers.UnmarshalStream, - }, - unmarshalerForEvent, - ) - - es.outputReader = r.HTTPResponse.Body - es.Reader = newReadStartLiveTailResponseStream(eventReader) -} -func (es *StartLiveTailEventStream) recvInitialEvent(r *request.Request) { - // Wait for the initial response event, which must be the first - // event to be received from the API. - select { - case event, ok := <-es.Events(): - if !ok { - return - } - - v, ok := event.(*StartLiveTailOutput) - if !ok || v == nil { - r.Error = awserr.New( - request.ErrCodeSerialization, - fmt.Sprintf("invalid event, %T, expect %T, %v", - event, (*StartLiveTailOutput)(nil), v), - nil, - ) - return - } - - *es.output = *v - es.output.eventStream = es - } -} - -// Close closes the stream. This will also cause the stream to be closed. -// Close must be called when done using the stream API. Not calling Close -// may result in resource leaks. -// -// You can use the closing of the Reader's Events channel to terminate your -// application's read from the API's stream. -func (es *StartLiveTailEventStream) Close() (err error) { - es.closeOnce.Do(es.safeClose) - return es.Err() -} - -func (es *StartLiveTailEventStream) safeClose() { - if es.done != nil { - close(es.done) - } - - es.Reader.Close() - if es.outputReader != nil { - es.outputReader.Close() - } -} - -// Err returns any error that occurred while reading or writing EventStream -// Events from the service API's response. Returns nil if there were no errors. -func (es *StartLiveTailEventStream) Err() error { - if err := es.err.Err(); err != nil { - return err - } - if err := es.Reader.Err(); err != nil { - return err - } - - return nil -} - -const opStartQuery = "StartQuery" - -// StartQueryRequest generates a "aws/request.Request" representing the -// client's request for the StartQuery operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See StartQuery for more information on using the StartQuery -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the StartQueryRequest method. -// req, resp := client.StartQueryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/StartQuery -func (c *CloudWatchLogs) StartQueryRequest(input *StartQueryInput) (req *request.Request, output *StartQueryOutput) { - op := &request.Operation{ - Name: opStartQuery, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &StartQueryInput{} - } - - output = &StartQueryOutput{} - req = c.newRequest(op, input, output) - return -} - -// StartQuery API operation for Amazon CloudWatch Logs. -// -// Schedules a query of a log group using CloudWatch Logs Insights. You specify -// the log group and time range to query and the query string to use. -// -// For more information, see CloudWatch Logs Insights Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). -// -// After you run a query using StartQuery, the query results are stored by CloudWatch -// Logs. You can use GetQueryResults (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetQueryResults.html) -// to retrieve the results of a query, using the queryId that StartQuery returns. -// -// If you have associated a KMS key with the query results in this account, -// then StartQuery (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html) -// uses that key to encrypt the results when it stores them. If no key is associated -// with query results, the query results are encrypted with the default CloudWatch -// Logs encryption method. -// -// Queries time out after 60 minutes of runtime. If your queries are timing -// out, reduce the time range being searched or partition your query into a -// number of queries. -// -// If you are using CloudWatch cross-account observability, you can use this -// operation in a monitoring account to start a query in a linked source account. -// For more information, see CloudWatch cross-account observability (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html). -// For a cross-account StartQuery operation, the query definition must be defined -// in the monitoring account. -// -// You can have up to 30 concurrent CloudWatch Logs insights queries, including -// queries that have been added to dashboards. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation StartQuery for usage and error information. -// -// Returned Error Types: -// -// - MalformedQueryException -// The query string is not valid. Details about this error are displayed in -// a QueryCompileError object. For more information, see QueryCompileError (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_QueryCompileError.html). -// -// For more information about valid query syntax, see CloudWatch Logs Insights -// Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - LimitExceededException -// You have reached the maximum number of resources that can be created. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/StartQuery -func (c *CloudWatchLogs) StartQuery(input *StartQueryInput) (*StartQueryOutput, error) { - req, out := c.StartQueryRequest(input) - return out, req.Send() -} - -// StartQueryWithContext is the same as StartQuery with the addition of -// the ability to pass a context and additional request options. -// -// See StartQuery for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) StartQueryWithContext(ctx aws.Context, input *StartQueryInput, opts ...request.Option) (*StartQueryOutput, error) { - req, out := c.StartQueryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opStopQuery = "StopQuery" - -// StopQueryRequest generates a "aws/request.Request" representing the -// client's request for the StopQuery operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See StopQuery for more information on using the StopQuery -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the StopQueryRequest method. -// req, resp := client.StopQueryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/StopQuery -func (c *CloudWatchLogs) StopQueryRequest(input *StopQueryInput) (req *request.Request, output *StopQueryOutput) { - op := &request.Operation{ - Name: opStopQuery, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &StopQueryInput{} - } - - output = &StopQueryOutput{} - req = c.newRequest(op, input, output) - return -} - -// StopQuery API operation for Amazon CloudWatch Logs. -// -// Stops a CloudWatch Logs Insights query that is in progress. If the query -// has already ended, the operation returns an error indicating that the specified -// query is not running. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation StopQuery for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/StopQuery -func (c *CloudWatchLogs) StopQuery(input *StopQueryInput) (*StopQueryOutput, error) { - req, out := c.StopQueryRequest(input) - return out, req.Send() -} - -// StopQueryWithContext is the same as StopQuery with the addition of -// the ability to pass a context and additional request options. -// -// See StopQuery for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) StopQueryWithContext(ctx aws.Context, input *StopQueryInput, opts ...request.Option) (*StopQueryOutput, error) { - req, out := c.StopQueryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opTagLogGroup = "TagLogGroup" - -// TagLogGroupRequest generates a "aws/request.Request" representing the -// client's request for the TagLogGroup operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See TagLogGroup for more information on using the TagLogGroup -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the TagLogGroupRequest method. -// req, resp := client.TagLogGroupRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/TagLogGroup -// -// Deprecated: Please use the generic tagging API TagResource -func (c *CloudWatchLogs) TagLogGroupRequest(input *TagLogGroupInput) (req *request.Request, output *TagLogGroupOutput) { - if c.Client.Config.Logger != nil { - c.Client.Config.Logger.Log("This operation, TagLogGroup, has been deprecated") - } - op := &request.Operation{ - Name: opTagLogGroup, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &TagLogGroupInput{} - } - - output = &TagLogGroupOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// TagLogGroup API operation for Amazon CloudWatch Logs. -// -// The TagLogGroup operation is on the path to deprecation. We recommend that -// you use TagResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_TagResource.html) -// instead. -// -// Adds or updates the specified tags for the specified log group. -// -// To list the tags for a log group, use ListTagsForResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListTagsForResource.html). -// To remove tags, use UntagResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UntagResource.html). -// -// For more information about tags, see Tag Log Groups in Amazon CloudWatch -// Logs (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#log-group-tagging) -// in the Amazon CloudWatch Logs User Guide. -// -// CloudWatch Logs doesn’t support IAM policies that prevent users from assigning -// specified tags to log groups using the aws:Resource/key-name or aws:TagKeys -// condition keys. For more information about using tags to control access, -// see Controlling access to Amazon Web Services resources using tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation TagLogGroup for usage and error information. -// -// Returned Error Types: -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/TagLogGroup -// -// Deprecated: Please use the generic tagging API TagResource -func (c *CloudWatchLogs) TagLogGroup(input *TagLogGroupInput) (*TagLogGroupOutput, error) { - req, out := c.TagLogGroupRequest(input) - return out, req.Send() -} - -// TagLogGroupWithContext is the same as TagLogGroup with the addition of -// the ability to pass a context and additional request options. -// -// See TagLogGroup for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -// -// Deprecated: Please use the generic tagging API TagResource -func (c *CloudWatchLogs) TagLogGroupWithContext(ctx aws.Context, input *TagLogGroupInput, opts ...request.Option) (*TagLogGroupOutput, error) { - req, out := c.TagLogGroupRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opTagResource = "TagResource" - -// TagResourceRequest generates a "aws/request.Request" representing the -// client's request for the TagResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See TagResource for more information on using the TagResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the TagResourceRequest method. -// req, resp := client.TagResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/TagResource -func (c *CloudWatchLogs) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { - op := &request.Operation{ - Name: opTagResource, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &TagResourceInput{} - } - - output = &TagResourceOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// TagResource API operation for Amazon CloudWatch Logs. -// -// Assigns one or more tags (key-value pairs) to the specified CloudWatch Logs -// resource. Currently, the only CloudWatch Logs resources that can be tagged -// are log groups and destinations. -// -// Tags can help you organize and categorize your resources. You can also use -// them to scope user permissions by granting a user permission to access or -// change only resources with certain tag values. -// -// Tags don't have any semantic meaning to Amazon Web Services and are interpreted -// strictly as strings of characters. -// -// You can use the TagResource action with a resource that already has tags. -// If you specify a new tag key for the alarm, this tag is appended to the list -// of tags associated with the alarm. If you specify a tag key that is already -// associated with the alarm, the new tag value that you specify replaces the -// previous value for that tag. -// -// You can associate as many as 50 tags with a CloudWatch Logs resource. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation TagResource for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - TooManyTagsException -// A resource can have no more than 50 tags. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/TagResource -func (c *CloudWatchLogs) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { - req, out := c.TagResourceRequest(input) - return out, req.Send() -} - -// TagResourceWithContext is the same as TagResource with the addition of -// the ability to pass a context and additional request options. -// -// See TagResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { - req, out := c.TagResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opTestMetricFilter = "TestMetricFilter" - -// TestMetricFilterRequest generates a "aws/request.Request" representing the -// client's request for the TestMetricFilter operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See TestMetricFilter for more information on using the TestMetricFilter -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the TestMetricFilterRequest method. -// req, resp := client.TestMetricFilterRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/TestMetricFilter -func (c *CloudWatchLogs) TestMetricFilterRequest(input *TestMetricFilterInput) (req *request.Request, output *TestMetricFilterOutput) { - op := &request.Operation{ - Name: opTestMetricFilter, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &TestMetricFilterInput{} - } - - output = &TestMetricFilterOutput{} - req = c.newRequest(op, input, output) - return -} - -// TestMetricFilter API operation for Amazon CloudWatch Logs. -// -// Tests the filter pattern of a metric filter against a sample of log event -// messages. You can use this operation to validate the correctness of a metric -// filter pattern. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation TestMetricFilter for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/TestMetricFilter -func (c *CloudWatchLogs) TestMetricFilter(input *TestMetricFilterInput) (*TestMetricFilterOutput, error) { - req, out := c.TestMetricFilterRequest(input) - return out, req.Send() -} - -// TestMetricFilterWithContext is the same as TestMetricFilter with the addition of -// the ability to pass a context and additional request options. -// -// See TestMetricFilter for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) TestMetricFilterWithContext(ctx aws.Context, input *TestMetricFilterInput, opts ...request.Option) (*TestMetricFilterOutput, error) { - req, out := c.TestMetricFilterRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUntagLogGroup = "UntagLogGroup" - -// UntagLogGroupRequest generates a "aws/request.Request" representing the -// client's request for the UntagLogGroup operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UntagLogGroup for more information on using the UntagLogGroup -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the UntagLogGroupRequest method. -// req, resp := client.UntagLogGroupRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UntagLogGroup -// -// Deprecated: Please use the generic tagging API UntagResource -func (c *CloudWatchLogs) UntagLogGroupRequest(input *UntagLogGroupInput) (req *request.Request, output *UntagLogGroupOutput) { - if c.Client.Config.Logger != nil { - c.Client.Config.Logger.Log("This operation, UntagLogGroup, has been deprecated") - } - op := &request.Operation{ - Name: opUntagLogGroup, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UntagLogGroupInput{} - } - - output = &UntagLogGroupOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// UntagLogGroup API operation for Amazon CloudWatch Logs. -// -// The UntagLogGroup operation is on the path to deprecation. We recommend that -// you use UntagResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UntagResource.html) -// instead. -// -// Removes the specified tags from the specified log group. -// -// To list the tags for a log group, use ListTagsForResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListTagsForResource.html). -// To add tags, use TagResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_TagResource.html). -// -// CloudWatch Logs doesn’t support IAM policies that prevent users from assigning -// specified tags to log groups using the aws:Resource/key-name or aws:TagKeys -// condition keys. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation UntagLogGroup for usage and error information. -// -// Returned Error Types: -// - ResourceNotFoundException -// The specified resource does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UntagLogGroup -// -// Deprecated: Please use the generic tagging API UntagResource -func (c *CloudWatchLogs) UntagLogGroup(input *UntagLogGroupInput) (*UntagLogGroupOutput, error) { - req, out := c.UntagLogGroupRequest(input) - return out, req.Send() -} - -// UntagLogGroupWithContext is the same as UntagLogGroup with the addition of -// the ability to pass a context and additional request options. -// -// See UntagLogGroup for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -// -// Deprecated: Please use the generic tagging API UntagResource -func (c *CloudWatchLogs) UntagLogGroupWithContext(ctx aws.Context, input *UntagLogGroupInput, opts ...request.Option) (*UntagLogGroupOutput, error) { - req, out := c.UntagLogGroupRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUntagResource = "UntagResource" - -// UntagResourceRequest generates a "aws/request.Request" representing the -// client's request for the UntagResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UntagResource for more information on using the UntagResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the UntagResourceRequest method. -// req, resp := client.UntagResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UntagResource -func (c *CloudWatchLogs) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { - op := &request.Operation{ - Name: opUntagResource, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UntagResourceInput{} - } - - output = &UntagResourceOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// UntagResource API operation for Amazon CloudWatch Logs. -// -// Removes one or more tags from the specified resource. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation UntagResource for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UntagResource -func (c *CloudWatchLogs) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { - req, out := c.UntagResourceRequest(input) - return out, req.Send() -} - -// UntagResourceWithContext is the same as UntagResource with the addition of -// the ability to pass a context and additional request options. -// -// See UntagResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { - req, out := c.UntagResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateAnomaly = "UpdateAnomaly" - -// UpdateAnomalyRequest generates a "aws/request.Request" representing the -// client's request for the UpdateAnomaly operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateAnomaly for more information on using the UpdateAnomaly -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the UpdateAnomalyRequest method. -// req, resp := client.UpdateAnomalyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UpdateAnomaly -func (c *CloudWatchLogs) UpdateAnomalyRequest(input *UpdateAnomalyInput) (req *request.Request, output *UpdateAnomalyOutput) { - op := &request.Operation{ - Name: opUpdateAnomaly, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UpdateAnomalyInput{} - } - - output = &UpdateAnomalyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// UpdateAnomaly API operation for Amazon CloudWatch Logs. -// -// Use this operation to suppress anomaly detection for a specified anomaly -// or pattern. If you suppress an anomaly, CloudWatch Logs won’t report new -// occurrences of that anomaly and won't update that anomaly with new data. -// If you suppress a pattern, CloudWatch Logs won’t report any anomalies related -// to that pattern. -// -// You must specify either anomalyId or patternId, but you can't specify both -// parameters in the same operation. -// -// If you have previously used this operation to suppress detection of a pattern -// or anomaly, you can use it again to cause CloudWatch Logs to end the suppression. -// To do this, use this operation and specify the anomaly or pattern to stop -// suppressing, and omit the suppressionType and suppressionPeriod parameters. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation UpdateAnomaly for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UpdateAnomaly -func (c *CloudWatchLogs) UpdateAnomaly(input *UpdateAnomalyInput) (*UpdateAnomalyOutput, error) { - req, out := c.UpdateAnomalyRequest(input) - return out, req.Send() -} - -// UpdateAnomalyWithContext is the same as UpdateAnomaly with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateAnomaly for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) UpdateAnomalyWithContext(ctx aws.Context, input *UpdateAnomalyInput, opts ...request.Option) (*UpdateAnomalyOutput, error) { - req, out := c.UpdateAnomalyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateLogAnomalyDetector = "UpdateLogAnomalyDetector" - -// UpdateLogAnomalyDetectorRequest generates a "aws/request.Request" representing the -// client's request for the UpdateLogAnomalyDetector operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateLogAnomalyDetector for more information on using the UpdateLogAnomalyDetector -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the UpdateLogAnomalyDetectorRequest method. -// req, resp := client.UpdateLogAnomalyDetectorRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UpdateLogAnomalyDetector -func (c *CloudWatchLogs) UpdateLogAnomalyDetectorRequest(input *UpdateLogAnomalyDetectorInput) (req *request.Request, output *UpdateLogAnomalyDetectorOutput) { - op := &request.Operation{ - Name: opUpdateLogAnomalyDetector, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UpdateLogAnomalyDetectorInput{} - } - - output = &UpdateLogAnomalyDetectorOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// UpdateLogAnomalyDetector API operation for Amazon CloudWatch Logs. -// -// Updates an existing log anomaly detector. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon CloudWatch Logs's -// API operation UpdateLogAnomalyDetector for usage and error information. -// -// Returned Error Types: -// -// - InvalidParameterException -// A parameter is specified incorrectly. -// -// - ResourceNotFoundException -// The specified resource does not exist. -// -// - ServiceUnavailableException -// The service cannot complete the request. -// -// - OperationAbortedException -// Multiple concurrent requests to update the same resource were in conflict. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/UpdateLogAnomalyDetector -func (c *CloudWatchLogs) UpdateLogAnomalyDetector(input *UpdateLogAnomalyDetectorInput) (*UpdateLogAnomalyDetectorOutput, error) { - req, out := c.UpdateLogAnomalyDetectorRequest(input) - return out, req.Send() -} - -// UpdateLogAnomalyDetectorWithContext is the same as UpdateLogAnomalyDetector with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateLogAnomalyDetector for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *CloudWatchLogs) UpdateLogAnomalyDetectorWithContext(ctx aws.Context, input *UpdateLogAnomalyDetectorInput, opts ...request.Option) (*UpdateLogAnomalyDetectorOutput, error) { - req, out := c.UpdateLogAnomalyDetectorRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// You don't have sufficient permissions to perform this action. -type AccessDeniedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AccessDeniedException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AccessDeniedException) GoString() string { - return s.String() -} - -func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { - return &AccessDeniedException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *AccessDeniedException) Code() string { - return "AccessDeniedException" -} - -// Message returns the exception's message. -func (s *AccessDeniedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *AccessDeniedException) OrigErr() error { - return nil -} - -func (s *AccessDeniedException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *AccessDeniedException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *AccessDeniedException) RequestID() string { - return s.RespMetadata.RequestID -} - -// A structure that contains information about one CloudWatch Logs account policy. -type AccountPolicy struct { - _ struct{} `type:"structure"` - - // The Amazon Web Services account ID that the policy applies to. - AccountId *string `locationName:"accountId" min:"12" type:"string"` - - // The date and time that this policy was most recently updated. - LastUpdatedTime *int64 `locationName:"lastUpdatedTime" type:"long"` - - // The policy document for this account policy. - // - // The JSON specified in policyDocument can be up to 30,720 characters. - PolicyDocument *string `locationName:"policyDocument" type:"string"` - - // The name of the account policy. - PolicyName *string `locationName:"policyName" type:"string"` - - // The type of policy for this account policy. - PolicyType *string `locationName:"policyType" type:"string" enum:"PolicyType"` - - // The scope of the account policy. - Scope *string `locationName:"scope" type:"string" enum:"Scope"` - - // The log group selection criteria for this subscription filter policy. - SelectionCriteria *string `locationName:"selectionCriteria" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AccountPolicy) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AccountPolicy) GoString() string { - return s.String() -} - -// SetAccountId sets the AccountId field's value. -func (s *AccountPolicy) SetAccountId(v string) *AccountPolicy { - s.AccountId = &v - return s -} - -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *AccountPolicy) SetLastUpdatedTime(v int64) *AccountPolicy { - s.LastUpdatedTime = &v - return s -} - -// SetPolicyDocument sets the PolicyDocument field's value. -func (s *AccountPolicy) SetPolicyDocument(v string) *AccountPolicy { - s.PolicyDocument = &v - return s -} - -// SetPolicyName sets the PolicyName field's value. -func (s *AccountPolicy) SetPolicyName(v string) *AccountPolicy { - s.PolicyName = &v - return s -} - -// SetPolicyType sets the PolicyType field's value. -func (s *AccountPolicy) SetPolicyType(v string) *AccountPolicy { - s.PolicyType = &v - return s -} - -// SetScope sets the Scope field's value. -func (s *AccountPolicy) SetScope(v string) *AccountPolicy { - s.Scope = &v - return s -} - -// SetSelectionCriteria sets the SelectionCriteria field's value. -func (s *AccountPolicy) SetSelectionCriteria(v string) *AccountPolicy { - s.SelectionCriteria = &v - return s -} - -// This structure represents one anomaly that has been found by a logs anomaly -// detector. -// -// For more information about patterns and anomalies, see CreateLogAnomalyDetector -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateLogAnomalyDetector.html). -type Anomaly struct { - _ struct{} `type:"structure"` - - // Specifies whether this anomaly is still ongoing. - // - // Active is a required field - Active *bool `locationName:"active" type:"boolean" required:"true"` - - // The ARN of the anomaly detector that identified this anomaly. - // - // AnomalyDetectorArn is a required field - AnomalyDetectorArn *string `locationName:"anomalyDetectorArn" min:"1" type:"string" required:"true"` - - // The unique ID that CloudWatch Logs assigned to this anomaly. - // - // AnomalyId is a required field - AnomalyId *string `locationName:"anomalyId" min:"36" type:"string" required:"true"` - - // A human-readable description of the anomaly. This description is generated - // by CloudWatch Logs. - // - // Description is a required field - Description *string `locationName:"description" min:"1" type:"string" required:"true"` - - // The date and time when the anomaly detector first saw this anomaly. It is - // specified as epoch time, which is the number of seconds since January 1, - // 1970, 00:00:00 UTC. - // - // FirstSeen is a required field - FirstSeen *int64 `locationName:"firstSeen" type:"long" required:"true"` - - // A map showing times when the anomaly detector ran, and the number of occurrences - // of this anomaly that were detected at each of those runs. The times are specified - // in epoch time, which is the number of seconds since January 1, 1970, 00:00:00 - // UTC. - // - // Histogram is a required field - Histogram map[string]*int64 `locationName:"histogram" type:"map" required:"true"` - - // If this anomaly is suppressed, this field is true if the suppression is because - // the pattern is suppressed. If false, then only this particular anomaly is - // suppressed. - IsPatternLevelSuppression *bool `locationName:"isPatternLevelSuppression" type:"boolean"` - - // The date and time when the anomaly detector most recently saw this anomaly. - // It is specified as epoch time, which is the number of seconds since January - // 1, 1970, 00:00:00 UTC. - // - // LastSeen is a required field - LastSeen *int64 `locationName:"lastSeen" type:"long" required:"true"` - - // An array of ARNS of the log groups that contained log events considered to - // be part of this anomaly. - // - // LogGroupArnList is a required field - LogGroupArnList []*string `locationName:"logGroupArnList" type:"list" required:"true"` - - // An array of sample log event messages that are considered to be part of this - // anomaly. - // - // LogSamples is a required field - LogSamples []*LogEvent `locationName:"logSamples" type:"list" required:"true"` - - // The ID of the pattern used to help identify this anomaly. - // - // PatternId is a required field - PatternId *string `locationName:"patternId" min:"32" type:"string" required:"true"` - - // The pattern used to help identify this anomaly, in regular expression format. - PatternRegex *string `locationName:"patternRegex" min:"1" type:"string"` - - // The pattern used to help identify this anomaly, in string format. - // - // PatternString is a required field - PatternString *string `locationName:"patternString" min:"1" type:"string" required:"true"` - - // An array of structures where each structure contains information about one - // token that makes up the pattern. - // - // PatternTokens is a required field - PatternTokens []*PatternToken `locationName:"patternTokens" type:"list" required:"true"` - - // The priority level of this anomaly, as determined by CloudWatch Logs. Priority - // is computed based on log severity labels such as FATAL and ERROR and the - // amount of deviation from the baseline. Possible values are HIGH, MEDIUM, - // and LOW. - Priority *string `locationName:"priority" min:"1" type:"string"` - - // Indicates the current state of this anomaly. If it is still being treated - // as an anomaly, the value is Active. If you have suppressed this anomaly by - // using the UpdateAnomaly (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UpdateAnomaly.html) - // operation, the value is Suppressed. If this behavior is now considered to - // be normal, the value is Baseline. - // - // State is a required field - State *string `locationName:"state" type:"string" required:"true" enum:"State"` - - // Indicates whether this anomaly is currently suppressed. To suppress an anomaly, - // use UpdateAnomaly (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UpdateAnomaly.html). - Suppressed *bool `locationName:"suppressed" type:"boolean"` - - // If the anomaly is suppressed, this indicates when it was suppressed. - SuppressedDate *int64 `locationName:"suppressedDate" type:"long"` - - // If the anomaly is suppressed, this indicates when the suppression will end. - // If this value is 0, the anomaly was suppressed with no expiration, with the - // INFINITE value. - SuppressedUntil *int64 `locationName:"suppressedUntil" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Anomaly) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Anomaly) GoString() string { - return s.String() -} - -// SetActive sets the Active field's value. -func (s *Anomaly) SetActive(v bool) *Anomaly { - s.Active = &v - return s -} - -// SetAnomalyDetectorArn sets the AnomalyDetectorArn field's value. -func (s *Anomaly) SetAnomalyDetectorArn(v string) *Anomaly { - s.AnomalyDetectorArn = &v - return s -} - -// SetAnomalyId sets the AnomalyId field's value. -func (s *Anomaly) SetAnomalyId(v string) *Anomaly { - s.AnomalyId = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *Anomaly) SetDescription(v string) *Anomaly { - s.Description = &v - return s -} - -// SetFirstSeen sets the FirstSeen field's value. -func (s *Anomaly) SetFirstSeen(v int64) *Anomaly { - s.FirstSeen = &v - return s -} - -// SetHistogram sets the Histogram field's value. -func (s *Anomaly) SetHistogram(v map[string]*int64) *Anomaly { - s.Histogram = v - return s -} - -// SetIsPatternLevelSuppression sets the IsPatternLevelSuppression field's value. -func (s *Anomaly) SetIsPatternLevelSuppression(v bool) *Anomaly { - s.IsPatternLevelSuppression = &v - return s -} - -// SetLastSeen sets the LastSeen field's value. -func (s *Anomaly) SetLastSeen(v int64) *Anomaly { - s.LastSeen = &v - return s -} - -// SetLogGroupArnList sets the LogGroupArnList field's value. -func (s *Anomaly) SetLogGroupArnList(v []*string) *Anomaly { - s.LogGroupArnList = v - return s -} - -// SetLogSamples sets the LogSamples field's value. -func (s *Anomaly) SetLogSamples(v []*LogEvent) *Anomaly { - s.LogSamples = v - return s -} - -// SetPatternId sets the PatternId field's value. -func (s *Anomaly) SetPatternId(v string) *Anomaly { - s.PatternId = &v - return s -} - -// SetPatternRegex sets the PatternRegex field's value. -func (s *Anomaly) SetPatternRegex(v string) *Anomaly { - s.PatternRegex = &v - return s -} - -// SetPatternString sets the PatternString field's value. -func (s *Anomaly) SetPatternString(v string) *Anomaly { - s.PatternString = &v - return s -} - -// SetPatternTokens sets the PatternTokens field's value. -func (s *Anomaly) SetPatternTokens(v []*PatternToken) *Anomaly { - s.PatternTokens = v - return s -} - -// SetPriority sets the Priority field's value. -func (s *Anomaly) SetPriority(v string) *Anomaly { - s.Priority = &v - return s -} - -// SetState sets the State field's value. -func (s *Anomaly) SetState(v string) *Anomaly { - s.State = &v - return s -} - -// SetSuppressed sets the Suppressed field's value. -func (s *Anomaly) SetSuppressed(v bool) *Anomaly { - s.Suppressed = &v - return s -} - -// SetSuppressedDate sets the SuppressedDate field's value. -func (s *Anomaly) SetSuppressedDate(v int64) *Anomaly { - s.SuppressedDate = &v - return s -} - -// SetSuppressedUntil sets the SuppressedUntil field's value. -func (s *Anomaly) SetSuppressedUntil(v int64) *Anomaly { - s.SuppressedUntil = &v - return s -} - -// Contains information about one anomaly detector in the account. -type AnomalyDetector struct { - _ struct{} `type:"structure"` - - // The ARN of the anomaly detector. - AnomalyDetectorArn *string `locationName:"anomalyDetectorArn" min:"1" type:"string"` - - // Specifies the current status of the anomaly detector. To pause an anomaly - // detector, use the enabled parameter in the UpdateLogAnomalyDetector (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UpdateLogAnomalyDetector.html) - // operation. - AnomalyDetectorStatus *string `locationName:"anomalyDetectorStatus" type:"string" enum:"AnomalyDetectorStatus"` - - // The number of days used as the life cycle of anomalies. After this time, - // anomalies are automatically baselined and the anomaly detector model will - // treat new occurrences of similar event as normal. - AnomalyVisibilityTime *int64 `locationName:"anomalyVisibilityTime" min:"7" type:"long"` - - // The date and time when this anomaly detector was created. - CreationTimeStamp *int64 `locationName:"creationTimeStamp" type:"long"` - - // The name of the anomaly detector. - DetectorName *string `locationName:"detectorName" min:"1" type:"string"` - - // Specifies how often the anomaly detector runs and look for anomalies. - EvaluationFrequency *string `locationName:"evaluationFrequency" type:"string" enum:"EvaluationFrequency"` - - // A symbolic description of how CloudWatch Logs should interpret the data in - // each log event. For example, a log event can contain timestamps, IP addresses, - // strings, and so on. You use the filter pattern to specify what to look for - // in the log event message. - FilterPattern *string `locationName:"filterPattern" type:"string"` - - // The ID of the KMS key assigned to this anomaly detector, if any. - KmsKeyId *string `locationName:"kmsKeyId" type:"string"` - - // The date and time when this anomaly detector was most recently modified. - LastModifiedTimeStamp *int64 `locationName:"lastModifiedTimeStamp" type:"long"` - - // A list of the ARNs of the log groups that this anomaly detector watches. - LogGroupArnList []*string `locationName:"logGroupArnList" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AnomalyDetector) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AnomalyDetector) GoString() string { - return s.String() -} - -// SetAnomalyDetectorArn sets the AnomalyDetectorArn field's value. -func (s *AnomalyDetector) SetAnomalyDetectorArn(v string) *AnomalyDetector { - s.AnomalyDetectorArn = &v - return s -} - -// SetAnomalyDetectorStatus sets the AnomalyDetectorStatus field's value. -func (s *AnomalyDetector) SetAnomalyDetectorStatus(v string) *AnomalyDetector { - s.AnomalyDetectorStatus = &v - return s -} - -// SetAnomalyVisibilityTime sets the AnomalyVisibilityTime field's value. -func (s *AnomalyDetector) SetAnomalyVisibilityTime(v int64) *AnomalyDetector { - s.AnomalyVisibilityTime = &v - return s -} - -// SetCreationTimeStamp sets the CreationTimeStamp field's value. -func (s *AnomalyDetector) SetCreationTimeStamp(v int64) *AnomalyDetector { - s.CreationTimeStamp = &v - return s -} - -// SetDetectorName sets the DetectorName field's value. -func (s *AnomalyDetector) SetDetectorName(v string) *AnomalyDetector { - s.DetectorName = &v - return s -} - -// SetEvaluationFrequency sets the EvaluationFrequency field's value. -func (s *AnomalyDetector) SetEvaluationFrequency(v string) *AnomalyDetector { - s.EvaluationFrequency = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *AnomalyDetector) SetFilterPattern(v string) *AnomalyDetector { - s.FilterPattern = &v - return s -} - -// SetKmsKeyId sets the KmsKeyId field's value. -func (s *AnomalyDetector) SetKmsKeyId(v string) *AnomalyDetector { - s.KmsKeyId = &v - return s -} - -// SetLastModifiedTimeStamp sets the LastModifiedTimeStamp field's value. -func (s *AnomalyDetector) SetLastModifiedTimeStamp(v int64) *AnomalyDetector { - s.LastModifiedTimeStamp = &v - return s -} - -// SetLogGroupArnList sets the LogGroupArnList field's value. -func (s *AnomalyDetector) SetLogGroupArnList(v []*string) *AnomalyDetector { - s.LogGroupArnList = v - return s -} - -type AssociateKmsKeyInput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the KMS key to use when encrypting log - // data. This must be a symmetric KMS key. For more information, see Amazon - // Resource Names (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kms) - // and Using Symmetric and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html). - // - // KmsKeyId is a required field - KmsKeyId *string `locationName:"kmsKeyId" type:"string" required:"true"` - - // The name of the log group. - // - // In your AssociateKmsKey operation, you must specify either the resourceIdentifier - // parameter or the logGroup parameter, but you can't specify both. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // Specifies the target for this operation. You must specify one of the following: - // - // * Specify the following ARN to have future GetQueryResults (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetQueryResults.html) - // operations in this account encrypt the results with the specified KMS - // key. Replace REGION and ACCOUNT_ID with your Region and account ID. arn:aws:logs:REGION:ACCOUNT_ID:query-result:* - // - // * Specify the ARN of a log group to have CloudWatch Logs use the KMS key - // to encrypt log events that are ingested and stored by that log group. - // The log group ARN must be in the following format. Replace REGION and - // ACCOUNT_ID with your Region and account ID. arn:aws:logs:REGION:ACCOUNT_ID:log-group:LOG_GROUP_NAME - // - // In your AssociateKmsKey operation, you must specify either the resourceIdentifier - // parameter or the logGroup parameter, but you can't specify both. - ResourceIdentifier *string `locationName:"resourceIdentifier" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssociateKmsKeyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssociateKmsKeyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssociateKmsKeyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssociateKmsKeyInput"} - if s.KmsKeyId == nil { - invalidParams.Add(request.NewErrParamRequired("KmsKeyId")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.ResourceIdentifier != nil && len(*s.ResourceIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceIdentifier", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKmsKeyId sets the KmsKeyId field's value. -func (s *AssociateKmsKeyInput) SetKmsKeyId(v string) *AssociateKmsKeyInput { - s.KmsKeyId = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *AssociateKmsKeyInput) SetLogGroupName(v string) *AssociateKmsKeyInput { - s.LogGroupName = &v - return s -} - -// SetResourceIdentifier sets the ResourceIdentifier field's value. -func (s *AssociateKmsKeyInput) SetResourceIdentifier(v string) *AssociateKmsKeyInput { - s.ResourceIdentifier = &v - return s -} - -type AssociateKmsKeyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssociateKmsKeyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssociateKmsKeyOutput) GoString() string { - return s.String() -} - -type CancelExportTaskInput struct { - _ struct{} `type:"structure"` - - // The ID of the export task. - // - // TaskId is a required field - TaskId *string `locationName:"taskId" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CancelExportTaskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CancelExportTaskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CancelExportTaskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CancelExportTaskInput"} - if s.TaskId == nil { - invalidParams.Add(request.NewErrParamRequired("TaskId")) - } - if s.TaskId != nil && len(*s.TaskId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TaskId", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetTaskId sets the TaskId field's value. -func (s *CancelExportTaskInput) SetTaskId(v string) *CancelExportTaskInput { - s.TaskId = &v - return s -} - -type CancelExportTaskOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CancelExportTaskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CancelExportTaskOutput) GoString() string { - return s.String() -} - -// This operation attempted to create a resource that already exists. -type ConflictException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ConflictException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ConflictException) GoString() string { - return s.String() -} - -func newErrorConflictException(v protocol.ResponseMetadata) error { - return &ConflictException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ConflictException) Code() string { - return "ConflictException" -} - -// Message returns the exception's message. -func (s *ConflictException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ConflictException) OrigErr() error { - return nil -} - -func (s *ConflictException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ConflictException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ConflictException) RequestID() string { - return s.RespMetadata.RequestID -} - -type CreateDeliveryInput struct { - _ struct{} `type:"structure"` - - // The ARN of the delivery destination to use for this delivery. - // - // DeliveryDestinationArn is a required field - DeliveryDestinationArn *string `locationName:"deliveryDestinationArn" type:"string" required:"true"` - - // The name of the delivery source to use for this delivery. - // - // DeliverySourceName is a required field - DeliverySourceName *string `locationName:"deliverySourceName" min:"1" type:"string" required:"true"` - - // An optional list of key-value pairs to associate with the resource. - // - // For more information about tagging, see Tagging Amazon Web Services resources - // (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateDeliveryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateDeliveryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDeliveryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDeliveryInput"} - if s.DeliveryDestinationArn == nil { - invalidParams.Add(request.NewErrParamRequired("DeliveryDestinationArn")) - } - if s.DeliverySourceName == nil { - invalidParams.Add(request.NewErrParamRequired("DeliverySourceName")) - } - if s.DeliverySourceName != nil && len(*s.DeliverySourceName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DeliverySourceName", 1)) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDeliveryDestinationArn sets the DeliveryDestinationArn field's value. -func (s *CreateDeliveryInput) SetDeliveryDestinationArn(v string) *CreateDeliveryInput { - s.DeliveryDestinationArn = &v - return s -} - -// SetDeliverySourceName sets the DeliverySourceName field's value. -func (s *CreateDeliveryInput) SetDeliverySourceName(v string) *CreateDeliveryInput { - s.DeliverySourceName = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *CreateDeliveryInput) SetTags(v map[string]*string) *CreateDeliveryInput { - s.Tags = v - return s -} - -type CreateDeliveryOutput struct { - _ struct{} `type:"structure"` - - // A structure that contains information about the delivery that you just created. - Delivery *Delivery `locationName:"delivery" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateDeliveryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateDeliveryOutput) GoString() string { - return s.String() -} - -// SetDelivery sets the Delivery field's value. -func (s *CreateDeliveryOutput) SetDelivery(v *Delivery) *CreateDeliveryOutput { - s.Delivery = v - return s -} - -type CreateExportTaskInput struct { - _ struct{} `type:"structure"` - - // The name of S3 bucket for the exported log data. The bucket must be in the - // same Amazon Web Services Region. - // - // Destination is a required field - Destination *string `locationName:"destination" min:"1" type:"string" required:"true"` - - // The prefix used as the start of the key for every object exported. If you - // don't specify a value, the default is exportedlogs. - DestinationPrefix *string `locationName:"destinationPrefix" type:"string"` - - // The start time of the range for the request, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. Events with a timestamp earlier than this - // time are not exported. - // - // From is a required field - From *int64 `locationName:"from" type:"long" required:"true"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // Export only log streams that match the provided prefix. If you don't specify - // a value, no prefix filter is applied. - LogStreamNamePrefix *string `locationName:"logStreamNamePrefix" min:"1" type:"string"` - - // The name of the export task. - TaskName *string `locationName:"taskName" min:"1" type:"string"` - - // The end time of the range for the request, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time - // are not exported. - // - // You must specify a time that is not earlier than when this log group was - // created. - // - // To is a required field - To *int64 `locationName:"to" type:"long" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateExportTaskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateExportTaskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateExportTaskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateExportTaskInput"} - if s.Destination == nil { - invalidParams.Add(request.NewErrParamRequired("Destination")) - } - if s.Destination != nil && len(*s.Destination) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Destination", 1)) - } - if s.From == nil { - invalidParams.Add(request.NewErrParamRequired("From")) - } - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.LogStreamNamePrefix != nil && len(*s.LogStreamNamePrefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamNamePrefix", 1)) - } - if s.TaskName != nil && len(*s.TaskName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TaskName", 1)) - } - if s.To == nil { - invalidParams.Add(request.NewErrParamRequired("To")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestination sets the Destination field's value. -func (s *CreateExportTaskInput) SetDestination(v string) *CreateExportTaskInput { - s.Destination = &v - return s -} - -// SetDestinationPrefix sets the DestinationPrefix field's value. -func (s *CreateExportTaskInput) SetDestinationPrefix(v string) *CreateExportTaskInput { - s.DestinationPrefix = &v - return s -} - -// SetFrom sets the From field's value. -func (s *CreateExportTaskInput) SetFrom(v int64) *CreateExportTaskInput { - s.From = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *CreateExportTaskInput) SetLogGroupName(v string) *CreateExportTaskInput { - s.LogGroupName = &v - return s -} - -// SetLogStreamNamePrefix sets the LogStreamNamePrefix field's value. -func (s *CreateExportTaskInput) SetLogStreamNamePrefix(v string) *CreateExportTaskInput { - s.LogStreamNamePrefix = &v - return s -} - -// SetTaskName sets the TaskName field's value. -func (s *CreateExportTaskInput) SetTaskName(v string) *CreateExportTaskInput { - s.TaskName = &v - return s -} - -// SetTo sets the To field's value. -func (s *CreateExportTaskInput) SetTo(v int64) *CreateExportTaskInput { - s.To = &v - return s -} - -type CreateExportTaskOutput struct { - _ struct{} `type:"structure"` - - // The ID of the export task. - TaskId *string `locationName:"taskId" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateExportTaskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateExportTaskOutput) GoString() string { - return s.String() -} - -// SetTaskId sets the TaskId field's value. -func (s *CreateExportTaskOutput) SetTaskId(v string) *CreateExportTaskOutput { - s.TaskId = &v - return s -} - -type CreateLogAnomalyDetectorInput struct { - _ struct{} `type:"structure"` - - // The number of days to have visibility on an anomaly. After this time period - // has elapsed for an anomaly, it will be automatically baselined and the anomaly - // detector will treat new occurrences of a similar anomaly as normal. Therefore, - // if you do not correct the cause of an anomaly during the time period specified - // in anomalyVisibilityTime, it will be considered normal going forward and - // will not be detected as an anomaly. - AnomalyVisibilityTime *int64 `locationName:"anomalyVisibilityTime" min:"7" type:"long"` - - // A name for this anomaly detector. - DetectorName *string `locationName:"detectorName" min:"1" type:"string"` - - // Specifies how often the anomaly detector is to run and look for anomalies. - // Set this value according to the frequency that the log group receives new - // logs. For example, if the log group receives new log events every 10 minutes, - // then 15 minutes might be a good setting for evaluationFrequency . - EvaluationFrequency *string `locationName:"evaluationFrequency" type:"string" enum:"EvaluationFrequency"` - - // You can use this parameter to limit the anomaly detection model to examine - // only log events that match the pattern you specify here. For more information, - // see Filter and Pattern Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html). - FilterPattern *string `locationName:"filterPattern" type:"string"` - - // Optionally assigns a KMS key to secure this anomaly detector and its findings. - // If a key is assigned, the anomalies found and the model used by this detector - // are encrypted at rest with the key. If a key is assigned to an anomaly detector, - // a user must have permissions for both this key and for the anomaly detector - // to retrieve information about the anomalies that it finds. - // - // For more information about using a KMS key and to see the required IAM policy, - // see Use a KMS key with an anomaly detector (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/LogsAnomalyDetection-KMS.html). - KmsKeyId *string `locationName:"kmsKeyId" type:"string"` - - // An array containing the ARN of the log group that this anomaly detector will - // watch. You can specify only one log group ARN. - // - // LogGroupArnList is a required field - LogGroupArnList []*string `locationName:"logGroupArnList" type:"list" required:"true"` - - // An optional list of key-value pairs to associate with the resource. - // - // For more information about tagging, see Tagging Amazon Web Services resources - // (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogAnomalyDetectorInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogAnomalyDetectorInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLogAnomalyDetectorInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLogAnomalyDetectorInput"} - if s.AnomalyVisibilityTime != nil && *s.AnomalyVisibilityTime < 7 { - invalidParams.Add(request.NewErrParamMinValue("AnomalyVisibilityTime", 7)) - } - if s.DetectorName != nil && len(*s.DetectorName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DetectorName", 1)) - } - if s.LogGroupArnList == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupArnList")) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnomalyVisibilityTime sets the AnomalyVisibilityTime field's value. -func (s *CreateLogAnomalyDetectorInput) SetAnomalyVisibilityTime(v int64) *CreateLogAnomalyDetectorInput { - s.AnomalyVisibilityTime = &v - return s -} - -// SetDetectorName sets the DetectorName field's value. -func (s *CreateLogAnomalyDetectorInput) SetDetectorName(v string) *CreateLogAnomalyDetectorInput { - s.DetectorName = &v - return s -} - -// SetEvaluationFrequency sets the EvaluationFrequency field's value. -func (s *CreateLogAnomalyDetectorInput) SetEvaluationFrequency(v string) *CreateLogAnomalyDetectorInput { - s.EvaluationFrequency = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *CreateLogAnomalyDetectorInput) SetFilterPattern(v string) *CreateLogAnomalyDetectorInput { - s.FilterPattern = &v - return s -} - -// SetKmsKeyId sets the KmsKeyId field's value. -func (s *CreateLogAnomalyDetectorInput) SetKmsKeyId(v string) *CreateLogAnomalyDetectorInput { - s.KmsKeyId = &v - return s -} - -// SetLogGroupArnList sets the LogGroupArnList field's value. -func (s *CreateLogAnomalyDetectorInput) SetLogGroupArnList(v []*string) *CreateLogAnomalyDetectorInput { - s.LogGroupArnList = v - return s -} - -// SetTags sets the Tags field's value. -func (s *CreateLogAnomalyDetectorInput) SetTags(v map[string]*string) *CreateLogAnomalyDetectorInput { - s.Tags = v - return s -} - -type CreateLogAnomalyDetectorOutput struct { - _ struct{} `type:"structure"` - - // The ARN of the log anomaly detector that you just created. - AnomalyDetectorArn *string `locationName:"anomalyDetectorArn" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogAnomalyDetectorOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogAnomalyDetectorOutput) GoString() string { - return s.String() -} - -// SetAnomalyDetectorArn sets the AnomalyDetectorArn field's value. -func (s *CreateLogAnomalyDetectorOutput) SetAnomalyDetectorArn(v string) *CreateLogAnomalyDetectorOutput { - s.AnomalyDetectorArn = &v - return s -} - -type CreateLogGroupInput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the KMS key to use when encrypting log - // data. For more information, see Amazon Resource Names (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kms). - KmsKeyId *string `locationName:"kmsKeyId" type:"string"` - - // Use this parameter to specify the log group class for this log group. There - // are two classes: - // - // * The Standard log class supports all CloudWatch Logs features. - // - // * The Infrequent Access log class supports a subset of CloudWatch Logs - // features and incurs lower costs. - // - // If you omit this parameter, the default of STANDARD is used. - // - // The value of logGroupClass can't be changed after a log group is created. - // - // For details about the features supported by each class, see Log classes (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch_Logs_Log_Classes.html) - LogGroupClass *string `locationName:"logGroupClass" type:"string" enum:"LogGroupClass"` - - // A name for the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The key-value pairs to use for the tags. - // - // You can grant users access to certain log groups while preventing them from - // accessing other log groups. To do so, tag your groups and use IAM policies - // that refer to those tags. To assign tags when you create a log group, you - // must have either the logs:TagResource or logs:TagLogGroup permission. For - // more information about tagging, see Tagging Amazon Web Services resources - // (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html). For more - // information about using tags to control access, see Controlling access to - // Amazon Web Services resources using tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html). - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogGroupInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogGroupInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLogGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLogGroupInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKmsKeyId sets the KmsKeyId field's value. -func (s *CreateLogGroupInput) SetKmsKeyId(v string) *CreateLogGroupInput { - s.KmsKeyId = &v - return s -} - -// SetLogGroupClass sets the LogGroupClass field's value. -func (s *CreateLogGroupInput) SetLogGroupClass(v string) *CreateLogGroupInput { - s.LogGroupClass = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *CreateLogGroupInput) SetLogGroupName(v string) *CreateLogGroupInput { - s.LogGroupName = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *CreateLogGroupInput) SetTags(v map[string]*string) *CreateLogGroupInput { - s.Tags = v - return s -} - -type CreateLogGroupOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogGroupOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogGroupOutput) GoString() string { - return s.String() -} - -type CreateLogStreamInput struct { - _ struct{} `type:"structure"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The name of the log stream. - // - // LogStreamName is a required field - LogStreamName *string `locationName:"logStreamName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogStreamInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogStreamInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLogStreamInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLogStreamInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.LogStreamName == nil { - invalidParams.Add(request.NewErrParamRequired("LogStreamName")) - } - if s.LogStreamName != nil && len(*s.LogStreamName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *CreateLogStreamInput) SetLogGroupName(v string) *CreateLogStreamInput { - s.LogGroupName = &v - return s -} - -// SetLogStreamName sets the LogStreamName field's value. -func (s *CreateLogStreamInput) SetLogStreamName(v string) *CreateLogStreamInput { - s.LogStreamName = &v - return s -} - -type CreateLogStreamOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogStreamOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateLogStreamOutput) GoString() string { - return s.String() -} - -// The event was already logged. -// -// PutLogEvents actions are now always accepted and never return DataAlreadyAcceptedException -// regardless of whether a given batch of log events has already been accepted. -type DataAlreadyAcceptedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - ExpectedSequenceToken *string `locationName:"expectedSequenceToken" min:"1" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DataAlreadyAcceptedException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DataAlreadyAcceptedException) GoString() string { - return s.String() -} - -func newErrorDataAlreadyAcceptedException(v protocol.ResponseMetadata) error { - return &DataAlreadyAcceptedException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *DataAlreadyAcceptedException) Code() string { - return "DataAlreadyAcceptedException" -} - -// Message returns the exception's message. -func (s *DataAlreadyAcceptedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *DataAlreadyAcceptedException) OrigErr() error { - return nil -} - -func (s *DataAlreadyAcceptedException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *DataAlreadyAcceptedException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *DataAlreadyAcceptedException) RequestID() string { - return s.RespMetadata.RequestID -} - -type DeleteAccountPolicyInput struct { - _ struct{} `type:"structure"` - - // The name of the policy to delete. - // - // PolicyName is a required field - PolicyName *string `locationName:"policyName" type:"string" required:"true"` - - // The type of policy to delete. - // - // PolicyType is a required field - PolicyType *string `locationName:"policyType" type:"string" required:"true" enum:"PolicyType"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteAccountPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteAccountPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteAccountPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteAccountPolicyInput"} - if s.PolicyName == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyName")) - } - if s.PolicyType == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPolicyName sets the PolicyName field's value. -func (s *DeleteAccountPolicyInput) SetPolicyName(v string) *DeleteAccountPolicyInput { - s.PolicyName = &v - return s -} - -// SetPolicyType sets the PolicyType field's value. -func (s *DeleteAccountPolicyInput) SetPolicyType(v string) *DeleteAccountPolicyInput { - s.PolicyType = &v - return s -} - -type DeleteAccountPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteAccountPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteAccountPolicyOutput) GoString() string { - return s.String() -} - -type DeleteDataProtectionPolicyInput struct { - _ struct{} `type:"structure"` - - // The name or ARN of the log group that you want to delete the data protection - // policy for. - // - // LogGroupIdentifier is a required field - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDataProtectionPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDataProtectionPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDataProtectionPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDataProtectionPolicyInput"} - if s.LogGroupIdentifier == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupIdentifier")) - } - if s.LogGroupIdentifier != nil && len(*s.LogGroupIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupIdentifier", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *DeleteDataProtectionPolicyInput) SetLogGroupIdentifier(v string) *DeleteDataProtectionPolicyInput { - s.LogGroupIdentifier = &v - return s -} - -type DeleteDataProtectionPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDataProtectionPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDataProtectionPolicyOutput) GoString() string { - return s.String() -} - -type DeleteDeliveryDestinationInput struct { - _ struct{} `type:"structure"` - - // The name of the delivery destination that you want to delete. You can find - // a list of delivery destionation names by using the DescribeDeliveryDestinations - // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeDeliveryDestinations.html) - // operation. - // - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryDestinationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryDestinationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDeliveryDestinationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDeliveryDestinationInput"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetName sets the Name field's value. -func (s *DeleteDeliveryDestinationInput) SetName(v string) *DeleteDeliveryDestinationInput { - s.Name = &v - return s -} - -type DeleteDeliveryDestinationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryDestinationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryDestinationOutput) GoString() string { - return s.String() -} - -type DeleteDeliveryDestinationPolicyInput struct { - _ struct{} `type:"structure"` - - // The name of the delivery destination that you want to delete the policy for. - // - // DeliveryDestinationName is a required field - DeliveryDestinationName *string `locationName:"deliveryDestinationName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryDestinationPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryDestinationPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDeliveryDestinationPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDeliveryDestinationPolicyInput"} - if s.DeliveryDestinationName == nil { - invalidParams.Add(request.NewErrParamRequired("DeliveryDestinationName")) - } - if s.DeliveryDestinationName != nil && len(*s.DeliveryDestinationName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DeliveryDestinationName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDeliveryDestinationName sets the DeliveryDestinationName field's value. -func (s *DeleteDeliveryDestinationPolicyInput) SetDeliveryDestinationName(v string) *DeleteDeliveryDestinationPolicyInput { - s.DeliveryDestinationName = &v - return s -} - -type DeleteDeliveryDestinationPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryDestinationPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryDestinationPolicyOutput) GoString() string { - return s.String() -} - -type DeleteDeliveryInput struct { - _ struct{} `type:"structure"` - - // The unique ID of the delivery to delete. You can find the ID of a delivery - // with the DescribeDeliveries (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeDeliveries.html) - // operation. - // - // Id is a required field - Id *string `locationName:"id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDeliveryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDeliveryInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteDeliveryInput) SetId(v string) *DeleteDeliveryInput { - s.Id = &v - return s -} - -type DeleteDeliveryOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliveryOutput) GoString() string { - return s.String() -} - -type DeleteDeliverySourceInput struct { - _ struct{} `type:"structure"` - - // The name of the delivery source that you want to delete. - // - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliverySourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliverySourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDeliverySourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDeliverySourceInput"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetName sets the Name field's value. -func (s *DeleteDeliverySourceInput) SetName(v string) *DeleteDeliverySourceInput { - s.Name = &v - return s -} - -type DeleteDeliverySourceOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliverySourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDeliverySourceOutput) GoString() string { - return s.String() -} - -type DeleteDestinationInput struct { - _ struct{} `type:"structure"` - - // The name of the destination. - // - // DestinationName is a required field - DestinationName *string `locationName:"destinationName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDestinationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDestinationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDestinationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDestinationInput"} - if s.DestinationName == nil { - invalidParams.Add(request.NewErrParamRequired("DestinationName")) - } - if s.DestinationName != nil && len(*s.DestinationName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DestinationName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestinationName sets the DestinationName field's value. -func (s *DeleteDestinationInput) SetDestinationName(v string) *DeleteDestinationInput { - s.DestinationName = &v - return s -} - -type DeleteDestinationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDestinationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteDestinationOutput) GoString() string { - return s.String() -} - -type DeleteLogAnomalyDetectorInput struct { - _ struct{} `type:"structure"` - - // The ARN of the anomaly detector to delete. You can find the ARNs of log anomaly - // detectors in your account by using the ListLogAnomalyDetectors (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListLogAnomalyDetectors.html) - // operation. - // - // AnomalyDetectorArn is a required field - AnomalyDetectorArn *string `locationName:"anomalyDetectorArn" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogAnomalyDetectorInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogAnomalyDetectorInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLogAnomalyDetectorInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLogAnomalyDetectorInput"} - if s.AnomalyDetectorArn == nil { - invalidParams.Add(request.NewErrParamRequired("AnomalyDetectorArn")) - } - if s.AnomalyDetectorArn != nil && len(*s.AnomalyDetectorArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AnomalyDetectorArn", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnomalyDetectorArn sets the AnomalyDetectorArn field's value. -func (s *DeleteLogAnomalyDetectorInput) SetAnomalyDetectorArn(v string) *DeleteLogAnomalyDetectorInput { - s.AnomalyDetectorArn = &v - return s -} - -type DeleteLogAnomalyDetectorOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogAnomalyDetectorOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogAnomalyDetectorOutput) GoString() string { - return s.String() -} - -type DeleteLogGroupInput struct { - _ struct{} `type:"structure"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogGroupInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogGroupInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLogGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLogGroupInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DeleteLogGroupInput) SetLogGroupName(v string) *DeleteLogGroupInput { - s.LogGroupName = &v - return s -} - -type DeleteLogGroupOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogGroupOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogGroupOutput) GoString() string { - return s.String() -} - -type DeleteLogStreamInput struct { - _ struct{} `type:"structure"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The name of the log stream. - // - // LogStreamName is a required field - LogStreamName *string `locationName:"logStreamName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogStreamInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogStreamInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLogStreamInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLogStreamInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.LogStreamName == nil { - invalidParams.Add(request.NewErrParamRequired("LogStreamName")) - } - if s.LogStreamName != nil && len(*s.LogStreamName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DeleteLogStreamInput) SetLogGroupName(v string) *DeleteLogStreamInput { - s.LogGroupName = &v - return s -} - -// SetLogStreamName sets the LogStreamName field's value. -func (s *DeleteLogStreamInput) SetLogStreamName(v string) *DeleteLogStreamInput { - s.LogStreamName = &v - return s -} - -type DeleteLogStreamOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogStreamOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteLogStreamOutput) GoString() string { - return s.String() -} - -type DeleteMetricFilterInput struct { - _ struct{} `type:"structure"` - - // The name of the metric filter. - // - // FilterName is a required field - FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteMetricFilterInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteMetricFilterInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteMetricFilterInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteMetricFilterInput"} - if s.FilterName == nil { - invalidParams.Add(request.NewErrParamRequired("FilterName")) - } - if s.FilterName != nil && len(*s.FilterName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("FilterName", 1)) - } - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilterName sets the FilterName field's value. -func (s *DeleteMetricFilterInput) SetFilterName(v string) *DeleteMetricFilterInput { - s.FilterName = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DeleteMetricFilterInput) SetLogGroupName(v string) *DeleteMetricFilterInput { - s.LogGroupName = &v - return s -} - -type DeleteMetricFilterOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteMetricFilterOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteMetricFilterOutput) GoString() string { - return s.String() -} - -type DeleteQueryDefinitionInput struct { - _ struct{} `type:"structure"` - - // The ID of the query definition that you want to delete. You can use DescribeQueryDefinitions - // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeQueryDefinitions.html) - // to retrieve the IDs of your saved query definitions. - // - // QueryDefinitionId is a required field - QueryDefinitionId *string `locationName:"queryDefinitionId" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteQueryDefinitionInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteQueryDefinitionInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteQueryDefinitionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteQueryDefinitionInput"} - if s.QueryDefinitionId == nil { - invalidParams.Add(request.NewErrParamRequired("QueryDefinitionId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetQueryDefinitionId sets the QueryDefinitionId field's value. -func (s *DeleteQueryDefinitionInput) SetQueryDefinitionId(v string) *DeleteQueryDefinitionInput { - s.QueryDefinitionId = &v - return s -} - -type DeleteQueryDefinitionOutput struct { - _ struct{} `type:"structure"` - - // A value of TRUE indicates that the operation succeeded. FALSE indicates that - // the operation failed. - Success *bool `locationName:"success" type:"boolean"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteQueryDefinitionOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteQueryDefinitionOutput) GoString() string { - return s.String() -} - -// SetSuccess sets the Success field's value. -func (s *DeleteQueryDefinitionOutput) SetSuccess(v bool) *DeleteQueryDefinitionOutput { - s.Success = &v - return s -} - -type DeleteResourcePolicyInput struct { - _ struct{} `type:"structure"` - - // The name of the policy to be revoked. This parameter is required. - PolicyName *string `locationName:"policyName" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteResourcePolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteResourcePolicyInput) GoString() string { - return s.String() -} - -// SetPolicyName sets the PolicyName field's value. -func (s *DeleteResourcePolicyInput) SetPolicyName(v string) *DeleteResourcePolicyInput { - s.PolicyName = &v - return s -} - -type DeleteResourcePolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteResourcePolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteResourcePolicyOutput) GoString() string { - return s.String() -} - -type DeleteRetentionPolicyInput struct { - _ struct{} `type:"structure"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteRetentionPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteRetentionPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteRetentionPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteRetentionPolicyInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DeleteRetentionPolicyInput) SetLogGroupName(v string) *DeleteRetentionPolicyInput { - s.LogGroupName = &v - return s -} - -type DeleteRetentionPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteRetentionPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteRetentionPolicyOutput) GoString() string { - return s.String() -} - -type DeleteSubscriptionFilterInput struct { - _ struct{} `type:"structure"` - - // The name of the subscription filter. - // - // FilterName is a required field - FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteSubscriptionFilterInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteSubscriptionFilterInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteSubscriptionFilterInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteSubscriptionFilterInput"} - if s.FilterName == nil { - invalidParams.Add(request.NewErrParamRequired("FilterName")) - } - if s.FilterName != nil && len(*s.FilterName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("FilterName", 1)) - } - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilterName sets the FilterName field's value. -func (s *DeleteSubscriptionFilterInput) SetFilterName(v string) *DeleteSubscriptionFilterInput { - s.FilterName = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DeleteSubscriptionFilterInput) SetLogGroupName(v string) *DeleteSubscriptionFilterInput { - s.LogGroupName = &v - return s -} - -type DeleteSubscriptionFilterOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteSubscriptionFilterOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeleteSubscriptionFilterOutput) GoString() string { - return s.String() -} - -// This structure contains information about one delivery in your account. -// -// A delivery is a connection between a logical delivery source and a logical -// delivery destination. -// -// For more information, see CreateDelivery (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateDelivery.html). -// -// You can't update an existing delivery. You can only create and delete deliveries. -type Delivery struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) that uniquely identifies this delivery. - Arn *string `locationName:"arn" type:"string"` - - // The ARN of the delivery destination that is associated with this delivery. - DeliveryDestinationArn *string `locationName:"deliveryDestinationArn" type:"string"` - - // Displays whether the delivery destination associated with this delivery is - // CloudWatch Logs, Amazon S3, or Firehose. - DeliveryDestinationType *string `locationName:"deliveryDestinationType" type:"string" enum:"DeliveryDestinationType"` - - // The name of the delivery source that is associated with this delivery. - DeliverySourceName *string `locationName:"deliverySourceName" min:"1" type:"string"` - - // The unique ID that identifies this delivery in your account. - Id *string `locationName:"id" min:"1" type:"string"` - - // The tags that have been assigned to this delivery. - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Delivery) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Delivery) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *Delivery) SetArn(v string) *Delivery { - s.Arn = &v - return s -} - -// SetDeliveryDestinationArn sets the DeliveryDestinationArn field's value. -func (s *Delivery) SetDeliveryDestinationArn(v string) *Delivery { - s.DeliveryDestinationArn = &v - return s -} - -// SetDeliveryDestinationType sets the DeliveryDestinationType field's value. -func (s *Delivery) SetDeliveryDestinationType(v string) *Delivery { - s.DeliveryDestinationType = &v - return s -} - -// SetDeliverySourceName sets the DeliverySourceName field's value. -func (s *Delivery) SetDeliverySourceName(v string) *Delivery { - s.DeliverySourceName = &v - return s -} - -// SetId sets the Id field's value. -func (s *Delivery) SetId(v string) *Delivery { - s.Id = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *Delivery) SetTags(v map[string]*string) *Delivery { - s.Tags = v - return s -} - -// This structure contains information about one delivery destination in your -// account. A delivery destination is an Amazon Web Services resource that represents -// an Amazon Web Services service that logs can be sent to. CloudWatch Logs, -// Amazon S3, are supported as Firehose delivery destinations. -// -// To configure logs delivery between a supported Amazon Web Services service -// and a destination, you must do the following: -// -// - Create a delivery source, which is a logical object that represents -// the resource that is actually sending the logs. For more information, -// see PutDeliverySource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliverySource.html). -// -// - Create a delivery destination, which is a logical object that represents -// the actual delivery destination. -// -// - If you are delivering logs cross-account, you must use PutDeliveryDestinationPolicy -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestinationPolicy.html) -// in the destination account to assign an IAM policy to the destination. -// This policy allows delivery to that destination. -// -// - Create a delivery by pairing exactly one delivery source and one delivery -// destination. For more information, see CreateDelivery (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateDelivery.html). -// -// You can configure a single delivery source to send logs to multiple destinations -// by creating multiple deliveries. You can also create multiple deliveries -// to configure multiple delivery sources to send logs to the same delivery -// destination. -type DeliveryDestination struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) that uniquely identifies this delivery destination. - Arn *string `locationName:"arn" type:"string"` - - // A structure that contains the ARN of the Amazon Web Services resource that - // will receive the logs. - DeliveryDestinationConfiguration *DeliveryDestinationConfiguration `locationName:"deliveryDestinationConfiguration" type:"structure"` - - // Displays whether this delivery destination is CloudWatch Logs, Amazon S3, - // or Firehose. - DeliveryDestinationType *string `locationName:"deliveryDestinationType" type:"string" enum:"DeliveryDestinationType"` - - // The name of this delivery destination. - Name *string `locationName:"name" min:"1" type:"string"` - - // The format of the logs that are sent to this delivery destination. - OutputFormat *string `locationName:"outputFormat" type:"string" enum:"OutputFormat"` - - // The tags that have been assigned to this delivery destination. - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeliveryDestination) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeliveryDestination) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *DeliveryDestination) SetArn(v string) *DeliveryDestination { - s.Arn = &v - return s -} - -// SetDeliveryDestinationConfiguration sets the DeliveryDestinationConfiguration field's value. -func (s *DeliveryDestination) SetDeliveryDestinationConfiguration(v *DeliveryDestinationConfiguration) *DeliveryDestination { - s.DeliveryDestinationConfiguration = v - return s -} - -// SetDeliveryDestinationType sets the DeliveryDestinationType field's value. -func (s *DeliveryDestination) SetDeliveryDestinationType(v string) *DeliveryDestination { - s.DeliveryDestinationType = &v - return s -} - -// SetName sets the Name field's value. -func (s *DeliveryDestination) SetName(v string) *DeliveryDestination { - s.Name = &v - return s -} - -// SetOutputFormat sets the OutputFormat field's value. -func (s *DeliveryDestination) SetOutputFormat(v string) *DeliveryDestination { - s.OutputFormat = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *DeliveryDestination) SetTags(v map[string]*string) *DeliveryDestination { - s.Tags = v - return s -} - -// A structure that contains information about one logs delivery destination. -type DeliveryDestinationConfiguration struct { - _ struct{} `type:"structure"` - - // The ARN of the Amazon Web Services destination that this delivery destination - // represents. That Amazon Web Services destination can be a log group in CloudWatch - // Logs, an Amazon S3 bucket, or a delivery stream in Firehose. - // - // DestinationResourceArn is a required field - DestinationResourceArn *string `locationName:"destinationResourceArn" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeliveryDestinationConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeliveryDestinationConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeliveryDestinationConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeliveryDestinationConfiguration"} - if s.DestinationResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("DestinationResourceArn")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestinationResourceArn sets the DestinationResourceArn field's value. -func (s *DeliveryDestinationConfiguration) SetDestinationResourceArn(v string) *DeliveryDestinationConfiguration { - s.DestinationResourceArn = &v - return s -} - -// This structure contains information about one delivery source in your account. -// A delivery source is an Amazon Web Services resource that sends logs to an -// Amazon Web Services destination. The destination can be CloudWatch Logs, -// Amazon S3, or Firehose. -// -// Only some Amazon Web Services services support being configured as a delivery -// source. These services are listed as Supported [V2 Permissions] in the table -// at Enabling logging from Amazon Web Services services. (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html) -// -// To configure logs delivery between a supported Amazon Web Services service -// and a destination, you must do the following: -// -// - Create a delivery source, which is a logical object that represents -// the resource that is actually sending the logs. For more information, -// see PutDeliverySource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliverySource.html). -// -// - Create a delivery destination, which is a logical object that represents -// the actual delivery destination. For more information, see PutDeliveryDestination -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestination.html). -// -// - If you are delivering logs cross-account, you must use PutDeliveryDestinationPolicy -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDeliveryDestinationPolicy.html) -// in the destination account to assign an IAM policy to the destination. -// This policy allows delivery to that destination. -// -// - Create a delivery by pairing exactly one delivery source and one delivery -// destination. For more information, see CreateDelivery (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateDelivery.html). -// -// You can configure a single delivery source to send logs to multiple destinations -// by creating multiple deliveries. You can also create multiple deliveries -// to configure multiple delivery sources to send logs to the same delivery -// destination. -type DeliverySource struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) that uniquely identifies this delivery source. - Arn *string `locationName:"arn" type:"string"` - - // The type of log that the source is sending. For valid values for this parameter, - // see the documentation for the source service. - LogType *string `locationName:"logType" min:"1" type:"string"` - - // The unique name of the delivery source. - Name *string `locationName:"name" min:"1" type:"string"` - - // This array contains the ARN of the Amazon Web Services resource that sends - // logs and is represented by this delivery source. Currently, only one ARN - // can be in the array. - ResourceArns []*string `locationName:"resourceArns" type:"list"` - - // The Amazon Web Services service that is sending logs. - Service *string `locationName:"service" min:"1" type:"string"` - - // The tags that have been assigned to this delivery source. - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeliverySource) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DeliverySource) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *DeliverySource) SetArn(v string) *DeliverySource { - s.Arn = &v - return s -} - -// SetLogType sets the LogType field's value. -func (s *DeliverySource) SetLogType(v string) *DeliverySource { - s.LogType = &v - return s -} - -// SetName sets the Name field's value. -func (s *DeliverySource) SetName(v string) *DeliverySource { - s.Name = &v - return s -} - -// SetResourceArns sets the ResourceArns field's value. -func (s *DeliverySource) SetResourceArns(v []*string) *DeliverySource { - s.ResourceArns = v - return s -} - -// SetService sets the Service field's value. -func (s *DeliverySource) SetService(v string) *DeliverySource { - s.Service = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *DeliverySource) SetTags(v map[string]*string) *DeliverySource { - s.Tags = v - return s -} - -type DescribeAccountPoliciesInput struct { - _ struct{} `type:"structure"` - - // If you are using an account that is set up as a monitoring account for CloudWatch - // unified cross-account observability, you can use this to specify the account - // ID of a source account. If you do, the operation returns the account policy - // for the specified account. Currently, you can specify only one account ID - // in this parameter. - // - // If you omit this parameter, only the policy in the current account is returned. - AccountIdentifiers []*string `locationName:"accountIdentifiers" type:"list"` - - // Use this parameter to limit the returned policies to only the policy with - // the name that you specify. - PolicyName *string `locationName:"policyName" type:"string"` - - // Use this parameter to limit the returned policies to only the policies that - // match the policy type that you specify. - // - // PolicyType is a required field - PolicyType *string `locationName:"policyType" type:"string" required:"true" enum:"PolicyType"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeAccountPoliciesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeAccountPoliciesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeAccountPoliciesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeAccountPoliciesInput"} - if s.PolicyType == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccountIdentifiers sets the AccountIdentifiers field's value. -func (s *DescribeAccountPoliciesInput) SetAccountIdentifiers(v []*string) *DescribeAccountPoliciesInput { - s.AccountIdentifiers = v - return s -} - -// SetPolicyName sets the PolicyName field's value. -func (s *DescribeAccountPoliciesInput) SetPolicyName(v string) *DescribeAccountPoliciesInput { - s.PolicyName = &v - return s -} - -// SetPolicyType sets the PolicyType field's value. -func (s *DescribeAccountPoliciesInput) SetPolicyType(v string) *DescribeAccountPoliciesInput { - s.PolicyType = &v - return s -} - -type DescribeAccountPoliciesOutput struct { - _ struct{} `type:"structure"` - - // An array of structures that contain information about the CloudWatch Logs - // account policies that match the specified filters. - AccountPolicies []*AccountPolicy `locationName:"accountPolicies" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeAccountPoliciesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeAccountPoliciesOutput) GoString() string { - return s.String() -} - -// SetAccountPolicies sets the AccountPolicies field's value. -func (s *DescribeAccountPoliciesOutput) SetAccountPolicies(v []*AccountPolicy) *DescribeAccountPoliciesOutput { - s.AccountPolicies = v - return s -} - -type DescribeDeliveriesInput struct { - _ struct{} `type:"structure"` - - // Optionally specify the maximum number of deliveries to return in the response. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliveriesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliveriesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDeliveriesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDeliveriesInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLimit sets the Limit field's value. -func (s *DescribeDeliveriesInput) SetLimit(v int64) *DescribeDeliveriesInput { - s.Limit = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeDeliveriesInput) SetNextToken(v string) *DescribeDeliveriesInput { - s.NextToken = &v - return s -} - -type DescribeDeliveriesOutput struct { - _ struct{} `type:"structure"` - - // An array of structures. Each structure contains information about one delivery - // in the account. - Deliveries []*Delivery `locationName:"deliveries" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliveriesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliveriesOutput) GoString() string { - return s.String() -} - -// SetDeliveries sets the Deliveries field's value. -func (s *DescribeDeliveriesOutput) SetDeliveries(v []*Delivery) *DescribeDeliveriesOutput { - s.Deliveries = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeDeliveriesOutput) SetNextToken(v string) *DescribeDeliveriesOutput { - s.NextToken = &v - return s -} - -type DescribeDeliveryDestinationsInput struct { - _ struct{} `type:"structure"` - - // Optionally specify the maximum number of delivery destinations to return - // in the response. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliveryDestinationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliveryDestinationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDeliveryDestinationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDeliveryDestinationsInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLimit sets the Limit field's value. -func (s *DescribeDeliveryDestinationsInput) SetLimit(v int64) *DescribeDeliveryDestinationsInput { - s.Limit = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeDeliveryDestinationsInput) SetNextToken(v string) *DescribeDeliveryDestinationsInput { - s.NextToken = &v - return s -} - -type DescribeDeliveryDestinationsOutput struct { - _ struct{} `type:"structure"` - - // An array of structures. Each structure contains information about one delivery - // destination in the account. - DeliveryDestinations []*DeliveryDestination `locationName:"deliveryDestinations" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliveryDestinationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliveryDestinationsOutput) GoString() string { - return s.String() -} - -// SetDeliveryDestinations sets the DeliveryDestinations field's value. -func (s *DescribeDeliveryDestinationsOutput) SetDeliveryDestinations(v []*DeliveryDestination) *DescribeDeliveryDestinationsOutput { - s.DeliveryDestinations = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeDeliveryDestinationsOutput) SetNextToken(v string) *DescribeDeliveryDestinationsOutput { - s.NextToken = &v - return s -} - -type DescribeDeliverySourcesInput struct { - _ struct{} `type:"structure"` - - // Optionally specify the maximum number of delivery sources to return in the - // response. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliverySourcesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliverySourcesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDeliverySourcesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDeliverySourcesInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLimit sets the Limit field's value. -func (s *DescribeDeliverySourcesInput) SetLimit(v int64) *DescribeDeliverySourcesInput { - s.Limit = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeDeliverySourcesInput) SetNextToken(v string) *DescribeDeliverySourcesInput { - s.NextToken = &v - return s -} - -type DescribeDeliverySourcesOutput struct { - _ struct{} `type:"structure"` - - // An array of structures. Each structure contains information about one delivery - // source in the account. - DeliverySources []*DeliverySource `locationName:"deliverySources" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliverySourcesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDeliverySourcesOutput) GoString() string { - return s.String() -} - -// SetDeliverySources sets the DeliverySources field's value. -func (s *DescribeDeliverySourcesOutput) SetDeliverySources(v []*DeliverySource) *DescribeDeliverySourcesOutput { - s.DeliverySources = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeDeliverySourcesOutput) SetNextToken(v string) *DescribeDeliverySourcesOutput { - s.NextToken = &v - return s -} - -type DescribeDestinationsInput struct { - _ struct{} `type:"structure"` - - // The prefix to match. If you don't specify a value, no prefix filter is applied. - DestinationNamePrefix *string `min:"1" type:"string"` - - // The maximum number of items returned. If you don't specify a value, the default - // maximum value of 50 items is used. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The token for the next set of items to return. (You received this token from - // a previous call.) - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDestinationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDestinationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDestinationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDestinationsInput"} - if s.DestinationNamePrefix != nil && len(*s.DestinationNamePrefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DestinationNamePrefix", 1)) - } - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestinationNamePrefix sets the DestinationNamePrefix field's value. -func (s *DescribeDestinationsInput) SetDestinationNamePrefix(v string) *DescribeDestinationsInput { - s.DestinationNamePrefix = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *DescribeDestinationsInput) SetLimit(v int64) *DescribeDestinationsInput { - s.Limit = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeDestinationsInput) SetNextToken(v string) *DescribeDestinationsInput { - s.NextToken = &v - return s -} - -type DescribeDestinationsOutput struct { - _ struct{} `type:"structure"` - - // The destinations. - Destinations []*Destination `locationName:"destinations" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDestinationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeDestinationsOutput) GoString() string { - return s.String() -} - -// SetDestinations sets the Destinations field's value. -func (s *DescribeDestinationsOutput) SetDestinations(v []*Destination) *DescribeDestinationsOutput { - s.Destinations = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeDestinationsOutput) SetNextToken(v string) *DescribeDestinationsOutput { - s.NextToken = &v - return s -} - -type DescribeExportTasksInput struct { - _ struct{} `type:"structure"` - - // The maximum number of items returned. If you don't specify a value, the default - // is up to 50 items. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The token for the next set of items to return. (You received this token from - // a previous call.) - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // The status code of the export task. Specifying a status code filters the - // results to zero or more export tasks. - StatusCode *string `locationName:"statusCode" type:"string" enum:"ExportTaskStatusCode"` - - // The ID of the export task. Specifying a task ID filters the results to one - // or zero export tasks. - TaskId *string `locationName:"taskId" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeExportTasksInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeExportTasksInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeExportTasksInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeExportTasksInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - if s.TaskId != nil && len(*s.TaskId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TaskId", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLimit sets the Limit field's value. -func (s *DescribeExportTasksInput) SetLimit(v int64) *DescribeExportTasksInput { - s.Limit = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeExportTasksInput) SetNextToken(v string) *DescribeExportTasksInput { - s.NextToken = &v - return s -} - -// SetStatusCode sets the StatusCode field's value. -func (s *DescribeExportTasksInput) SetStatusCode(v string) *DescribeExportTasksInput { - s.StatusCode = &v - return s -} - -// SetTaskId sets the TaskId field's value. -func (s *DescribeExportTasksInput) SetTaskId(v string) *DescribeExportTasksInput { - s.TaskId = &v - return s -} - -type DescribeExportTasksOutput struct { - _ struct{} `type:"structure"` - - // The export tasks. - ExportTasks []*ExportTask `locationName:"exportTasks" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeExportTasksOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeExportTasksOutput) GoString() string { - return s.String() -} - -// SetExportTasks sets the ExportTasks field's value. -func (s *DescribeExportTasksOutput) SetExportTasks(v []*ExportTask) *DescribeExportTasksOutput { - s.ExportTasks = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeExportTasksOutput) SetNextToken(v string) *DescribeExportTasksOutput { - s.NextToken = &v - return s -} - -type DescribeLogGroupsInput struct { - _ struct{} `type:"structure"` - - // When includeLinkedAccounts is set to True, use this parameter to specify - // the list of accounts to search. You can specify as many as 20 account IDs - // in the array. - AccountIdentifiers []*string `locationName:"accountIdentifiers" type:"list"` - - // If you are using a monitoring account, set this to True to have the operation - // return log groups in the accounts listed in accountIdentifiers. - // - // If this parameter is set to true and accountIdentifiers contains a null value, - // the operation returns all log groups in the monitoring account and all log - // groups in all source accounts that are linked to the monitoring account. - IncludeLinkedAccounts *bool `locationName:"includeLinkedAccounts" type:"boolean"` - - // The maximum number of items returned. If you don't specify a value, the default - // is up to 50 items. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // Specifies the log group class for this log group. There are two classes: - // - // * The Standard log class supports all CloudWatch Logs features. - // - // * The Infrequent Access log class supports a subset of CloudWatch Logs - // features and incurs lower costs. - // - // For details about the features supported by each class, see Log classes (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch_Logs_Log_Classes.html) - LogGroupClass *string `locationName:"logGroupClass" type:"string" enum:"LogGroupClass"` - - // If you specify a string for this parameter, the operation returns only log - // groups that have names that match the string based on a case-sensitive substring - // search. For example, if you specify Foo, log groups named FooBar, aws/Foo, - // and GroupFoo would match, but foo, F/o/o and Froo would not match. - // - // If you specify logGroupNamePattern in your request, then only arn, creationTime, - // and logGroupName are included in the response. - // - // logGroupNamePattern and logGroupNamePrefix are mutually exclusive. Only one - // of these parameters can be passed. - LogGroupNamePattern *string `locationName:"logGroupNamePattern" type:"string"` - - // The prefix to match. - // - // logGroupNamePrefix and logGroupNamePattern are mutually exclusive. Only one - // of these parameters can be passed. - LogGroupNamePrefix *string `locationName:"logGroupNamePrefix" min:"1" type:"string"` - - // The token for the next set of items to return. (You received this token from - // a previous call.) - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeLogGroupsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeLogGroupsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeLogGroupsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeLogGroupsInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.LogGroupNamePrefix != nil && len(*s.LogGroupNamePrefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupNamePrefix", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccountIdentifiers sets the AccountIdentifiers field's value. -func (s *DescribeLogGroupsInput) SetAccountIdentifiers(v []*string) *DescribeLogGroupsInput { - s.AccountIdentifiers = v - return s -} - -// SetIncludeLinkedAccounts sets the IncludeLinkedAccounts field's value. -func (s *DescribeLogGroupsInput) SetIncludeLinkedAccounts(v bool) *DescribeLogGroupsInput { - s.IncludeLinkedAccounts = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *DescribeLogGroupsInput) SetLimit(v int64) *DescribeLogGroupsInput { - s.Limit = &v - return s -} - -// SetLogGroupClass sets the LogGroupClass field's value. -func (s *DescribeLogGroupsInput) SetLogGroupClass(v string) *DescribeLogGroupsInput { - s.LogGroupClass = &v - return s -} - -// SetLogGroupNamePattern sets the LogGroupNamePattern field's value. -func (s *DescribeLogGroupsInput) SetLogGroupNamePattern(v string) *DescribeLogGroupsInput { - s.LogGroupNamePattern = &v - return s -} - -// SetLogGroupNamePrefix sets the LogGroupNamePrefix field's value. -func (s *DescribeLogGroupsInput) SetLogGroupNamePrefix(v string) *DescribeLogGroupsInput { - s.LogGroupNamePrefix = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeLogGroupsInput) SetNextToken(v string) *DescribeLogGroupsInput { - s.NextToken = &v - return s -} - -type DescribeLogGroupsOutput struct { - _ struct{} `type:"structure"` - - // The log groups. - // - // If the retentionInDays value is not included for a log group, then that log - // group's events do not expire. - LogGroups []*LogGroup `locationName:"logGroups" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeLogGroupsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeLogGroupsOutput) GoString() string { - return s.String() -} - -// SetLogGroups sets the LogGroups field's value. -func (s *DescribeLogGroupsOutput) SetLogGroups(v []*LogGroup) *DescribeLogGroupsOutput { - s.LogGroups = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeLogGroupsOutput) SetNextToken(v string) *DescribeLogGroupsOutput { - s.NextToken = &v - return s -} - -type DescribeLogStreamsInput struct { - _ struct{} `type:"structure"` - - // If the value is true, results are returned in descending order. If the value - // is to false, results are returned in ascending order. The default value is - // false. - Descending *bool `locationName:"descending" type:"boolean"` - - // The maximum number of items returned. If you don't specify a value, the default - // is up to 50 items. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // Specify either the name or ARN of the log group to view. If the log group - // is in a source account and you are using a monitoring account, you must use - // the log group ARN. - // - // You must include either logGroupIdentifier or logGroupName, but not both. - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string"` - - // The name of the log group. - // - // You must include either logGroupIdentifier or logGroupName, but not both. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // The prefix to match. - // - // If orderBy is LastEventTime, you cannot specify this parameter. - LogStreamNamePrefix *string `locationName:"logStreamNamePrefix" min:"1" type:"string"` - - // The token for the next set of items to return. (You received this token from - // a previous call.) - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // If the value is LogStreamName, the results are ordered by log stream name. - // If the value is LastEventTime, the results are ordered by the event time. - // The default value is LogStreamName. - // - // If you order the results by event time, you cannot specify the logStreamNamePrefix - // parameter. - // - // lastEventTimestamp represents the time of the most recent log event in the - // log stream in CloudWatch Logs. This number is expressed as the number of - // milliseconds after Jan 1, 1970 00:00:00 UTC. lastEventTimestamp updates on - // an eventual consistency basis. It typically updates in less than an hour - // from ingestion, but in rare situations might take longer. - OrderBy *string `locationName:"orderBy" type:"string" enum:"OrderBy"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeLogStreamsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeLogStreamsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeLogStreamsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeLogStreamsInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.LogGroupIdentifier != nil && len(*s.LogGroupIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupIdentifier", 1)) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.LogStreamNamePrefix != nil && len(*s.LogStreamNamePrefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamNamePrefix", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDescending sets the Descending field's value. -func (s *DescribeLogStreamsInput) SetDescending(v bool) *DescribeLogStreamsInput { - s.Descending = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *DescribeLogStreamsInput) SetLimit(v int64) *DescribeLogStreamsInput { - s.Limit = &v - return s -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *DescribeLogStreamsInput) SetLogGroupIdentifier(v string) *DescribeLogStreamsInput { - s.LogGroupIdentifier = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DescribeLogStreamsInput) SetLogGroupName(v string) *DescribeLogStreamsInput { - s.LogGroupName = &v - return s -} - -// SetLogStreamNamePrefix sets the LogStreamNamePrefix field's value. -func (s *DescribeLogStreamsInput) SetLogStreamNamePrefix(v string) *DescribeLogStreamsInput { - s.LogStreamNamePrefix = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeLogStreamsInput) SetNextToken(v string) *DescribeLogStreamsInput { - s.NextToken = &v - return s -} - -// SetOrderBy sets the OrderBy field's value. -func (s *DescribeLogStreamsInput) SetOrderBy(v string) *DescribeLogStreamsInput { - s.OrderBy = &v - return s -} - -type DescribeLogStreamsOutput struct { - _ struct{} `type:"structure"` - - // The log streams. - LogStreams []*LogStream `locationName:"logStreams" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeLogStreamsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeLogStreamsOutput) GoString() string { - return s.String() -} - -// SetLogStreams sets the LogStreams field's value. -func (s *DescribeLogStreamsOutput) SetLogStreams(v []*LogStream) *DescribeLogStreamsOutput { - s.LogStreams = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeLogStreamsOutput) SetNextToken(v string) *DescribeLogStreamsOutput { - s.NextToken = &v - return s -} - -type DescribeMetricFiltersInput struct { - _ struct{} `type:"structure"` - - // The prefix to match. CloudWatch Logs uses the value that you set here only - // if you also include the logGroupName parameter in your request. - FilterNamePrefix *string `locationName:"filterNamePrefix" min:"1" type:"string"` - - // The maximum number of items returned. If you don't specify a value, the default - // is up to 50 items. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The name of the log group. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // Filters results to include only those with the specified metric name. If - // you include this parameter in your request, you must also include the metricNamespace - // parameter. - MetricName *string `locationName:"metricName" type:"string"` - - // Filters results to include only those in the specified namespace. If you - // include this parameter in your request, you must also include the metricName - // parameter. - MetricNamespace *string `locationName:"metricNamespace" type:"string"` - - // The token for the next set of items to return. (You received this token from - // a previous call.) - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeMetricFiltersInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeMetricFiltersInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeMetricFiltersInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeMetricFiltersInput"} - if s.FilterNamePrefix != nil && len(*s.FilterNamePrefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("FilterNamePrefix", 1)) - } - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilterNamePrefix sets the FilterNamePrefix field's value. -func (s *DescribeMetricFiltersInput) SetFilterNamePrefix(v string) *DescribeMetricFiltersInput { - s.FilterNamePrefix = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *DescribeMetricFiltersInput) SetLimit(v int64) *DescribeMetricFiltersInput { - s.Limit = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DescribeMetricFiltersInput) SetLogGroupName(v string) *DescribeMetricFiltersInput { - s.LogGroupName = &v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *DescribeMetricFiltersInput) SetMetricName(v string) *DescribeMetricFiltersInput { - s.MetricName = &v - return s -} - -// SetMetricNamespace sets the MetricNamespace field's value. -func (s *DescribeMetricFiltersInput) SetMetricNamespace(v string) *DescribeMetricFiltersInput { - s.MetricNamespace = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeMetricFiltersInput) SetNextToken(v string) *DescribeMetricFiltersInput { - s.NextToken = &v - return s -} - -type DescribeMetricFiltersOutput struct { - _ struct{} `type:"structure"` - - // The metric filters. - MetricFilters []*MetricFilter `locationName:"metricFilters" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeMetricFiltersOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeMetricFiltersOutput) GoString() string { - return s.String() -} - -// SetMetricFilters sets the MetricFilters field's value. -func (s *DescribeMetricFiltersOutput) SetMetricFilters(v []*MetricFilter) *DescribeMetricFiltersOutput { - s.MetricFilters = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeMetricFiltersOutput) SetNextToken(v string) *DescribeMetricFiltersOutput { - s.NextToken = &v - return s -} - -type DescribeQueriesInput struct { - _ struct{} `type:"structure"` - - // Limits the returned queries to only those for the specified log group. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // Limits the number of returned queries to the specified number. - MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // Limits the returned queries to only those that have the specified status. - // Valid values are Cancelled, Complete, Failed, Running, and Scheduled. - Status *string `locationName:"status" type:"string" enum:"QueryStatus"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeQueriesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeQueriesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeQueriesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeQueriesInput"} - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DescribeQueriesInput) SetLogGroupName(v string) *DescribeQueriesInput { - s.LogGroupName = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *DescribeQueriesInput) SetMaxResults(v int64) *DescribeQueriesInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeQueriesInput) SetNextToken(v string) *DescribeQueriesInput { - s.NextToken = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *DescribeQueriesInput) SetStatus(v string) *DescribeQueriesInput { - s.Status = &v - return s -} - -type DescribeQueriesOutput struct { - _ struct{} `type:"structure"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // The list of queries that match the request. - Queries []*QueryInfo `locationName:"queries" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeQueriesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeQueriesOutput) GoString() string { - return s.String() -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeQueriesOutput) SetNextToken(v string) *DescribeQueriesOutput { - s.NextToken = &v - return s -} - -// SetQueries sets the Queries field's value. -func (s *DescribeQueriesOutput) SetQueries(v []*QueryInfo) *DescribeQueriesOutput { - s.Queries = v - return s -} - -type DescribeQueryDefinitionsInput struct { - _ struct{} `type:"structure"` - - // Limits the number of returned query definitions to the specified number. - MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // Use this parameter to filter your results to only the query definitions that - // have names that start with the prefix you specify. - QueryDefinitionNamePrefix *string `locationName:"queryDefinitionNamePrefix" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeQueryDefinitionsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeQueryDefinitionsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeQueryDefinitionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeQueryDefinitionsInput"} - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - if s.QueryDefinitionNamePrefix != nil && len(*s.QueryDefinitionNamePrefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("QueryDefinitionNamePrefix", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetMaxResults sets the MaxResults field's value. -func (s *DescribeQueryDefinitionsInput) SetMaxResults(v int64) *DescribeQueryDefinitionsInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeQueryDefinitionsInput) SetNextToken(v string) *DescribeQueryDefinitionsInput { - s.NextToken = &v - return s -} - -// SetQueryDefinitionNamePrefix sets the QueryDefinitionNamePrefix field's value. -func (s *DescribeQueryDefinitionsInput) SetQueryDefinitionNamePrefix(v string) *DescribeQueryDefinitionsInput { - s.QueryDefinitionNamePrefix = &v - return s -} - -type DescribeQueryDefinitionsOutput struct { - _ struct{} `type:"structure"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // The list of query definitions that match your request. - QueryDefinitions []*QueryDefinition `locationName:"queryDefinitions" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeQueryDefinitionsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeQueryDefinitionsOutput) GoString() string { - return s.String() -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeQueryDefinitionsOutput) SetNextToken(v string) *DescribeQueryDefinitionsOutput { - s.NextToken = &v - return s -} - -// SetQueryDefinitions sets the QueryDefinitions field's value. -func (s *DescribeQueryDefinitionsOutput) SetQueryDefinitions(v []*QueryDefinition) *DescribeQueryDefinitionsOutput { - s.QueryDefinitions = v - return s -} - -type DescribeResourcePoliciesInput struct { - _ struct{} `type:"structure"` - - // The maximum number of resource policies to be displayed with one call of - // this API. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeResourcePoliciesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeResourcePoliciesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeResourcePoliciesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeResourcePoliciesInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLimit sets the Limit field's value. -func (s *DescribeResourcePoliciesInput) SetLimit(v int64) *DescribeResourcePoliciesInput { - s.Limit = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeResourcePoliciesInput) SetNextToken(v string) *DescribeResourcePoliciesInput { - s.NextToken = &v - return s -} - -type DescribeResourcePoliciesOutput struct { - _ struct{} `type:"structure"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // The resource policies that exist in this account. - ResourcePolicies []*ResourcePolicy `locationName:"resourcePolicies" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeResourcePoliciesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeResourcePoliciesOutput) GoString() string { - return s.String() -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeResourcePoliciesOutput) SetNextToken(v string) *DescribeResourcePoliciesOutput { - s.NextToken = &v - return s -} - -// SetResourcePolicies sets the ResourcePolicies field's value. -func (s *DescribeResourcePoliciesOutput) SetResourcePolicies(v []*ResourcePolicy) *DescribeResourcePoliciesOutput { - s.ResourcePolicies = v - return s -} - -type DescribeSubscriptionFiltersInput struct { - _ struct{} `type:"structure"` - - // The prefix to match. If you don't specify a value, no prefix filter is applied. - FilterNamePrefix *string `locationName:"filterNamePrefix" min:"1" type:"string"` - - // The maximum number of items returned. If you don't specify a value, the default - // is up to 50 items. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The token for the next set of items to return. (You received this token from - // a previous call.) - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeSubscriptionFiltersInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeSubscriptionFiltersInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeSubscriptionFiltersInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeSubscriptionFiltersInput"} - if s.FilterNamePrefix != nil && len(*s.FilterNamePrefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("FilterNamePrefix", 1)) - } - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilterNamePrefix sets the FilterNamePrefix field's value. -func (s *DescribeSubscriptionFiltersInput) SetFilterNamePrefix(v string) *DescribeSubscriptionFiltersInput { - s.FilterNamePrefix = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *DescribeSubscriptionFiltersInput) SetLimit(v int64) *DescribeSubscriptionFiltersInput { - s.Limit = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DescribeSubscriptionFiltersInput) SetLogGroupName(v string) *DescribeSubscriptionFiltersInput { - s.LogGroupName = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeSubscriptionFiltersInput) SetNextToken(v string) *DescribeSubscriptionFiltersInput { - s.NextToken = &v - return s -} - -type DescribeSubscriptionFiltersOutput struct { - _ struct{} `type:"structure"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // The subscription filters. - SubscriptionFilters []*SubscriptionFilter `locationName:"subscriptionFilters" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeSubscriptionFiltersOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DescribeSubscriptionFiltersOutput) GoString() string { - return s.String() -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeSubscriptionFiltersOutput) SetNextToken(v string) *DescribeSubscriptionFiltersOutput { - s.NextToken = &v - return s -} - -// SetSubscriptionFilters sets the SubscriptionFilters field's value. -func (s *DescribeSubscriptionFiltersOutput) SetSubscriptionFilters(v []*SubscriptionFilter) *DescribeSubscriptionFiltersOutput { - s.SubscriptionFilters = v - return s -} - -// Represents a cross-account destination that receives subscription log events. -type Destination struct { - _ struct{} `type:"structure"` - - // An IAM policy document that governs which Amazon Web Services accounts can - // create subscription filters against this destination. - AccessPolicy *string `locationName:"accessPolicy" min:"1" type:"string"` - - // The ARN of this destination. - Arn *string `locationName:"arn" type:"string"` - - // The creation time of the destination, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. - CreationTime *int64 `locationName:"creationTime" type:"long"` - - // The name of the destination. - DestinationName *string `locationName:"destinationName" min:"1" type:"string"` - - // A role for impersonation, used when delivering log events to the target. - RoleArn *string `locationName:"roleArn" min:"1" type:"string"` - - // The Amazon Resource Name (ARN) of the physical target where the log events - // are delivered (for example, a Kinesis stream). - TargetArn *string `locationName:"targetArn" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Destination) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Destination) GoString() string { - return s.String() -} - -// SetAccessPolicy sets the AccessPolicy field's value. -func (s *Destination) SetAccessPolicy(v string) *Destination { - s.AccessPolicy = &v - return s -} - -// SetArn sets the Arn field's value. -func (s *Destination) SetArn(v string) *Destination { - s.Arn = &v - return s -} - -// SetCreationTime sets the CreationTime field's value. -func (s *Destination) SetCreationTime(v int64) *Destination { - s.CreationTime = &v - return s -} - -// SetDestinationName sets the DestinationName field's value. -func (s *Destination) SetDestinationName(v string) *Destination { - s.DestinationName = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *Destination) SetRoleArn(v string) *Destination { - s.RoleArn = &v - return s -} - -// SetTargetArn sets the TargetArn field's value. -func (s *Destination) SetTargetArn(v string) *Destination { - s.TargetArn = &v - return s -} - -type DisassociateKmsKeyInput struct { - _ struct{} `type:"structure"` - - // The name of the log group. - // - // In your DisassociateKmsKey operation, you must specify either the resourceIdentifier - // parameter or the logGroup parameter, but you can't specify both. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // Specifies the target for this operation. You must specify one of the following: - // - // * Specify the ARN of a log group to stop having CloudWatch Logs use the - // KMS key to encrypt log events that are ingested and stored by that log - // group. After you run this operation, CloudWatch Logs encrypts ingested - // log events with the default CloudWatch Logs method. The log group ARN - // must be in the following format. Replace REGION and ACCOUNT_ID with your - // Region and account ID. arn:aws:logs:REGION:ACCOUNT_ID:log-group:LOG_GROUP_NAME - // - // * Specify the following ARN to stop using this key to encrypt the results - // of future StartQuery (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html) - // operations in this account. Replace REGION and ACCOUNT_ID with your Region - // and account ID. arn:aws:logs:REGION:ACCOUNT_ID:query-result:* - // - // In your DisssociateKmsKey operation, you must specify either the resourceIdentifier - // parameter or the logGroup parameter, but you can't specify both. - ResourceIdentifier *string `locationName:"resourceIdentifier" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DisassociateKmsKeyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DisassociateKmsKeyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DisassociateKmsKeyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DisassociateKmsKeyInput"} - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.ResourceIdentifier != nil && len(*s.ResourceIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceIdentifier", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *DisassociateKmsKeyInput) SetLogGroupName(v string) *DisassociateKmsKeyInput { - s.LogGroupName = &v - return s -} - -// SetResourceIdentifier sets the ResourceIdentifier field's value. -func (s *DisassociateKmsKeyInput) SetResourceIdentifier(v string) *DisassociateKmsKeyInput { - s.ResourceIdentifier = &v - return s -} - -type DisassociateKmsKeyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DisassociateKmsKeyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DisassociateKmsKeyOutput) GoString() string { - return s.String() -} - -// Represents an export task. -type ExportTask struct { - _ struct{} `type:"structure"` - - // The name of the S3 bucket to which the log data was exported. - Destination *string `locationName:"destination" min:"1" type:"string"` - - // The prefix that was used as the start of Amazon S3 key for every object exported. - DestinationPrefix *string `locationName:"destinationPrefix" type:"string"` - - // Execution information about the export task. - ExecutionInfo *ExportTaskExecutionInfo `locationName:"executionInfo" type:"structure"` - - // The start time, expressed as the number of milliseconds after Jan 1, 1970 - // 00:00:00 UTC. Events with a timestamp before this time are not exported. - From *int64 `locationName:"from" type:"long"` - - // The name of the log group from which logs data was exported. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // The status of the export task. - Status *ExportTaskStatus `locationName:"status" type:"structure"` - - // The ID of the export task. - TaskId *string `locationName:"taskId" min:"1" type:"string"` - - // The name of the export task. - TaskName *string `locationName:"taskName" min:"1" type:"string"` - - // The end time, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 - // UTC. Events with a timestamp later than this time are not exported. - To *int64 `locationName:"to" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ExportTask) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ExportTask) GoString() string { - return s.String() -} - -// SetDestination sets the Destination field's value. -func (s *ExportTask) SetDestination(v string) *ExportTask { - s.Destination = &v - return s -} - -// SetDestinationPrefix sets the DestinationPrefix field's value. -func (s *ExportTask) SetDestinationPrefix(v string) *ExportTask { - s.DestinationPrefix = &v - return s -} - -// SetExecutionInfo sets the ExecutionInfo field's value. -func (s *ExportTask) SetExecutionInfo(v *ExportTaskExecutionInfo) *ExportTask { - s.ExecutionInfo = v - return s -} - -// SetFrom sets the From field's value. -func (s *ExportTask) SetFrom(v int64) *ExportTask { - s.From = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *ExportTask) SetLogGroupName(v string) *ExportTask { - s.LogGroupName = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *ExportTask) SetStatus(v *ExportTaskStatus) *ExportTask { - s.Status = v - return s -} - -// SetTaskId sets the TaskId field's value. -func (s *ExportTask) SetTaskId(v string) *ExportTask { - s.TaskId = &v - return s -} - -// SetTaskName sets the TaskName field's value. -func (s *ExportTask) SetTaskName(v string) *ExportTask { - s.TaskName = &v - return s -} - -// SetTo sets the To field's value. -func (s *ExportTask) SetTo(v int64) *ExportTask { - s.To = &v - return s -} - -// Represents the status of an export task. -type ExportTaskExecutionInfo struct { - _ struct{} `type:"structure"` - - // The completion time of the export task, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. - CompletionTime *int64 `locationName:"completionTime" type:"long"` - - // The creation time of the export task, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. - CreationTime *int64 `locationName:"creationTime" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ExportTaskExecutionInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ExportTaskExecutionInfo) GoString() string { - return s.String() -} - -// SetCompletionTime sets the CompletionTime field's value. -func (s *ExportTaskExecutionInfo) SetCompletionTime(v int64) *ExportTaskExecutionInfo { - s.CompletionTime = &v - return s -} - -// SetCreationTime sets the CreationTime field's value. -func (s *ExportTaskExecutionInfo) SetCreationTime(v int64) *ExportTaskExecutionInfo { - s.CreationTime = &v - return s -} - -// Represents the status of an export task. -type ExportTaskStatus struct { - _ struct{} `type:"structure"` - - // The status code of the export task. - Code *string `locationName:"code" type:"string" enum:"ExportTaskStatusCode"` - - // The status message related to the status code. - Message *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ExportTaskStatus) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ExportTaskStatus) GoString() string { - return s.String() -} - -// SetCode sets the Code field's value. -func (s *ExportTaskStatus) SetCode(v string) *ExportTaskStatus { - s.Code = &v - return s -} - -// SetMessage sets the Message field's value. -func (s *ExportTaskStatus) SetMessage(v string) *ExportTaskStatus { - s.Message = &v - return s -} - -type FilterLogEventsInput struct { - _ struct{} `type:"structure"` - - // The end of the time range, expressed as the number of milliseconds after - // Jan 1, 1970 00:00:00 UTC. Events with a timestamp later than this time are - // not returned. - EndTime *int64 `locationName:"endTime" type:"long"` - - // The filter pattern to use. For more information, see Filter and Pattern Syntax - // (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html). - // - // If not provided, all the events are matched. - FilterPattern *string `locationName:"filterPattern" type:"string"` - - // If the value is true, the operation attempts to provide responses that contain - // events from multiple log streams within the log group, interleaved in a single - // response. If the value is false, all the matched log events in the first - // log stream are searched first, then those in the next log stream, and so - // on. - // - // Important As of June 17, 2019, this parameter is ignored and the value is - // assumed to be true. The response from this operation always interleaves events - // from multiple log streams within a log group. - // - // Deprecated: Starting on June 17, 2019, this parameter will be ignored and the value will be assumed to be true. The response from this operation will always interleave events from multiple log streams within a log group. - Interleaved *bool `locationName:"interleaved" deprecated:"true" type:"boolean"` - - // The maximum number of events to return. The default is 10,000 events. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // Specify either the name or ARN of the log group to view log events from. - // If the log group is in a source account and you are using a monitoring account, - // you must use the log group ARN. - // - // You must include either logGroupIdentifier or logGroupName, but not both. - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string"` - - // The name of the log group to search. - // - // You must include either logGroupIdentifier or logGroupName, but not both. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // Filters the results to include only events from log streams that have names - // starting with this prefix. - // - // If you specify a value for both logStreamNamePrefix and logStreamNames, but - // the value for logStreamNamePrefix does not match any log stream names specified - // in logStreamNames, the action returns an InvalidParameterException error. - LogStreamNamePrefix *string `locationName:"logStreamNamePrefix" min:"1" type:"string"` - - // Filters the results to only logs from the log streams in this list. - // - // If you specify a value for both logStreamNamePrefix and logStreamNames, the - // action returns an InvalidParameterException error. - LogStreamNames []*string `locationName:"logStreamNames" min:"1" type:"list"` - - // The token for the next set of events to return. (You received this token - // from a previous call.) - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // The start of the time range, expressed as the number of milliseconds after - // Jan 1, 1970 00:00:00 UTC. Events with a timestamp before this time are not - // returned. - StartTime *int64 `locationName:"startTime" type:"long"` - - // Specify true to display the log event fields with all sensitive data unmasked - // and visible. The default is false. - // - // To use this operation with this parameter, you must be signed into an account - // with the logs:Unmask permission. - Unmask *bool `locationName:"unmask" type:"boolean"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s FilterLogEventsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s FilterLogEventsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *FilterLogEventsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "FilterLogEventsInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.LogGroupIdentifier != nil && len(*s.LogGroupIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupIdentifier", 1)) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.LogStreamNamePrefix != nil && len(*s.LogStreamNamePrefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamNamePrefix", 1)) - } - if s.LogStreamNames != nil && len(s.LogStreamNames) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamNames", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEndTime sets the EndTime field's value. -func (s *FilterLogEventsInput) SetEndTime(v int64) *FilterLogEventsInput { - s.EndTime = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *FilterLogEventsInput) SetFilterPattern(v string) *FilterLogEventsInput { - s.FilterPattern = &v - return s -} - -// SetInterleaved sets the Interleaved field's value. -func (s *FilterLogEventsInput) SetInterleaved(v bool) *FilterLogEventsInput { - s.Interleaved = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *FilterLogEventsInput) SetLimit(v int64) *FilterLogEventsInput { - s.Limit = &v - return s -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *FilterLogEventsInput) SetLogGroupIdentifier(v string) *FilterLogEventsInput { - s.LogGroupIdentifier = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *FilterLogEventsInput) SetLogGroupName(v string) *FilterLogEventsInput { - s.LogGroupName = &v - return s -} - -// SetLogStreamNamePrefix sets the LogStreamNamePrefix field's value. -func (s *FilterLogEventsInput) SetLogStreamNamePrefix(v string) *FilterLogEventsInput { - s.LogStreamNamePrefix = &v - return s -} - -// SetLogStreamNames sets the LogStreamNames field's value. -func (s *FilterLogEventsInput) SetLogStreamNames(v []*string) *FilterLogEventsInput { - s.LogStreamNames = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *FilterLogEventsInput) SetNextToken(v string) *FilterLogEventsInput { - s.NextToken = &v - return s -} - -// SetStartTime sets the StartTime field's value. -func (s *FilterLogEventsInput) SetStartTime(v int64) *FilterLogEventsInput { - s.StartTime = &v - return s -} - -// SetUnmask sets the Unmask field's value. -func (s *FilterLogEventsInput) SetUnmask(v bool) *FilterLogEventsInput { - s.Unmask = &v - return s -} - -type FilterLogEventsOutput struct { - _ struct{} `type:"structure"` - - // The matched events. - Events []*FilteredLogEvent `locationName:"events" type:"list"` - - // The token to use when requesting the next set of items. The token expires - // after 24 hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // Important As of May 15, 2020, this parameter is no longer supported. This - // parameter returns an empty list. - // - // Indicates which log streams have been searched and whether each has been - // searched completely. - SearchedLogStreams []*SearchedLogStream `locationName:"searchedLogStreams" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s FilterLogEventsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s FilterLogEventsOutput) GoString() string { - return s.String() -} - -// SetEvents sets the Events field's value. -func (s *FilterLogEventsOutput) SetEvents(v []*FilteredLogEvent) *FilterLogEventsOutput { - s.Events = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *FilterLogEventsOutput) SetNextToken(v string) *FilterLogEventsOutput { - s.NextToken = &v - return s -} - -// SetSearchedLogStreams sets the SearchedLogStreams field's value. -func (s *FilterLogEventsOutput) SetSearchedLogStreams(v []*SearchedLogStream) *FilterLogEventsOutput { - s.SearchedLogStreams = v - return s -} - -// Represents a matched event. -type FilteredLogEvent struct { - _ struct{} `type:"structure"` - - // The ID of the event. - EventId *string `locationName:"eventId" type:"string"` - - // The time the event was ingested, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. - IngestionTime *int64 `locationName:"ingestionTime" type:"long"` - - // The name of the log stream to which this event belongs. - LogStreamName *string `locationName:"logStreamName" min:"1" type:"string"` - - // The data contained in the log event. - Message *string `locationName:"message" min:"1" type:"string"` - - // The time the event occurred, expressed as the number of milliseconds after - // Jan 1, 1970 00:00:00 UTC. - Timestamp *int64 `locationName:"timestamp" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s FilteredLogEvent) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s FilteredLogEvent) GoString() string { - return s.String() -} - -// SetEventId sets the EventId field's value. -func (s *FilteredLogEvent) SetEventId(v string) *FilteredLogEvent { - s.EventId = &v - return s -} - -// SetIngestionTime sets the IngestionTime field's value. -func (s *FilteredLogEvent) SetIngestionTime(v int64) *FilteredLogEvent { - s.IngestionTime = &v - return s -} - -// SetLogStreamName sets the LogStreamName field's value. -func (s *FilteredLogEvent) SetLogStreamName(v string) *FilteredLogEvent { - s.LogStreamName = &v - return s -} - -// SetMessage sets the Message field's value. -func (s *FilteredLogEvent) SetMessage(v string) *FilteredLogEvent { - s.Message = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *FilteredLogEvent) SetTimestamp(v int64) *FilteredLogEvent { - s.Timestamp = &v - return s -} - -type GetDataProtectionPolicyInput struct { - _ struct{} `type:"structure"` - - // The name or ARN of the log group that contains the data protection policy - // that you want to see. - // - // LogGroupIdentifier is a required field - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDataProtectionPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDataProtectionPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDataProtectionPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDataProtectionPolicyInput"} - if s.LogGroupIdentifier == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupIdentifier")) - } - if s.LogGroupIdentifier != nil && len(*s.LogGroupIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupIdentifier", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *GetDataProtectionPolicyInput) SetLogGroupIdentifier(v string) *GetDataProtectionPolicyInput { - s.LogGroupIdentifier = &v - return s -} - -type GetDataProtectionPolicyOutput struct { - _ struct{} `type:"structure"` - - // The date and time that this policy was most recently updated. - LastUpdatedTime *int64 `locationName:"lastUpdatedTime" type:"long"` - - // The log group name or ARN that you specified in your request. - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string"` - - // The data protection policy document for this log group. - PolicyDocument *string `locationName:"policyDocument" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDataProtectionPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDataProtectionPolicyOutput) GoString() string { - return s.String() -} - -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *GetDataProtectionPolicyOutput) SetLastUpdatedTime(v int64) *GetDataProtectionPolicyOutput { - s.LastUpdatedTime = &v - return s -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *GetDataProtectionPolicyOutput) SetLogGroupIdentifier(v string) *GetDataProtectionPolicyOutput { - s.LogGroupIdentifier = &v - return s -} - -// SetPolicyDocument sets the PolicyDocument field's value. -func (s *GetDataProtectionPolicyOutput) SetPolicyDocument(v string) *GetDataProtectionPolicyOutput { - s.PolicyDocument = &v - return s -} - -type GetDeliveryDestinationInput struct { - _ struct{} `type:"structure"` - - // The name of the delivery destination that you want to retrieve. - // - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryDestinationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryDestinationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDeliveryDestinationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDeliveryDestinationInput"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetName sets the Name field's value. -func (s *GetDeliveryDestinationInput) SetName(v string) *GetDeliveryDestinationInput { - s.Name = &v - return s -} - -type GetDeliveryDestinationOutput struct { - _ struct{} `type:"structure"` - - // A structure containing information about the delivery destination. - DeliveryDestination *DeliveryDestination `locationName:"deliveryDestination" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryDestinationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryDestinationOutput) GoString() string { - return s.String() -} - -// SetDeliveryDestination sets the DeliveryDestination field's value. -func (s *GetDeliveryDestinationOutput) SetDeliveryDestination(v *DeliveryDestination) *GetDeliveryDestinationOutput { - s.DeliveryDestination = v - return s -} - -type GetDeliveryDestinationPolicyInput struct { - _ struct{} `type:"structure"` - - // The name of the delivery destination that you want to retrieve the policy - // of. - // - // DeliveryDestinationName is a required field - DeliveryDestinationName *string `locationName:"deliveryDestinationName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryDestinationPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryDestinationPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDeliveryDestinationPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDeliveryDestinationPolicyInput"} - if s.DeliveryDestinationName == nil { - invalidParams.Add(request.NewErrParamRequired("DeliveryDestinationName")) - } - if s.DeliveryDestinationName != nil && len(*s.DeliveryDestinationName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DeliveryDestinationName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDeliveryDestinationName sets the DeliveryDestinationName field's value. -func (s *GetDeliveryDestinationPolicyInput) SetDeliveryDestinationName(v string) *GetDeliveryDestinationPolicyInput { - s.DeliveryDestinationName = &v - return s -} - -type GetDeliveryDestinationPolicyOutput struct { - _ struct{} `type:"structure"` - - // The IAM policy for this delivery destination. - Policy *Policy `locationName:"policy" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryDestinationPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryDestinationPolicyOutput) GoString() string { - return s.String() -} - -// SetPolicy sets the Policy field's value. -func (s *GetDeliveryDestinationPolicyOutput) SetPolicy(v *Policy) *GetDeliveryDestinationPolicyOutput { - s.Policy = v - return s -} - -type GetDeliveryInput struct { - _ struct{} `type:"structure"` - - // The ID of the delivery that you want to retrieve. - // - // Id is a required field - Id *string `locationName:"id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDeliveryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDeliveryInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetDeliveryInput) SetId(v string) *GetDeliveryInput { - s.Id = &v - return s -} - -type GetDeliveryOutput struct { - _ struct{} `type:"structure"` - - // A structure that contains information about the delivery. - Delivery *Delivery `locationName:"delivery" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliveryOutput) GoString() string { - return s.String() -} - -// SetDelivery sets the Delivery field's value. -func (s *GetDeliveryOutput) SetDelivery(v *Delivery) *GetDeliveryOutput { - s.Delivery = v - return s -} - -type GetDeliverySourceInput struct { - _ struct{} `type:"structure"` - - // The name of the delivery source that you want to retrieve. - // - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliverySourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliverySourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDeliverySourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDeliverySourceInput"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetName sets the Name field's value. -func (s *GetDeliverySourceInput) SetName(v string) *GetDeliverySourceInput { - s.Name = &v - return s -} - -type GetDeliverySourceOutput struct { - _ struct{} `type:"structure"` - - // A structure containing information about the delivery source. - DeliverySource *DeliverySource `locationName:"deliverySource" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliverySourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetDeliverySourceOutput) GoString() string { - return s.String() -} - -// SetDeliverySource sets the DeliverySource field's value. -func (s *GetDeliverySourceOutput) SetDeliverySource(v *DeliverySource) *GetDeliverySourceOutput { - s.DeliverySource = v - return s -} - -type GetLogAnomalyDetectorInput struct { - _ struct{} `type:"structure"` - - // The ARN of the anomaly detector to retrieve information about. You can find - // the ARNs of log anomaly detectors in your account by using the ListLogAnomalyDetectors - // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListLogAnomalyDetectors.html) - // operation. - // - // AnomalyDetectorArn is a required field - AnomalyDetectorArn *string `locationName:"anomalyDetectorArn" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogAnomalyDetectorInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogAnomalyDetectorInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLogAnomalyDetectorInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLogAnomalyDetectorInput"} - if s.AnomalyDetectorArn == nil { - invalidParams.Add(request.NewErrParamRequired("AnomalyDetectorArn")) - } - if s.AnomalyDetectorArn != nil && len(*s.AnomalyDetectorArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AnomalyDetectorArn", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnomalyDetectorArn sets the AnomalyDetectorArn field's value. -func (s *GetLogAnomalyDetectorInput) SetAnomalyDetectorArn(v string) *GetLogAnomalyDetectorInput { - s.AnomalyDetectorArn = &v - return s -} - -type GetLogAnomalyDetectorOutput struct { - _ struct{} `type:"structure"` - - // Specifies whether the anomaly detector is currently active. To change its - // status, use the enabled parameter in the UpdateLogAnomalyDetector (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UpdateLogAnomalyDetector.html) - // operation. - AnomalyDetectorStatus *string `locationName:"anomalyDetectorStatus" type:"string" enum:"AnomalyDetectorStatus"` - - // The number of days used as the life cycle of anomalies. After this time, - // anomalies are automatically baselined and the anomaly detector model will - // treat new occurrences of similar event as normal. - AnomalyVisibilityTime *int64 `locationName:"anomalyVisibilityTime" min:"7" type:"long"` - - // The date and time when this anomaly detector was created. - CreationTimeStamp *int64 `locationName:"creationTimeStamp" type:"long"` - - // The name of the log anomaly detector - DetectorName *string `locationName:"detectorName" min:"1" type:"string"` - - // Specifies how often the anomaly detector runs and look for anomalies. Set - // this value according to the frequency that the log group receives new logs. - // For example, if the log group receives new log events every 10 minutes, then - // setting evaluationFrequency to FIFTEEN_MIN might be appropriate. - EvaluationFrequency *string `locationName:"evaluationFrequency" type:"string" enum:"EvaluationFrequency"` - - // A symbolic description of how CloudWatch Logs should interpret the data in - // each log event. For example, a log event can contain timestamps, IP addresses, - // strings, and so on. You use the filter pattern to specify what to look for - // in the log event message. - FilterPattern *string `locationName:"filterPattern" type:"string"` - - // The ID of the KMS key assigned to this anomaly detector, if any. - KmsKeyId *string `locationName:"kmsKeyId" type:"string"` - - // The date and time when this anomaly detector was most recently modified. - LastModifiedTimeStamp *int64 `locationName:"lastModifiedTimeStamp" type:"long"` - - // An array of structures, where each structure contains the ARN of a log group - // associated with this anomaly detector. - LogGroupArnList []*string `locationName:"logGroupArnList" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogAnomalyDetectorOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogAnomalyDetectorOutput) GoString() string { - return s.String() -} - -// SetAnomalyDetectorStatus sets the AnomalyDetectorStatus field's value. -func (s *GetLogAnomalyDetectorOutput) SetAnomalyDetectorStatus(v string) *GetLogAnomalyDetectorOutput { - s.AnomalyDetectorStatus = &v - return s -} - -// SetAnomalyVisibilityTime sets the AnomalyVisibilityTime field's value. -func (s *GetLogAnomalyDetectorOutput) SetAnomalyVisibilityTime(v int64) *GetLogAnomalyDetectorOutput { - s.AnomalyVisibilityTime = &v - return s -} - -// SetCreationTimeStamp sets the CreationTimeStamp field's value. -func (s *GetLogAnomalyDetectorOutput) SetCreationTimeStamp(v int64) *GetLogAnomalyDetectorOutput { - s.CreationTimeStamp = &v - return s -} - -// SetDetectorName sets the DetectorName field's value. -func (s *GetLogAnomalyDetectorOutput) SetDetectorName(v string) *GetLogAnomalyDetectorOutput { - s.DetectorName = &v - return s -} - -// SetEvaluationFrequency sets the EvaluationFrequency field's value. -func (s *GetLogAnomalyDetectorOutput) SetEvaluationFrequency(v string) *GetLogAnomalyDetectorOutput { - s.EvaluationFrequency = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *GetLogAnomalyDetectorOutput) SetFilterPattern(v string) *GetLogAnomalyDetectorOutput { - s.FilterPattern = &v - return s -} - -// SetKmsKeyId sets the KmsKeyId field's value. -func (s *GetLogAnomalyDetectorOutput) SetKmsKeyId(v string) *GetLogAnomalyDetectorOutput { - s.KmsKeyId = &v - return s -} - -// SetLastModifiedTimeStamp sets the LastModifiedTimeStamp field's value. -func (s *GetLogAnomalyDetectorOutput) SetLastModifiedTimeStamp(v int64) *GetLogAnomalyDetectorOutput { - s.LastModifiedTimeStamp = &v - return s -} - -// SetLogGroupArnList sets the LogGroupArnList field's value. -func (s *GetLogAnomalyDetectorOutput) SetLogGroupArnList(v []*string) *GetLogAnomalyDetectorOutput { - s.LogGroupArnList = v - return s -} - -type GetLogEventsInput struct { - _ struct{} `type:"structure"` - - // The end of the time range, expressed as the number of milliseconds after - // Jan 1, 1970 00:00:00 UTC. Events with a timestamp equal to or later than - // this time are not included. - EndTime *int64 `locationName:"endTime" type:"long"` - - // The maximum number of log events returned. If you don't specify a limit, - // the default is as many log events as can fit in a response size of 1 MB (up - // to 10,000 log events). - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // Specify either the name or ARN of the log group to view events from. If the - // log group is in a source account and you are using a monitoring account, - // you must use the log group ARN. - // - // You must include either logGroupIdentifier or logGroupName, but not both. - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string"` - - // The name of the log group. - // - // You must include either logGroupIdentifier or logGroupName, but not both. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // The name of the log stream. - // - // LogStreamName is a required field - LogStreamName *string `locationName:"logStreamName" min:"1" type:"string" required:"true"` - - // The token for the next set of items to return. (You received this token from - // a previous call.) - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // If the value is true, the earliest log events are returned first. If the - // value is false, the latest log events are returned first. The default value - // is false. - // - // If you are using a previous nextForwardToken value as the nextToken in this - // operation, you must specify true for startFromHead. - StartFromHead *bool `locationName:"startFromHead" type:"boolean"` - - // The start of the time range, expressed as the number of milliseconds after - // Jan 1, 1970 00:00:00 UTC. Events with a timestamp equal to this time or later - // than this time are included. Events with a timestamp earlier than this time - // are not included. - StartTime *int64 `locationName:"startTime" type:"long"` - - // Specify true to display the log event fields with all sensitive data unmasked - // and visible. The default is false. - // - // To use this operation with this parameter, you must be signed into an account - // with the logs:Unmask permission. - Unmask *bool `locationName:"unmask" type:"boolean"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogEventsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogEventsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLogEventsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLogEventsInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.LogGroupIdentifier != nil && len(*s.LogGroupIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupIdentifier", 1)) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.LogStreamName == nil { - invalidParams.Add(request.NewErrParamRequired("LogStreamName")) - } - if s.LogStreamName != nil && len(*s.LogStreamName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamName", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEndTime sets the EndTime field's value. -func (s *GetLogEventsInput) SetEndTime(v int64) *GetLogEventsInput { - s.EndTime = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *GetLogEventsInput) SetLimit(v int64) *GetLogEventsInput { - s.Limit = &v - return s -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *GetLogEventsInput) SetLogGroupIdentifier(v string) *GetLogEventsInput { - s.LogGroupIdentifier = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *GetLogEventsInput) SetLogGroupName(v string) *GetLogEventsInput { - s.LogGroupName = &v - return s -} - -// SetLogStreamName sets the LogStreamName field's value. -func (s *GetLogEventsInput) SetLogStreamName(v string) *GetLogEventsInput { - s.LogStreamName = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *GetLogEventsInput) SetNextToken(v string) *GetLogEventsInput { - s.NextToken = &v - return s -} - -// SetStartFromHead sets the StartFromHead field's value. -func (s *GetLogEventsInput) SetStartFromHead(v bool) *GetLogEventsInput { - s.StartFromHead = &v - return s -} - -// SetStartTime sets the StartTime field's value. -func (s *GetLogEventsInput) SetStartTime(v int64) *GetLogEventsInput { - s.StartTime = &v - return s -} - -// SetUnmask sets the Unmask field's value. -func (s *GetLogEventsInput) SetUnmask(v bool) *GetLogEventsInput { - s.Unmask = &v - return s -} - -type GetLogEventsOutput struct { - _ struct{} `type:"structure"` - - // The events. - Events []*OutputLogEvent `locationName:"events" type:"list"` - - // The token for the next set of items in the backward direction. The token - // expires after 24 hours. This token is not null. If you have reached the end - // of the stream, it returns the same token you passed in. - NextBackwardToken *string `locationName:"nextBackwardToken" min:"1" type:"string"` - - // The token for the next set of items in the forward direction. The token expires - // after 24 hours. If you have reached the end of the stream, it returns the - // same token you passed in. - NextForwardToken *string `locationName:"nextForwardToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogEventsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogEventsOutput) GoString() string { - return s.String() -} - -// SetEvents sets the Events field's value. -func (s *GetLogEventsOutput) SetEvents(v []*OutputLogEvent) *GetLogEventsOutput { - s.Events = v - return s -} - -// SetNextBackwardToken sets the NextBackwardToken field's value. -func (s *GetLogEventsOutput) SetNextBackwardToken(v string) *GetLogEventsOutput { - s.NextBackwardToken = &v - return s -} - -// SetNextForwardToken sets the NextForwardToken field's value. -func (s *GetLogEventsOutput) SetNextForwardToken(v string) *GetLogEventsOutput { - s.NextForwardToken = &v - return s -} - -type GetLogGroupFieldsInput struct { - _ struct{} `type:"structure"` - - // Specify either the name or ARN of the log group to view. If the log group - // is in a source account and you are using a monitoring account, you must specify - // the ARN. - // - // You must include either logGroupIdentifier or logGroupName, but not both. - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string"` - - // The name of the log group to search. - // - // You must include either logGroupIdentifier or logGroupName, but not both. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // The time to set as the center of the query. If you specify time, the 8 minutes - // before and 8 minutes after this time are searched. If you omit time, the - // most recent 15 minutes up to the current time are searched. - // - // The time value is specified as epoch time, which is the number of seconds - // since January 1, 1970, 00:00:00 UTC. - Time *int64 `locationName:"time" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogGroupFieldsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogGroupFieldsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLogGroupFieldsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLogGroupFieldsInput"} - if s.LogGroupIdentifier != nil && len(*s.LogGroupIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupIdentifier", 1)) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *GetLogGroupFieldsInput) SetLogGroupIdentifier(v string) *GetLogGroupFieldsInput { - s.LogGroupIdentifier = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *GetLogGroupFieldsInput) SetLogGroupName(v string) *GetLogGroupFieldsInput { - s.LogGroupName = &v - return s -} - -// SetTime sets the Time field's value. -func (s *GetLogGroupFieldsInput) SetTime(v int64) *GetLogGroupFieldsInput { - s.Time = &v - return s -} - -type GetLogGroupFieldsOutput struct { - _ struct{} `type:"structure"` - - // The array of fields found in the query. Each object in the array contains - // the name of the field, along with the percentage of time it appeared in the - // log events that were queried. - LogGroupFields []*LogGroupField `locationName:"logGroupFields" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogGroupFieldsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogGroupFieldsOutput) GoString() string { - return s.String() -} - -// SetLogGroupFields sets the LogGroupFields field's value. -func (s *GetLogGroupFieldsOutput) SetLogGroupFields(v []*LogGroupField) *GetLogGroupFieldsOutput { - s.LogGroupFields = v - return s -} - -type GetLogRecordInput struct { - _ struct{} `type:"structure"` - - // The pointer corresponding to the log event record you want to retrieve. You - // get this from the response of a GetQueryResults operation. In that response, - // the value of the @ptr field for a log event is the value to use as logRecordPointer - // to retrieve that complete log event record. - // - // LogRecordPointer is a required field - LogRecordPointer *string `locationName:"logRecordPointer" type:"string" required:"true"` - - // Specify true to display the log event fields with all sensitive data unmasked - // and visible. The default is false. - // - // To use this operation with this parameter, you must be signed into an account - // with the logs:Unmask permission. - Unmask *bool `locationName:"unmask" type:"boolean"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogRecordInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogRecordInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLogRecordInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLogRecordInput"} - if s.LogRecordPointer == nil { - invalidParams.Add(request.NewErrParamRequired("LogRecordPointer")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogRecordPointer sets the LogRecordPointer field's value. -func (s *GetLogRecordInput) SetLogRecordPointer(v string) *GetLogRecordInput { - s.LogRecordPointer = &v - return s -} - -// SetUnmask sets the Unmask field's value. -func (s *GetLogRecordInput) SetUnmask(v bool) *GetLogRecordInput { - s.Unmask = &v - return s -} - -type GetLogRecordOutput struct { - _ struct{} `type:"structure"` - - // The requested log event, as a JSON string. - LogRecord map[string]*string `locationName:"logRecord" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogRecordOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetLogRecordOutput) GoString() string { - return s.String() -} - -// SetLogRecord sets the LogRecord field's value. -func (s *GetLogRecordOutput) SetLogRecord(v map[string]*string) *GetLogRecordOutput { - s.LogRecord = v - return s -} - -type GetQueryResultsInput struct { - _ struct{} `type:"structure"` - - // The ID number of the query. - // - // QueryId is a required field - QueryId *string `locationName:"queryId" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetQueryResultsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetQueryResultsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetQueryResultsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetQueryResultsInput"} - if s.QueryId == nil { - invalidParams.Add(request.NewErrParamRequired("QueryId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetQueryId sets the QueryId field's value. -func (s *GetQueryResultsInput) SetQueryId(v string) *GetQueryResultsInput { - s.QueryId = &v - return s -} - -type GetQueryResultsOutput struct { - _ struct{} `type:"structure"` - - // If you associated an KMS key with the CloudWatch Logs Insights query results - // in this account, this field displays the ARN of the key that's used to encrypt - // the query results when StartQuery (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html) - // stores them. - EncryptionKey *string `locationName:"encryptionKey" type:"string"` - - // The log events that matched the query criteria during the most recent time - // it ran. - // - // The results value is an array of arrays. Each log event is one object in - // the top-level array. Each of these log event objects is an array of field/value - // pairs. - Results [][]*ResultField `locationName:"results" type:"list"` - - // Includes the number of log events scanned by the query, the number of log - // events that matched the query criteria, and the total number of bytes in - // the scanned log events. These values reflect the full raw results of the - // query. - Statistics *QueryStatistics `locationName:"statistics" type:"structure"` - - // The status of the most recent running of the query. Possible values are Cancelled, - // Complete, Failed, Running, Scheduled, Timeout, and Unknown. - // - // Queries time out after 60 minutes of runtime. To avoid having your queries - // time out, reduce the time range being searched or partition your query into - // a number of queries. - Status *string `locationName:"status" type:"string" enum:"QueryStatus"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetQueryResultsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetQueryResultsOutput) GoString() string { - return s.String() -} - -// SetEncryptionKey sets the EncryptionKey field's value. -func (s *GetQueryResultsOutput) SetEncryptionKey(v string) *GetQueryResultsOutput { - s.EncryptionKey = &v - return s -} - -// SetResults sets the Results field's value. -func (s *GetQueryResultsOutput) SetResults(v [][]*ResultField) *GetQueryResultsOutput { - s.Results = v - return s -} - -// SetStatistics sets the Statistics field's value. -func (s *GetQueryResultsOutput) SetStatistics(v *QueryStatistics) *GetQueryResultsOutput { - s.Statistics = v - return s -} - -// SetStatus sets the Status field's value. -func (s *GetQueryResultsOutput) SetStatus(v string) *GetQueryResultsOutput { - s.Status = &v - return s -} - -// Represents a log event, which is a record of activity that was recorded by -// the application or resource being monitored. -type InputLogEvent struct { - _ struct{} `type:"structure"` - - // The raw event message. Each log event can be no larger than 256 KB. - // - // Message is a required field - Message *string `locationName:"message" min:"1" type:"string" required:"true"` - - // The time the event occurred, expressed as the number of milliseconds after - // Jan 1, 1970 00:00:00 UTC. - // - // Timestamp is a required field - Timestamp *int64 `locationName:"timestamp" type:"long" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InputLogEvent) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InputLogEvent) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *InputLogEvent) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InputLogEvent"} - if s.Message == nil { - invalidParams.Add(request.NewErrParamRequired("Message")) - } - if s.Message != nil && len(*s.Message) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Message", 1)) - } - if s.Timestamp == nil { - invalidParams.Add(request.NewErrParamRequired("Timestamp")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetMessage sets the Message field's value. -func (s *InputLogEvent) SetMessage(v string) *InputLogEvent { - s.Message = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *InputLogEvent) SetTimestamp(v int64) *InputLogEvent { - s.Timestamp = &v - return s -} - -// The operation is not valid on the specified resource. -type InvalidOperationException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidOperationException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidOperationException) GoString() string { - return s.String() -} - -func newErrorInvalidOperationException(v protocol.ResponseMetadata) error { - return &InvalidOperationException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidOperationException) Code() string { - return "InvalidOperationException" -} - -// Message returns the exception's message. -func (s *InvalidOperationException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidOperationException) OrigErr() error { - return nil -} - -func (s *InvalidOperationException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidOperationException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidOperationException) RequestID() string { - return s.RespMetadata.RequestID -} - -// A parameter is specified incorrectly. -type InvalidParameterException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidParameterException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidParameterException) GoString() string { - return s.String() -} - -func newErrorInvalidParameterException(v protocol.ResponseMetadata) error { - return &InvalidParameterException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidParameterException) Code() string { - return "InvalidParameterException" -} - -// Message returns the exception's message. -func (s *InvalidParameterException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidParameterException) OrigErr() error { - return nil -} - -func (s *InvalidParameterException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidParameterException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidParameterException) RequestID() string { - return s.RespMetadata.RequestID -} - -// The sequence token is not valid. You can get the correct sequence token in -// the expectedSequenceToken field in the InvalidSequenceTokenException message. -// -// PutLogEvents actions are now always accepted and never return InvalidSequenceTokenException -// regardless of receiving an invalid sequence token. -type InvalidSequenceTokenException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - ExpectedSequenceToken *string `locationName:"expectedSequenceToken" min:"1" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidSequenceTokenException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidSequenceTokenException) GoString() string { - return s.String() -} - -func newErrorInvalidSequenceTokenException(v protocol.ResponseMetadata) error { - return &InvalidSequenceTokenException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidSequenceTokenException) Code() string { - return "InvalidSequenceTokenException" -} - -// Message returns the exception's message. -func (s *InvalidSequenceTokenException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidSequenceTokenException) OrigErr() error { - return nil -} - -func (s *InvalidSequenceTokenException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidSequenceTokenException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidSequenceTokenException) RequestID() string { - return s.RespMetadata.RequestID -} - -// You have reached the maximum number of resources that can be created. -type LimitExceededException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LimitExceededException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LimitExceededException) GoString() string { - return s.String() -} - -func newErrorLimitExceededException(v protocol.ResponseMetadata) error { - return &LimitExceededException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *LimitExceededException) Code() string { - return "LimitExceededException" -} - -// Message returns the exception's message. -func (s *LimitExceededException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *LimitExceededException) OrigErr() error { - return nil -} - -func (s *LimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *LimitExceededException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *LimitExceededException) RequestID() string { - return s.RespMetadata.RequestID -} - -type ListAnomaliesInput struct { - _ struct{} `type:"structure"` - - // Use this to optionally limit the results to only the anomalies found by a - // certain anomaly detector. - AnomalyDetectorArn *string `locationName:"anomalyDetectorArn" min:"1" type:"string"` - - // The maximum number of items to return. If you don't specify a value, the - // default maximum value of 50 items is used. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // You can specify this parameter if you want to the operation to return only - // anomalies that are currently either suppressed or unsuppressed. - SuppressionState *string `locationName:"suppressionState" type:"string" enum:"SuppressionState"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAnomaliesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAnomaliesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListAnomaliesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListAnomaliesInput"} - if s.AnomalyDetectorArn != nil && len(*s.AnomalyDetectorArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AnomalyDetectorArn", 1)) - } - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnomalyDetectorArn sets the AnomalyDetectorArn field's value. -func (s *ListAnomaliesInput) SetAnomalyDetectorArn(v string) *ListAnomaliesInput { - s.AnomalyDetectorArn = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *ListAnomaliesInput) SetLimit(v int64) *ListAnomaliesInput { - s.Limit = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListAnomaliesInput) SetNextToken(v string) *ListAnomaliesInput { - s.NextToken = &v - return s -} - -// SetSuppressionState sets the SuppressionState field's value. -func (s *ListAnomaliesInput) SetSuppressionState(v string) *ListAnomaliesInput { - s.SuppressionState = &v - return s -} - -type ListAnomaliesOutput struct { - _ struct{} `type:"structure"` - - // An array of structures, where each structure contains information about one - // anomaly that a log anomaly detector has found. - Anomalies []*Anomaly `locationName:"anomalies" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAnomaliesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAnomaliesOutput) GoString() string { - return s.String() -} - -// SetAnomalies sets the Anomalies field's value. -func (s *ListAnomaliesOutput) SetAnomalies(v []*Anomaly) *ListAnomaliesOutput { - s.Anomalies = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListAnomaliesOutput) SetNextToken(v string) *ListAnomaliesOutput { - s.NextToken = &v - return s -} - -type ListLogAnomalyDetectorsInput struct { - _ struct{} `type:"structure"` - - // Use this to optionally filter the results to only include anomaly detectors - // that are associated with the specified log group. - FilterLogGroupArn *string `locationName:"filterLogGroupArn" min:"1" type:"string"` - - // The maximum number of items to return. If you don't specify a value, the - // default maximum value of 50 items is used. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListLogAnomalyDetectorsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListLogAnomalyDetectorsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListLogAnomalyDetectorsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListLogAnomalyDetectorsInput"} - if s.FilterLogGroupArn != nil && len(*s.FilterLogGroupArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("FilterLogGroupArn", 1)) - } - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.NextToken != nil && len(*s.NextToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilterLogGroupArn sets the FilterLogGroupArn field's value. -func (s *ListLogAnomalyDetectorsInput) SetFilterLogGroupArn(v string) *ListLogAnomalyDetectorsInput { - s.FilterLogGroupArn = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *ListLogAnomalyDetectorsInput) SetLimit(v int64) *ListLogAnomalyDetectorsInput { - s.Limit = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListLogAnomalyDetectorsInput) SetNextToken(v string) *ListLogAnomalyDetectorsInput { - s.NextToken = &v - return s -} - -type ListLogAnomalyDetectorsOutput struct { - _ struct{} `type:"structure"` - - // An array of structures, where each structure in the array contains information - // about one anomaly detector. - AnomalyDetectors []*AnomalyDetector `locationName:"anomalyDetectors" type:"list"` - - // The token for the next set of items to return. The token expires after 24 - // hours. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListLogAnomalyDetectorsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListLogAnomalyDetectorsOutput) GoString() string { - return s.String() -} - -// SetAnomalyDetectors sets the AnomalyDetectors field's value. -func (s *ListLogAnomalyDetectorsOutput) SetAnomalyDetectors(v []*AnomalyDetector) *ListLogAnomalyDetectorsOutput { - s.AnomalyDetectors = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListLogAnomalyDetectorsOutput) SetNextToken(v string) *ListLogAnomalyDetectorsOutput { - s.NextToken = &v - return s -} - -type ListTagsForResourceInput struct { - _ struct{} `type:"structure"` - - // The ARN of the resource that you want to view tags for. - // - // The ARN format of a log group is arn:aws:logs:Region:account-id:log-group:log-group-name - // - // The ARN format of a destination is arn:aws:logs:Region:account-id:destination:destination-name - // - // For more information about ARN format, see CloudWatch Logs resources and - // operations (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html). - // - // ResourceArn is a required field - ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListTagsForResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListTagsForResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) - } - if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetResourceArn sets the ResourceArn field's value. -func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { - s.ResourceArn = &v - return s -} - -type ListTagsForResourceOutput struct { - _ struct{} `type:"structure"` - - // The list of tags associated with the requested resource.> - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListTagsForResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListTagsForResourceOutput) GoString() string { - return s.String() -} - -// SetTags sets the Tags field's value. -func (s *ListTagsForResourceOutput) SetTags(v map[string]*string) *ListTagsForResourceOutput { - s.Tags = v - return s -} - -// Deprecated: Please use the generic tagging API model ListTagsForResourceRequest and ListTagsForResourceResponse -type ListTagsLogGroupInput struct { - _ struct{} `deprecated:"true" type:"structure"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListTagsLogGroupInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListTagsLogGroupInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsLogGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsLogGroupInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *ListTagsLogGroupInput) SetLogGroupName(v string) *ListTagsLogGroupInput { - s.LogGroupName = &v - return s -} - -// Deprecated: Please use the generic tagging API model ListTagsForResourceRequest and ListTagsForResourceResponse -type ListTagsLogGroupOutput struct { - _ struct{} `deprecated:"true" type:"structure"` - - // The tags for the log group. - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListTagsLogGroupOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListTagsLogGroupOutput) GoString() string { - return s.String() -} - -// SetTags sets the Tags field's value. -func (s *ListTagsLogGroupOutput) SetTags(v map[string]*string) *ListTagsLogGroupOutput { - s.Tags = v - return s -} - -// This object contains the information for one log event returned in a Live -// Tail stream. -type LiveTailSessionLogEvent struct { - _ struct{} `type:"structure"` - - // The timestamp specifying when this log event was ingested into the log group. - IngestionTime *int64 `locationName:"ingestionTime" type:"long"` - - // The name or ARN of the log group that ingested this log event. - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string"` - - // The name of the log stream that ingested this log event. - LogStreamName *string `locationName:"logStreamName" min:"1" type:"string"` - - // The log event message text. - Message *string `locationName:"message" min:"1" type:"string"` - - // The timestamp specifying when this log event was created. - Timestamp *int64 `locationName:"timestamp" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LiveTailSessionLogEvent) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LiveTailSessionLogEvent) GoString() string { - return s.String() -} - -// SetIngestionTime sets the IngestionTime field's value. -func (s *LiveTailSessionLogEvent) SetIngestionTime(v int64) *LiveTailSessionLogEvent { - s.IngestionTime = &v - return s -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *LiveTailSessionLogEvent) SetLogGroupIdentifier(v string) *LiveTailSessionLogEvent { - s.LogGroupIdentifier = &v - return s -} - -// SetLogStreamName sets the LogStreamName field's value. -func (s *LiveTailSessionLogEvent) SetLogStreamName(v string) *LiveTailSessionLogEvent { - s.LogStreamName = &v - return s -} - -// SetMessage sets the Message field's value. -func (s *LiveTailSessionLogEvent) SetMessage(v string) *LiveTailSessionLogEvent { - s.Message = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *LiveTailSessionLogEvent) SetTimestamp(v int64) *LiveTailSessionLogEvent { - s.Timestamp = &v - return s -} - -// This object contains the metadata for one LiveTailSessionUpdate structure. -// It indicates whether that update includes only a sample of 500 log events -// out of a larger number of ingested log events, or if it contains all of the -// matching log events ingested during that second of time. -type LiveTailSessionMetadata struct { - _ struct{} `type:"structure"` - - // If this is true, then more than 500 log events matched the request for this - // update, and the sessionResults includes a sample of 500 of those events. - // - // If this is false, then 500 or fewer log events matched the request for this - // update, so no sampling was necessary. In this case, the sessionResults array - // includes all log events that matched your request during this time. - Sampled *bool `locationName:"sampled" type:"boolean"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LiveTailSessionMetadata) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LiveTailSessionMetadata) GoString() string { - return s.String() -} - -// SetSampled sets the Sampled field's value. -func (s *LiveTailSessionMetadata) SetSampled(v bool) *LiveTailSessionMetadata { - s.Sampled = &v - return s -} - -// This object contains information about this Live Tail session, including -// the log groups included and the log stream filters, if any. -type LiveTailSessionStart struct { - _ struct{} `type:"structure"` - - // An optional pattern to filter the results to include only log events that - // match the pattern. For example, a filter pattern of error 404 displays only - // log events that include both error and 404. - // - // For more information about filter pattern syntax, see Filter and Pattern - // Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html). - LogEventFilterPattern *string `locationName:"logEventFilterPattern" type:"string"` - - // An array of the names and ARNs of the log groups included in this Live Tail - // session. - LogGroupIdentifiers []*string `locationName:"logGroupIdentifiers" min:"1" type:"list"` - - // If your StartLiveTail operation request included a logStreamNamePrefixes - // parameter that filtered the session to only include log streams that have - // names that start with certain prefixes, these prefixes are listed here. - LogStreamNamePrefixes []*string `locationName:"logStreamNamePrefixes" min:"1" type:"list"` - - // If your StartLiveTail operation request included a logStreamNames parameter - // that filtered the session to only include certain log streams, these streams - // are listed here. - LogStreamNames []*string `locationName:"logStreamNames" min:"1" type:"list"` - - // The unique ID generated by CloudWatch Logs to identify this Live Tail session - // request. - RequestId *string `locationName:"requestId" type:"string"` - - // The unique ID generated by CloudWatch Logs to identify this Live Tail session. - SessionId *string `locationName:"sessionId" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LiveTailSessionStart) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LiveTailSessionStart) GoString() string { - return s.String() -} - -// SetLogEventFilterPattern sets the LogEventFilterPattern field's value. -func (s *LiveTailSessionStart) SetLogEventFilterPattern(v string) *LiveTailSessionStart { - s.LogEventFilterPattern = &v - return s -} - -// SetLogGroupIdentifiers sets the LogGroupIdentifiers field's value. -func (s *LiveTailSessionStart) SetLogGroupIdentifiers(v []*string) *LiveTailSessionStart { - s.LogGroupIdentifiers = v - return s -} - -// SetLogStreamNamePrefixes sets the LogStreamNamePrefixes field's value. -func (s *LiveTailSessionStart) SetLogStreamNamePrefixes(v []*string) *LiveTailSessionStart { - s.LogStreamNamePrefixes = v - return s -} - -// SetLogStreamNames sets the LogStreamNames field's value. -func (s *LiveTailSessionStart) SetLogStreamNames(v []*string) *LiveTailSessionStart { - s.LogStreamNames = v - return s -} - -// SetRequestId sets the RequestId field's value. -func (s *LiveTailSessionStart) SetRequestId(v string) *LiveTailSessionStart { - s.RequestId = &v - return s -} - -// SetSessionId sets the SessionId field's value. -func (s *LiveTailSessionStart) SetSessionId(v string) *LiveTailSessionStart { - s.SessionId = &v - return s -} - -// The LiveTailSessionStart is and event in the StartLiveTailResponseStream group of events. -func (s *LiveTailSessionStart) eventStartLiveTailResponseStream() {} - -// UnmarshalEvent unmarshals the EventStream Message into the LiveTailSessionStart value. -// This method is only used internally within the SDK's EventStream handling. -func (s *LiveTailSessionStart) UnmarshalEvent( - payloadUnmarshaler protocol.PayloadUnmarshaler, - msg eventstream.Message, -) error { - if err := payloadUnmarshaler.UnmarshalPayload( - bytes.NewReader(msg.Payload), s, - ); err != nil { - return err - } - return nil -} - -// MarshalEvent marshals the type into an stream event value. This method -// should only used internally within the SDK's EventStream handling. -func (s *LiveTailSessionStart) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { - msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) - var buf bytes.Buffer - if err = pm.MarshalPayload(&buf, s); err != nil { - return eventstream.Message{}, err - } - msg.Payload = buf.Bytes() - return msg, err -} - -// This object contains the log events and metadata for a Live Tail session. -type LiveTailSessionUpdate struct { - _ struct{} `type:"structure"` - - // This object contains the session metadata for a Live Tail session. - SessionMetadata *LiveTailSessionMetadata `locationName:"sessionMetadata" type:"structure"` - - // An array, where each member of the array includes the information for one - // log event in the Live Tail session. - // - // A sessionResults array can include as many as 500 log events. If the number - // of log events matching the request exceeds 500 per second, the log events - // are sampled down to 500 log events to be included in each sessionUpdate structure. - SessionResults []*LiveTailSessionLogEvent `locationName:"sessionResults" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LiveTailSessionUpdate) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LiveTailSessionUpdate) GoString() string { - return s.String() -} - -// SetSessionMetadata sets the SessionMetadata field's value. -func (s *LiveTailSessionUpdate) SetSessionMetadata(v *LiveTailSessionMetadata) *LiveTailSessionUpdate { - s.SessionMetadata = v - return s -} - -// SetSessionResults sets the SessionResults field's value. -func (s *LiveTailSessionUpdate) SetSessionResults(v []*LiveTailSessionLogEvent) *LiveTailSessionUpdate { - s.SessionResults = v - return s -} - -// The LiveTailSessionUpdate is and event in the StartLiveTailResponseStream group of events. -func (s *LiveTailSessionUpdate) eventStartLiveTailResponseStream() {} - -// UnmarshalEvent unmarshals the EventStream Message into the LiveTailSessionUpdate value. -// This method is only used internally within the SDK's EventStream handling. -func (s *LiveTailSessionUpdate) UnmarshalEvent( - payloadUnmarshaler protocol.PayloadUnmarshaler, - msg eventstream.Message, -) error { - if err := payloadUnmarshaler.UnmarshalPayload( - bytes.NewReader(msg.Payload), s, - ); err != nil { - return err - } - return nil -} - -// MarshalEvent marshals the type into an stream event value. This method -// should only used internally within the SDK's EventStream handling. -func (s *LiveTailSessionUpdate) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { - msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) - var buf bytes.Buffer - if err = pm.MarshalPayload(&buf, s); err != nil { - return eventstream.Message{}, err - } - msg.Payload = buf.Bytes() - return msg, err -} - -// This structure contains the information for one sample log event that is -// associated with an anomaly found by a log anomaly detector. -type LogEvent struct { - _ struct{} `type:"structure"` - - // The message content of the log event. - Message *string `locationName:"message" min:"1" type:"string"` - - // The time stamp of the log event. - Timestamp *int64 `locationName:"timestamp" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogEvent) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogEvent) GoString() string { - return s.String() -} - -// SetMessage sets the Message field's value. -func (s *LogEvent) SetMessage(v string) *LogEvent { - s.Message = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *LogEvent) SetTimestamp(v int64) *LogEvent { - s.Timestamp = &v - return s -} - -// Represents a log group. -type LogGroup struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the log group. This version of the ARN - // includes a trailing :* after the log group name. - // - // Use this version to refer to the ARN in IAM policies when specifying permissions - // for most API actions. The exception is when specifying permissions for TagResource - // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_TagResource.html), - // UntagResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UntagResource.html), - // and ListTagsForResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListTagsForResource.html). - // The permissions for those three actions require the ARN version that doesn't - // include a trailing :*. - Arn *string `locationName:"arn" type:"string"` - - // The creation time of the log group, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. - CreationTime *int64 `locationName:"creationTime" type:"long"` - - // Displays whether this log group has a protection policy, or whether it had - // one in the past. For more information, see PutDataProtectionPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDataProtectionPolicy.html). - DataProtectionStatus *string `locationName:"dataProtectionStatus" type:"string" enum:"DataProtectionStatus"` - - // Displays all the properties that this log group has inherited from account-level - // settings. - InheritedProperties []*string `locationName:"inheritedProperties" type:"list" enum:"InheritedProperty"` - - // The Amazon Resource Name (ARN) of the KMS key to use when encrypting log - // data. - KmsKeyId *string `locationName:"kmsKeyId" type:"string"` - - // The Amazon Resource Name (ARN) of the log group. This version of the ARN - // doesn't include a trailing :* after the log group name. - // - // Use this version to refer to the ARN in the following situations: - // - // * In the logGroupIdentifier input field in many CloudWatch Logs APIs. - // - // * In the resourceArn field in tagging APIs - // - // * In IAM policies, when specifying permissions for TagResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_TagResource.html), - // UntagResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UntagResource.html), - // and ListTagsForResource (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListTagsForResource.html). - LogGroupArn *string `locationName:"logGroupArn" type:"string"` - - // This specifies the log group class for this log group. There are two classes: - // - // * The Standard log class supports all CloudWatch Logs features. - // - // * The Infrequent Access log class supports a subset of CloudWatch Logs - // features and incurs lower costs. - // - // For details about the features supported by each class, see Log classes (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch_Logs_Log_Classes.html) - LogGroupClass *string `locationName:"logGroupClass" type:"string" enum:"LogGroupClass"` - - // The name of the log group. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // The number of metric filters. - MetricFilterCount *int64 `locationName:"metricFilterCount" type:"integer"` - - // The number of days to retain the log events in the specified log group. Possible - // values are: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, - // 1096, 1827, 2192, 2557, 2922, 3288, and 3653. - // - // To set a log group so that its log events do not expire, use DeleteRetentionPolicy - // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteRetentionPolicy.html). - RetentionInDays *int64 `locationName:"retentionInDays" type:"integer"` - - // The number of bytes stored. - StoredBytes *int64 `locationName:"storedBytes" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogGroup) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogGroup) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *LogGroup) SetArn(v string) *LogGroup { - s.Arn = &v - return s -} - -// SetCreationTime sets the CreationTime field's value. -func (s *LogGroup) SetCreationTime(v int64) *LogGroup { - s.CreationTime = &v - return s -} - -// SetDataProtectionStatus sets the DataProtectionStatus field's value. -func (s *LogGroup) SetDataProtectionStatus(v string) *LogGroup { - s.DataProtectionStatus = &v - return s -} - -// SetInheritedProperties sets the InheritedProperties field's value. -func (s *LogGroup) SetInheritedProperties(v []*string) *LogGroup { - s.InheritedProperties = v - return s -} - -// SetKmsKeyId sets the KmsKeyId field's value. -func (s *LogGroup) SetKmsKeyId(v string) *LogGroup { - s.KmsKeyId = &v - return s -} - -// SetLogGroupArn sets the LogGroupArn field's value. -func (s *LogGroup) SetLogGroupArn(v string) *LogGroup { - s.LogGroupArn = &v - return s -} - -// SetLogGroupClass sets the LogGroupClass field's value. -func (s *LogGroup) SetLogGroupClass(v string) *LogGroup { - s.LogGroupClass = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *LogGroup) SetLogGroupName(v string) *LogGroup { - s.LogGroupName = &v - return s -} - -// SetMetricFilterCount sets the MetricFilterCount field's value. -func (s *LogGroup) SetMetricFilterCount(v int64) *LogGroup { - s.MetricFilterCount = &v - return s -} - -// SetRetentionInDays sets the RetentionInDays field's value. -func (s *LogGroup) SetRetentionInDays(v int64) *LogGroup { - s.RetentionInDays = &v - return s -} - -// SetStoredBytes sets the StoredBytes field's value. -func (s *LogGroup) SetStoredBytes(v int64) *LogGroup { - s.StoredBytes = &v - return s -} - -// The fields contained in log events found by a GetLogGroupFields operation, -// along with the percentage of queried log events in which each field appears. -type LogGroupField struct { - _ struct{} `type:"structure"` - - // The name of a log field. - Name *string `locationName:"name" type:"string"` - - // The percentage of log events queried that contained the field. - Percent *int64 `locationName:"percent" type:"integer"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogGroupField) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogGroupField) GoString() string { - return s.String() -} - -// SetName sets the Name field's value. -func (s *LogGroupField) SetName(v string) *LogGroupField { - s.Name = &v - return s -} - -// SetPercent sets the Percent field's value. -func (s *LogGroupField) SetPercent(v int64) *LogGroupField { - s.Percent = &v - return s -} - -// Represents a log stream, which is a sequence of log events from a single -// emitter of logs. -type LogStream struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the log stream. - Arn *string `locationName:"arn" type:"string"` - - // The creation time of the stream, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. - CreationTime *int64 `locationName:"creationTime" type:"long"` - - // The time of the first event, expressed as the number of milliseconds after - // Jan 1, 1970 00:00:00 UTC. - FirstEventTimestamp *int64 `locationName:"firstEventTimestamp" type:"long"` - - // The time of the most recent log event in the log stream in CloudWatch Logs. - // This number is expressed as the number of milliseconds after Jan 1, 1970 - // 00:00:00 UTC. The lastEventTime value updates on an eventual consistency - // basis. It typically updates in less than an hour from ingestion, but in rare - // situations might take longer. - LastEventTimestamp *int64 `locationName:"lastEventTimestamp" type:"long"` - - // The ingestion time, expressed as the number of milliseconds after Jan 1, - // 1970 00:00:00 UTC The lastIngestionTime value updates on an eventual consistency - // basis. It typically updates in less than an hour after ingestion, but in - // rare situations might take longer. - LastIngestionTime *int64 `locationName:"lastIngestionTime" type:"long"` - - // The name of the log stream. - LogStreamName *string `locationName:"logStreamName" min:"1" type:"string"` - - // The number of bytes stored. - // - // Important: As of June 17, 2019, this parameter is no longer supported for - // log streams, and is always reported as zero. This change applies only to - // log streams. The storedBytes parameter for log groups is not affected. - // - // Deprecated: Starting on June 17, 2019, this parameter will be deprecated for log streams, and will be reported as zero. This change applies only to log streams. The storedBytes parameter for log groups is not affected. - StoredBytes *int64 `locationName:"storedBytes" deprecated:"true" type:"long"` - - // The sequence token. - // - // The sequence token is now ignored in PutLogEvents actions. PutLogEvents actions - // are always accepted regardless of receiving an invalid sequence token. You - // don't need to obtain uploadSequenceToken to use a PutLogEvents action. - UploadSequenceToken *string `locationName:"uploadSequenceToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogStream) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogStream) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *LogStream) SetArn(v string) *LogStream { - s.Arn = &v - return s -} - -// SetCreationTime sets the CreationTime field's value. -func (s *LogStream) SetCreationTime(v int64) *LogStream { - s.CreationTime = &v - return s -} - -// SetFirstEventTimestamp sets the FirstEventTimestamp field's value. -func (s *LogStream) SetFirstEventTimestamp(v int64) *LogStream { - s.FirstEventTimestamp = &v - return s -} - -// SetLastEventTimestamp sets the LastEventTimestamp field's value. -func (s *LogStream) SetLastEventTimestamp(v int64) *LogStream { - s.LastEventTimestamp = &v - return s -} - -// SetLastIngestionTime sets the LastIngestionTime field's value. -func (s *LogStream) SetLastIngestionTime(v int64) *LogStream { - s.LastIngestionTime = &v - return s -} - -// SetLogStreamName sets the LogStreamName field's value. -func (s *LogStream) SetLogStreamName(v string) *LogStream { - s.LogStreamName = &v - return s -} - -// SetStoredBytes sets the StoredBytes field's value. -func (s *LogStream) SetStoredBytes(v int64) *LogStream { - s.StoredBytes = &v - return s -} - -// SetUploadSequenceToken sets the UploadSequenceToken field's value. -func (s *LogStream) SetUploadSequenceToken(v string) *LogStream { - s.UploadSequenceToken = &v - return s -} - -// The query string is not valid. Details about this error are displayed in -// a QueryCompileError object. For more information, see QueryCompileError (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_QueryCompileError.html). -// -// For more information about valid query syntax, see CloudWatch Logs Insights -// Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). -type MalformedQueryException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` - - // Reserved. - QueryCompileError *QueryCompileError `locationName:"queryCompileError" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s MalformedQueryException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s MalformedQueryException) GoString() string { - return s.String() -} - -func newErrorMalformedQueryException(v protocol.ResponseMetadata) error { - return &MalformedQueryException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *MalformedQueryException) Code() string { - return "MalformedQueryException" -} - -// Message returns the exception's message. -func (s *MalformedQueryException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *MalformedQueryException) OrigErr() error { - return nil -} - -func (s *MalformedQueryException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *MalformedQueryException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *MalformedQueryException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Metric filters express how CloudWatch Logs would extract metric observations -// from ingested log events and transform them into metric data in a CloudWatch -// metric. -type MetricFilter struct { - _ struct{} `type:"structure"` - - // The creation time of the metric filter, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. - CreationTime *int64 `locationName:"creationTime" type:"long"` - - // The name of the metric filter. - FilterName *string `locationName:"filterName" min:"1" type:"string"` - - // A symbolic description of how CloudWatch Logs should interpret the data in - // each log event. For example, a log event can contain timestamps, IP addresses, - // strings, and so on. You use the filter pattern to specify what to look for - // in the log event message. - FilterPattern *string `locationName:"filterPattern" type:"string"` - - // The name of the log group. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // The metric transformations. - MetricTransformations []*MetricTransformation `locationName:"metricTransformations" min:"1" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s MetricFilter) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s MetricFilter) GoString() string { - return s.String() -} - -// SetCreationTime sets the CreationTime field's value. -func (s *MetricFilter) SetCreationTime(v int64) *MetricFilter { - s.CreationTime = &v - return s -} - -// SetFilterName sets the FilterName field's value. -func (s *MetricFilter) SetFilterName(v string) *MetricFilter { - s.FilterName = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *MetricFilter) SetFilterPattern(v string) *MetricFilter { - s.FilterPattern = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *MetricFilter) SetLogGroupName(v string) *MetricFilter { - s.LogGroupName = &v - return s -} - -// SetMetricTransformations sets the MetricTransformations field's value. -func (s *MetricFilter) SetMetricTransformations(v []*MetricTransformation) *MetricFilter { - s.MetricTransformations = v - return s -} - -// Represents a matched event. -type MetricFilterMatchRecord struct { - _ struct{} `type:"structure"` - - // The raw event data. - EventMessage *string `locationName:"eventMessage" min:"1" type:"string"` - - // The event number. - EventNumber *int64 `locationName:"eventNumber" type:"long"` - - // The values extracted from the event data by the filter. - ExtractedValues map[string]*string `locationName:"extractedValues" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s MetricFilterMatchRecord) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s MetricFilterMatchRecord) GoString() string { - return s.String() -} - -// SetEventMessage sets the EventMessage field's value. -func (s *MetricFilterMatchRecord) SetEventMessage(v string) *MetricFilterMatchRecord { - s.EventMessage = &v - return s -} - -// SetEventNumber sets the EventNumber field's value. -func (s *MetricFilterMatchRecord) SetEventNumber(v int64) *MetricFilterMatchRecord { - s.EventNumber = &v - return s -} - -// SetExtractedValues sets the ExtractedValues field's value. -func (s *MetricFilterMatchRecord) SetExtractedValues(v map[string]*string) *MetricFilterMatchRecord { - s.ExtractedValues = v - return s -} - -// Indicates how to transform ingested log events to metric data in a CloudWatch -// metric. -type MetricTransformation struct { - _ struct{} `type:"structure"` - - // (Optional) The value to emit when a filter pattern does not match a log event. - // This value can be null. - DefaultValue *float64 `locationName:"defaultValue" type:"double"` - - // The fields to use as dimensions for the metric. One metric filter can include - // as many as three dimensions. - // - // Metrics extracted from log events are charged as custom metrics. To prevent - // unexpected high charges, do not specify high-cardinality fields such as IPAddress - // or requestID as dimensions. Each different value found for a dimension is - // treated as a separate metric and accrues charges as a separate custom metric. - // - // CloudWatch Logs disables a metric filter if it generates 1000 different name/value - // pairs for your specified dimensions within a certain amount of time. This - // helps to prevent accidental high charges. - // - // You can also set up a billing alarm to alert you if your charges are higher - // than expected. For more information, see Creating a Billing Alarm to Monitor - // Your Estimated Amazon Web Services Charges (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html). - Dimensions map[string]*string `locationName:"dimensions" type:"map"` - - // The name of the CloudWatch metric. - // - // MetricName is a required field - MetricName *string `locationName:"metricName" type:"string" required:"true"` - - // A custom namespace to contain your metric in CloudWatch. Use namespaces to - // group together metrics that are similar. For more information, see Namespaces - // (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Namespace). - // - // MetricNamespace is a required field - MetricNamespace *string `locationName:"metricNamespace" type:"string" required:"true"` - - // The value to publish to the CloudWatch metric when a filter pattern matches - // a log event. - // - // MetricValue is a required field - MetricValue *string `locationName:"metricValue" type:"string" required:"true"` - - // The unit to assign to the metric. If you omit this, the unit is set as None. - Unit *string `locationName:"unit" type:"string" enum:"StandardUnit"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s MetricTransformation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s MetricTransformation) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *MetricTransformation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MetricTransformation"} - if s.MetricName == nil { - invalidParams.Add(request.NewErrParamRequired("MetricName")) - } - if s.MetricNamespace == nil { - invalidParams.Add(request.NewErrParamRequired("MetricNamespace")) - } - if s.MetricValue == nil { - invalidParams.Add(request.NewErrParamRequired("MetricValue")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDefaultValue sets the DefaultValue field's value. -func (s *MetricTransformation) SetDefaultValue(v float64) *MetricTransformation { - s.DefaultValue = &v - return s -} - -// SetDimensions sets the Dimensions field's value. -func (s *MetricTransformation) SetDimensions(v map[string]*string) *MetricTransformation { - s.Dimensions = v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *MetricTransformation) SetMetricName(v string) *MetricTransformation { - s.MetricName = &v - return s -} - -// SetMetricNamespace sets the MetricNamespace field's value. -func (s *MetricTransformation) SetMetricNamespace(v string) *MetricTransformation { - s.MetricNamespace = &v - return s -} - -// SetMetricValue sets the MetricValue field's value. -func (s *MetricTransformation) SetMetricValue(v string) *MetricTransformation { - s.MetricValue = &v - return s -} - -// SetUnit sets the Unit field's value. -func (s *MetricTransformation) SetUnit(v string) *MetricTransformation { - s.Unit = &v - return s -} - -// Multiple concurrent requests to update the same resource were in conflict. -type OperationAbortedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s OperationAbortedException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s OperationAbortedException) GoString() string { - return s.String() -} - -func newErrorOperationAbortedException(v protocol.ResponseMetadata) error { - return &OperationAbortedException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *OperationAbortedException) Code() string { - return "OperationAbortedException" -} - -// Message returns the exception's message. -func (s *OperationAbortedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *OperationAbortedException) OrigErr() error { - return nil -} - -func (s *OperationAbortedException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *OperationAbortedException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *OperationAbortedException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Represents a log event. -type OutputLogEvent struct { - _ struct{} `type:"structure"` - - // The time the event was ingested, expressed as the number of milliseconds - // after Jan 1, 1970 00:00:00 UTC. - IngestionTime *int64 `locationName:"ingestionTime" type:"long"` - - // The data contained in the log event. - Message *string `locationName:"message" min:"1" type:"string"` - - // The time the event occurred, expressed as the number of milliseconds after - // Jan 1, 1970 00:00:00 UTC. - Timestamp *int64 `locationName:"timestamp" type:"long"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s OutputLogEvent) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s OutputLogEvent) GoString() string { - return s.String() -} - -// SetIngestionTime sets the IngestionTime field's value. -func (s *OutputLogEvent) SetIngestionTime(v int64) *OutputLogEvent { - s.IngestionTime = &v - return s -} - -// SetMessage sets the Message field's value. -func (s *OutputLogEvent) SetMessage(v string) *OutputLogEvent { - s.Message = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *OutputLogEvent) SetTimestamp(v int64) *OutputLogEvent { - s.Timestamp = &v - return s -} - -// A tructures that contains information about one pattern token related to -// an anomaly. -// -// For more information about patterns and tokens, see CreateLogAnomalyDetector -// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateLogAnomalyDetector.html). -type PatternToken struct { - _ struct{} `type:"structure"` - - // For a dynamic token, this indicates where in the pattern that this token - // appears, related to other dynamic tokens. The dynamic token that appears - // first has a value of 1, the one that appears second is 2, and so on. - DynamicTokenPosition *int64 `locationName:"dynamicTokenPosition" type:"integer"` - - // Contains the values found for a dynamic token, and the number of times each - // value was found. - Enumerations map[string]*int64 `locationName:"enumerations" type:"map"` - - // Specifies whether this is a dynamic token. - IsDynamic *bool `locationName:"isDynamic" type:"boolean"` - - // The string represented by this token. If this is a dynamic token, the value - // will be <*> - TokenString *string `locationName:"tokenString" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PatternToken) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PatternToken) GoString() string { - return s.String() -} - -// SetDynamicTokenPosition sets the DynamicTokenPosition field's value. -func (s *PatternToken) SetDynamicTokenPosition(v int64) *PatternToken { - s.DynamicTokenPosition = &v - return s -} - -// SetEnumerations sets the Enumerations field's value. -func (s *PatternToken) SetEnumerations(v map[string]*int64) *PatternToken { - s.Enumerations = v - return s -} - -// SetIsDynamic sets the IsDynamic field's value. -func (s *PatternToken) SetIsDynamic(v bool) *PatternToken { - s.IsDynamic = &v - return s -} - -// SetTokenString sets the TokenString field's value. -func (s *PatternToken) SetTokenString(v string) *PatternToken { - s.TokenString = &v - return s -} - -// A structure that contains information about one delivery destination policy. -type Policy struct { - _ struct{} `type:"structure"` - - // The contents of the delivery destination policy. - DeliveryDestinationPolicy *string `locationName:"deliveryDestinationPolicy" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Policy) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Policy) GoString() string { - return s.String() -} - -// SetDeliveryDestinationPolicy sets the DeliveryDestinationPolicy field's value. -func (s *Policy) SetDeliveryDestinationPolicy(v string) *Policy { - s.DeliveryDestinationPolicy = &v - return s -} - -type PutAccountPolicyInput struct { - _ struct{} `type:"structure"` - - // Specify the policy, in JSON. - // - // Data protection policy - // - // A data protection policy must include two JSON blocks: - // - // * The first block must include both a DataIdentifer array and an Operation - // property with an Audit action. The DataIdentifer array lists the types - // of sensitive data that you want to mask. For more information about the - // available options, see Types of data that you can mask (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data-types.html). - // The Operation property with an Audit action is required to find the sensitive - // data terms. This Audit action must contain a FindingsDestination object. - // You can optionally use that FindingsDestination object to list one or - // more destinations to send audit findings to. If you specify destinations - // such as log groups, Firehose streams, and S3 buckets, they must already - // exist. - // - // * The second block must include both a DataIdentifer array and an Operation - // property with an Deidentify action. The DataIdentifer array must exactly - // match the DataIdentifer array in the first block of the policy. The Operation - // property with the Deidentify action is what actually masks the data, and - // it must contain the "MaskConfig": {} object. The "MaskConfig": {} object - // must be empty. - // - // For an example data protection policy, see the Examples section on this page. - // - // The contents of the two DataIdentifer arrays must match exactly. - // - // In addition to the two JSON blocks, the policyDocument can also include Name, - // Description, and Version fields. The Name is different than the operation's - // policyName parameter, and is used as a dimension when CloudWatch Logs reports - // audit findings metrics to CloudWatch. - // - // The JSON specified in policyDocument can be up to 30,720 characters long. - // - // Subscription filter policy - // - // A subscription filter policy can include the following attributes in a JSON - // block: - // - // * DestinationArn The ARN of the destination to deliver log events to. - // Supported destinations are: An Kinesis Data Streams data stream in the - // same account as the subscription policy, for same-account delivery. An - // Firehose data stream in the same account as the subscription policy, for - // same-account delivery. A Lambda function in the same account as the subscription - // policy, for same-account delivery. A logical destination in a different - // account created with PutDestination (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDestination.html), - // for cross-account delivery. Kinesis Data Streams and Firehose are supported - // as logical destinations. - // - // * RoleArn The ARN of an IAM role that grants CloudWatch Logs permissions - // to deliver ingested log events to the destination stream. You don't need - // to provide the ARN when you are working with a logical destination for - // cross-account delivery. - // - // * FilterPattern A filter pattern for subscribing to a filtered stream - // of log events. - // - // * DistributionThe method used to distribute log data to the destination. - // By default, log data is grouped by log stream, but the grouping can be - // set to Random for a more even distribution. This property is only applicable - // when the destination is an Kinesis Data Streams data stream. - // - // PolicyDocument is a required field - PolicyDocument *string `locationName:"policyDocument" type:"string" required:"true"` - - // A name for the policy. This must be unique within the account. - // - // PolicyName is a required field - PolicyName *string `locationName:"policyName" type:"string" required:"true"` - - // The type of policy that you're creating or updating. - // - // PolicyType is a required field - PolicyType *string `locationName:"policyType" type:"string" required:"true" enum:"PolicyType"` - - // Currently the only valid value for this parameter is ALL, which specifies - // that the data protection policy applies to all log groups in the account. - // If you omit this parameter, the default of ALL is used. - Scope *string `locationName:"scope" type:"string" enum:"Scope"` - - // Use this parameter to apply the subscription filter policy to a subset of - // log groups in the account. Currently, the only supported filter is LogGroupName - // NOT IN []. The selectionCriteria string can be up to 25KB in length. The - // length is determined by using its UTF-8 bytes. - // - // Using the selectionCriteria parameter is useful to help prevent infinite - // loops. For more information, see Log recursion prevention (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Subscriptions-recursion-prevention.html). - // - // Specifing selectionCriteria is valid only when you specify SUBSCRIPTION_FILTER_POLICY - // for policyType. - SelectionCriteria *string `locationName:"selectionCriteria" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutAccountPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutAccountPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutAccountPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutAccountPolicyInput"} - if s.PolicyDocument == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyDocument")) - } - if s.PolicyName == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyName")) - } - if s.PolicyType == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPolicyDocument sets the PolicyDocument field's value. -func (s *PutAccountPolicyInput) SetPolicyDocument(v string) *PutAccountPolicyInput { - s.PolicyDocument = &v - return s -} - -// SetPolicyName sets the PolicyName field's value. -func (s *PutAccountPolicyInput) SetPolicyName(v string) *PutAccountPolicyInput { - s.PolicyName = &v - return s -} - -// SetPolicyType sets the PolicyType field's value. -func (s *PutAccountPolicyInput) SetPolicyType(v string) *PutAccountPolicyInput { - s.PolicyType = &v - return s -} - -// SetScope sets the Scope field's value. -func (s *PutAccountPolicyInput) SetScope(v string) *PutAccountPolicyInput { - s.Scope = &v - return s -} - -// SetSelectionCriteria sets the SelectionCriteria field's value. -func (s *PutAccountPolicyInput) SetSelectionCriteria(v string) *PutAccountPolicyInput { - s.SelectionCriteria = &v - return s -} - -type PutAccountPolicyOutput struct { - _ struct{} `type:"structure"` - - // The account policy that you created. - AccountPolicy *AccountPolicy `locationName:"accountPolicy" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutAccountPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutAccountPolicyOutput) GoString() string { - return s.String() -} - -// SetAccountPolicy sets the AccountPolicy field's value. -func (s *PutAccountPolicyOutput) SetAccountPolicy(v *AccountPolicy) *PutAccountPolicyOutput { - s.AccountPolicy = v - return s -} - -type PutDataProtectionPolicyInput struct { - _ struct{} `type:"structure"` - - // Specify either the log group name or log group ARN. - // - // LogGroupIdentifier is a required field - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string" required:"true"` - - // Specify the data protection policy, in JSON. - // - // This policy must include two JSON blocks: - // - // * The first block must include both a DataIdentifer array and an Operation - // property with an Audit action. The DataIdentifer array lists the types - // of sensitive data that you want to mask. For more information about the - // available options, see Types of data that you can mask (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data-types.html). - // The Operation property with an Audit action is required to find the sensitive - // data terms. This Audit action must contain a FindingsDestination object. - // You can optionally use that FindingsDestination object to list one or - // more destinations to send audit findings to. If you specify destinations - // such as log groups, Firehose streams, and S3 buckets, they must already - // exist. - // - // * The second block must include both a DataIdentifer array and an Operation - // property with an Deidentify action. The DataIdentifer array must exactly - // match the DataIdentifer array in the first block of the policy. The Operation - // property with the Deidentify action is what actually masks the data, and - // it must contain the "MaskConfig": {} object. The "MaskConfig": {} object - // must be empty. - // - // For an example data protection policy, see the Examples section on this page. - // - // The contents of the two DataIdentifer arrays must match exactly. - // - // In addition to the two JSON blocks, the policyDocument can also include Name, - // Description, and Version fields. The Name is used as a dimension when CloudWatch - // Logs reports audit findings metrics to CloudWatch. - // - // The JSON specified in policyDocument can be up to 30,720 characters. - // - // PolicyDocument is a required field - PolicyDocument *string `locationName:"policyDocument" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDataProtectionPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDataProtectionPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutDataProtectionPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutDataProtectionPolicyInput"} - if s.LogGroupIdentifier == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupIdentifier")) - } - if s.LogGroupIdentifier != nil && len(*s.LogGroupIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupIdentifier", 1)) - } - if s.PolicyDocument == nil { - invalidParams.Add(request.NewErrParamRequired("PolicyDocument")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *PutDataProtectionPolicyInput) SetLogGroupIdentifier(v string) *PutDataProtectionPolicyInput { - s.LogGroupIdentifier = &v - return s -} - -// SetPolicyDocument sets the PolicyDocument field's value. -func (s *PutDataProtectionPolicyInput) SetPolicyDocument(v string) *PutDataProtectionPolicyInput { - s.PolicyDocument = &v - return s -} - -type PutDataProtectionPolicyOutput struct { - _ struct{} `type:"structure"` - - // The date and time that this policy was most recently updated. - LastUpdatedTime *int64 `locationName:"lastUpdatedTime" type:"long"` - - // The log group name or ARN that you specified in your request. - LogGroupIdentifier *string `locationName:"logGroupIdentifier" min:"1" type:"string"` - - // The data protection policy used for this log group. - PolicyDocument *string `locationName:"policyDocument" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDataProtectionPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDataProtectionPolicyOutput) GoString() string { - return s.String() -} - -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *PutDataProtectionPolicyOutput) SetLastUpdatedTime(v int64) *PutDataProtectionPolicyOutput { - s.LastUpdatedTime = &v - return s -} - -// SetLogGroupIdentifier sets the LogGroupIdentifier field's value. -func (s *PutDataProtectionPolicyOutput) SetLogGroupIdentifier(v string) *PutDataProtectionPolicyOutput { - s.LogGroupIdentifier = &v - return s -} - -// SetPolicyDocument sets the PolicyDocument field's value. -func (s *PutDataProtectionPolicyOutput) SetPolicyDocument(v string) *PutDataProtectionPolicyOutput { - s.PolicyDocument = &v - return s -} - -type PutDeliveryDestinationInput struct { - _ struct{} `type:"structure"` - - // A structure that contains the ARN of the Amazon Web Services resource that - // will receive the logs. - // - // DeliveryDestinationConfiguration is a required field - DeliveryDestinationConfiguration *DeliveryDestinationConfiguration `locationName:"deliveryDestinationConfiguration" type:"structure" required:"true"` - - // A name for this delivery destination. This name must be unique for all delivery - // destinations in your account. - // - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` - - // The format for the logs that this delivery destination will receive. - OutputFormat *string `locationName:"outputFormat" type:"string" enum:"OutputFormat"` - - // An optional list of key-value pairs to associate with the resource. - // - // For more information about tagging, see Tagging Amazon Web Services resources - // (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliveryDestinationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliveryDestinationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutDeliveryDestinationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutDeliveryDestinationInput"} - if s.DeliveryDestinationConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("DeliveryDestinationConfiguration")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - if s.DeliveryDestinationConfiguration != nil { - if err := s.DeliveryDestinationConfiguration.Validate(); err != nil { - invalidParams.AddNested("DeliveryDestinationConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDeliveryDestinationConfiguration sets the DeliveryDestinationConfiguration field's value. -func (s *PutDeliveryDestinationInput) SetDeliveryDestinationConfiguration(v *DeliveryDestinationConfiguration) *PutDeliveryDestinationInput { - s.DeliveryDestinationConfiguration = v - return s -} - -// SetName sets the Name field's value. -func (s *PutDeliveryDestinationInput) SetName(v string) *PutDeliveryDestinationInput { - s.Name = &v - return s -} - -// SetOutputFormat sets the OutputFormat field's value. -func (s *PutDeliveryDestinationInput) SetOutputFormat(v string) *PutDeliveryDestinationInput { - s.OutputFormat = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *PutDeliveryDestinationInput) SetTags(v map[string]*string) *PutDeliveryDestinationInput { - s.Tags = v - return s -} - -type PutDeliveryDestinationOutput struct { - _ struct{} `type:"structure"` - - // A structure containing information about the delivery destination that you - // just created or updated. - DeliveryDestination *DeliveryDestination `locationName:"deliveryDestination" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliveryDestinationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliveryDestinationOutput) GoString() string { - return s.String() -} - -// SetDeliveryDestination sets the DeliveryDestination field's value. -func (s *PutDeliveryDestinationOutput) SetDeliveryDestination(v *DeliveryDestination) *PutDeliveryDestinationOutput { - s.DeliveryDestination = v - return s -} - -type PutDeliveryDestinationPolicyInput struct { - _ struct{} `type:"structure"` - - // The name of the delivery destination to assign this policy to. - // - // DeliveryDestinationName is a required field - DeliveryDestinationName *string `locationName:"deliveryDestinationName" min:"1" type:"string" required:"true"` - - // The contents of the policy. - // - // DeliveryDestinationPolicy is a required field - DeliveryDestinationPolicy *string `locationName:"deliveryDestinationPolicy" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliveryDestinationPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliveryDestinationPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutDeliveryDestinationPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutDeliveryDestinationPolicyInput"} - if s.DeliveryDestinationName == nil { - invalidParams.Add(request.NewErrParamRequired("DeliveryDestinationName")) - } - if s.DeliveryDestinationName != nil && len(*s.DeliveryDestinationName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DeliveryDestinationName", 1)) - } - if s.DeliveryDestinationPolicy == nil { - invalidParams.Add(request.NewErrParamRequired("DeliveryDestinationPolicy")) - } - if s.DeliveryDestinationPolicy != nil && len(*s.DeliveryDestinationPolicy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DeliveryDestinationPolicy", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDeliveryDestinationName sets the DeliveryDestinationName field's value. -func (s *PutDeliveryDestinationPolicyInput) SetDeliveryDestinationName(v string) *PutDeliveryDestinationPolicyInput { - s.DeliveryDestinationName = &v - return s -} - -// SetDeliveryDestinationPolicy sets the DeliveryDestinationPolicy field's value. -func (s *PutDeliveryDestinationPolicyInput) SetDeliveryDestinationPolicy(v string) *PutDeliveryDestinationPolicyInput { - s.DeliveryDestinationPolicy = &v - return s -} - -type PutDeliveryDestinationPolicyOutput struct { - _ struct{} `type:"structure"` - - // The contents of the policy that you just created. - Policy *Policy `locationName:"policy" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliveryDestinationPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliveryDestinationPolicyOutput) GoString() string { - return s.String() -} - -// SetPolicy sets the Policy field's value. -func (s *PutDeliveryDestinationPolicyOutput) SetPolicy(v *Policy) *PutDeliveryDestinationPolicyOutput { - s.Policy = v - return s -} - -type PutDeliverySourceInput struct { - _ struct{} `type:"structure"` - - // Defines the type of log that the source is sending. - // - // * For Amazon CodeWhisperer, the valid value is EVENT_LOGS. - // - // * For IAM Identity Centerr, the valid value is ERROR_LOGS. - // - // * For Amazon WorkMail, the valid values are ACCESS_CONTROL_LOGS, AUTHENTICATION_LOGS, - // WORKMAIL_AVAILABILITY_PROVIDER_LOGS, and WORKMAIL_MAILBOX_ACCESS_LOGS. - // - // LogType is a required field - LogType *string `locationName:"logType" min:"1" type:"string" required:"true"` - - // A name for this delivery source. This name must be unique for all delivery - // sources in your account. - // - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` - - // The ARN of the Amazon Web Services resource that is generating and sending - // logs. For example, arn:aws:workmail:us-east-1:123456789012:organization/m-1234EXAMPLEabcd1234abcd1234abcd1234 - // - // ResourceArn is a required field - ResourceArn *string `locationName:"resourceArn" type:"string" required:"true"` - - // An optional list of key-value pairs to associate with the resource. - // - // For more information about tagging, see Tagging Amazon Web Services resources - // (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliverySourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliverySourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutDeliverySourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutDeliverySourceInput"} - if s.LogType == nil { - invalidParams.Add(request.NewErrParamRequired("LogType")) - } - if s.LogType != nil && len(*s.LogType) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogType", 1)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogType sets the LogType field's value. -func (s *PutDeliverySourceInput) SetLogType(v string) *PutDeliverySourceInput { - s.LogType = &v - return s -} - -// SetName sets the Name field's value. -func (s *PutDeliverySourceInput) SetName(v string) *PutDeliverySourceInput { - s.Name = &v - return s -} - -// SetResourceArn sets the ResourceArn field's value. -func (s *PutDeliverySourceInput) SetResourceArn(v string) *PutDeliverySourceInput { - s.ResourceArn = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *PutDeliverySourceInput) SetTags(v map[string]*string) *PutDeliverySourceInput { - s.Tags = v - return s -} - -type PutDeliverySourceOutput struct { - _ struct{} `type:"structure"` - - // A structure containing information about the delivery source that was just - // created or updated. - DeliverySource *DeliverySource `locationName:"deliverySource" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliverySourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDeliverySourceOutput) GoString() string { - return s.String() -} - -// SetDeliverySource sets the DeliverySource field's value. -func (s *PutDeliverySourceOutput) SetDeliverySource(v *DeliverySource) *PutDeliverySourceOutput { - s.DeliverySource = v - return s -} - -type PutDestinationInput struct { - _ struct{} `type:"structure"` - - // A name for the destination. - // - // DestinationName is a required field - DestinationName *string `locationName:"destinationName" min:"1" type:"string" required:"true"` - - // The ARN of an IAM role that grants CloudWatch Logs permissions to call the - // Amazon Kinesis PutRecord operation on the destination stream. - // - // RoleArn is a required field - RoleArn *string `locationName:"roleArn" min:"1" type:"string" required:"true"` - - // An optional list of key-value pairs to associate with the resource. - // - // For more information about tagging, see Tagging Amazon Web Services resources - // (https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) - Tags map[string]*string `locationName:"tags" min:"1" type:"map"` - - // The ARN of an Amazon Kinesis stream to which to deliver matching log events. - // - // TargetArn is a required field - TargetArn *string `locationName:"targetArn" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDestinationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDestinationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutDestinationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutDestinationInput"} - if s.DestinationName == nil { - invalidParams.Add(request.NewErrParamRequired("DestinationName")) - } - if s.DestinationName != nil && len(*s.DestinationName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DestinationName", 1)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 1)) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - if s.TargetArn == nil { - invalidParams.Add(request.NewErrParamRequired("TargetArn")) - } - if s.TargetArn != nil && len(*s.TargetArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TargetArn", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestinationName sets the DestinationName field's value. -func (s *PutDestinationInput) SetDestinationName(v string) *PutDestinationInput { - s.DestinationName = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *PutDestinationInput) SetRoleArn(v string) *PutDestinationInput { - s.RoleArn = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *PutDestinationInput) SetTags(v map[string]*string) *PutDestinationInput { - s.Tags = v - return s -} - -// SetTargetArn sets the TargetArn field's value. -func (s *PutDestinationInput) SetTargetArn(v string) *PutDestinationInput { - s.TargetArn = &v - return s -} - -type PutDestinationOutput struct { - _ struct{} `type:"structure"` - - // The destination. - Destination *Destination `locationName:"destination" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDestinationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDestinationOutput) GoString() string { - return s.String() -} - -// SetDestination sets the Destination field's value. -func (s *PutDestinationOutput) SetDestination(v *Destination) *PutDestinationOutput { - s.Destination = v - return s -} - -type PutDestinationPolicyInput struct { - _ struct{} `type:"structure"` - - // An IAM policy document that authorizes cross-account users to deliver their - // log events to the associated destination. This can be up to 5120 bytes. - // - // AccessPolicy is a required field - AccessPolicy *string `locationName:"accessPolicy" min:"1" type:"string" required:"true"` - - // A name for an existing destination. - // - // DestinationName is a required field - DestinationName *string `locationName:"destinationName" min:"1" type:"string" required:"true"` - - // Specify true if you are updating an existing destination policy to grant - // permission to an organization ID instead of granting permission to individual - // Amazon Web Services accounts. Before you update a destination policy this - // way, you must first update the subscription filters in the accounts that - // send logs to this destination. If you do not, the subscription filters might - // stop working. By specifying true for forceUpdate, you are affirming that - // you have already updated the subscription filters. For more information, - // see Updating an existing cross-account subscription (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Cross-Account-Log_Subscription-Update.html) - // - // If you omit this parameter, the default of false is used. - ForceUpdate *bool `locationName:"forceUpdate" type:"boolean"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDestinationPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDestinationPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutDestinationPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutDestinationPolicyInput"} - if s.AccessPolicy == nil { - invalidParams.Add(request.NewErrParamRequired("AccessPolicy")) - } - if s.AccessPolicy != nil && len(*s.AccessPolicy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AccessPolicy", 1)) - } - if s.DestinationName == nil { - invalidParams.Add(request.NewErrParamRequired("DestinationName")) - } - if s.DestinationName != nil && len(*s.DestinationName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DestinationName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccessPolicy sets the AccessPolicy field's value. -func (s *PutDestinationPolicyInput) SetAccessPolicy(v string) *PutDestinationPolicyInput { - s.AccessPolicy = &v - return s -} - -// SetDestinationName sets the DestinationName field's value. -func (s *PutDestinationPolicyInput) SetDestinationName(v string) *PutDestinationPolicyInput { - s.DestinationName = &v - return s -} - -// SetForceUpdate sets the ForceUpdate field's value. -func (s *PutDestinationPolicyInput) SetForceUpdate(v bool) *PutDestinationPolicyInput { - s.ForceUpdate = &v - return s -} - -type PutDestinationPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDestinationPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutDestinationPolicyOutput) GoString() string { - return s.String() -} - -type PutLogEventsInput struct { - _ struct{} `type:"structure"` - - // The log events. - // - // LogEvents is a required field - LogEvents []*InputLogEvent `locationName:"logEvents" min:"1" type:"list" required:"true"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The name of the log stream. - // - // LogStreamName is a required field - LogStreamName *string `locationName:"logStreamName" min:"1" type:"string" required:"true"` - - // The sequence token obtained from the response of the previous PutLogEvents - // call. - // - // The sequenceToken parameter is now ignored in PutLogEvents actions. PutLogEvents - // actions are now accepted and never return InvalidSequenceTokenException or - // DataAlreadyAcceptedException even if the sequence token is not valid. - SequenceToken *string `locationName:"sequenceToken" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutLogEventsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutLogEventsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutLogEventsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutLogEventsInput"} - if s.LogEvents == nil { - invalidParams.Add(request.NewErrParamRequired("LogEvents")) - } - if s.LogEvents != nil && len(s.LogEvents) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogEvents", 1)) - } - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.LogStreamName == nil { - invalidParams.Add(request.NewErrParamRequired("LogStreamName")) - } - if s.LogStreamName != nil && len(*s.LogStreamName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamName", 1)) - } - if s.SequenceToken != nil && len(*s.SequenceToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SequenceToken", 1)) - } - if s.LogEvents != nil { - for i, v := range s.LogEvents { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LogEvents", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogEvents sets the LogEvents field's value. -func (s *PutLogEventsInput) SetLogEvents(v []*InputLogEvent) *PutLogEventsInput { - s.LogEvents = v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *PutLogEventsInput) SetLogGroupName(v string) *PutLogEventsInput { - s.LogGroupName = &v - return s -} - -// SetLogStreamName sets the LogStreamName field's value. -func (s *PutLogEventsInput) SetLogStreamName(v string) *PutLogEventsInput { - s.LogStreamName = &v - return s -} - -// SetSequenceToken sets the SequenceToken field's value. -func (s *PutLogEventsInput) SetSequenceToken(v string) *PutLogEventsInput { - s.SequenceToken = &v - return s -} - -type PutLogEventsOutput struct { - _ struct{} `type:"structure"` - - // The next sequence token. - // - // This field has been deprecated. - // - // The sequence token is now ignored in PutLogEvents actions. PutLogEvents actions - // are always accepted even if the sequence token is not valid. You can use - // parallel PutLogEvents actions on the same log stream and you do not need - // to wait for the response of a previous PutLogEvents action to obtain the - // nextSequenceToken value. - NextSequenceToken *string `locationName:"nextSequenceToken" min:"1" type:"string"` - - // The rejected events. - RejectedLogEventsInfo *RejectedLogEventsInfo `locationName:"rejectedLogEventsInfo" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutLogEventsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutLogEventsOutput) GoString() string { - return s.String() -} - -// SetNextSequenceToken sets the NextSequenceToken field's value. -func (s *PutLogEventsOutput) SetNextSequenceToken(v string) *PutLogEventsOutput { - s.NextSequenceToken = &v - return s -} - -// SetRejectedLogEventsInfo sets the RejectedLogEventsInfo field's value. -func (s *PutLogEventsOutput) SetRejectedLogEventsInfo(v *RejectedLogEventsInfo) *PutLogEventsOutput { - s.RejectedLogEventsInfo = v - return s -} - -type PutMetricFilterInput struct { - _ struct{} `type:"structure"` - - // A name for the metric filter. - // - // FilterName is a required field - FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"` - - // A filter pattern for extracting metric data out of ingested log events. - // - // FilterPattern is a required field - FilterPattern *string `locationName:"filterPattern" type:"string" required:"true"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // A collection of information that defines how metric data gets emitted. - // - // MetricTransformations is a required field - MetricTransformations []*MetricTransformation `locationName:"metricTransformations" min:"1" type:"list" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutMetricFilterInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutMetricFilterInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutMetricFilterInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutMetricFilterInput"} - if s.FilterName == nil { - invalidParams.Add(request.NewErrParamRequired("FilterName")) - } - if s.FilterName != nil && len(*s.FilterName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("FilterName", 1)) - } - if s.FilterPattern == nil { - invalidParams.Add(request.NewErrParamRequired("FilterPattern")) - } - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.MetricTransformations == nil { - invalidParams.Add(request.NewErrParamRequired("MetricTransformations")) - } - if s.MetricTransformations != nil && len(s.MetricTransformations) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MetricTransformations", 1)) - } - if s.MetricTransformations != nil { - for i, v := range s.MetricTransformations { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "MetricTransformations", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilterName sets the FilterName field's value. -func (s *PutMetricFilterInput) SetFilterName(v string) *PutMetricFilterInput { - s.FilterName = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *PutMetricFilterInput) SetFilterPattern(v string) *PutMetricFilterInput { - s.FilterPattern = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *PutMetricFilterInput) SetLogGroupName(v string) *PutMetricFilterInput { - s.LogGroupName = &v - return s -} - -// SetMetricTransformations sets the MetricTransformations field's value. -func (s *PutMetricFilterInput) SetMetricTransformations(v []*MetricTransformation) *PutMetricFilterInput { - s.MetricTransformations = v - return s -} - -type PutMetricFilterOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutMetricFilterOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutMetricFilterOutput) GoString() string { - return s.String() -} - -type PutQueryDefinitionInput struct { - _ struct{} `type:"structure"` - - // Used as an idempotency token, to avoid returning an exception if the service - // receives the same request twice because of a network error. - ClientToken *string `locationName:"clientToken" min:"36" type:"string" idempotencyToken:"true"` - - // Use this parameter to include specific log groups as part of your query definition. - // - // If you are updating a query definition and you omit this parameter, then - // the updated definition will contain no log groups. - LogGroupNames []*string `locationName:"logGroupNames" type:"list"` - - // A name for the query definition. If you are saving numerous query definitions, - // we recommend that you name them. This way, you can find the ones you want - // by using the first part of the name as a filter in the queryDefinitionNamePrefix - // parameter of DescribeQueryDefinitions (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeQueryDefinitions.html). - // - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` - - // If you are updating a query definition, use this parameter to specify the - // ID of the query definition that you want to update. You can use DescribeQueryDefinitions - // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeQueryDefinitions.html) - // to retrieve the IDs of your saved query definitions. - // - // If you are creating a query definition, do not specify this parameter. CloudWatch - // generates a unique ID for the new query definition and include it in the - // response to this operation. - QueryDefinitionId *string `locationName:"queryDefinitionId" type:"string"` - - // The query string to use for this definition. For more information, see CloudWatch - // Logs Insights Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). - // - // QueryString is a required field - QueryString *string `locationName:"queryString" min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutQueryDefinitionInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutQueryDefinitionInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutQueryDefinitionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutQueryDefinitionInput"} - if s.ClientToken != nil && len(*s.ClientToken) < 36 { - invalidParams.Add(request.NewErrParamMinLen("ClientToken", 36)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.QueryString == nil { - invalidParams.Add(request.NewErrParamRequired("QueryString")) - } - if s.QueryString != nil && len(*s.QueryString) < 1 { - invalidParams.Add(request.NewErrParamMinLen("QueryString", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetClientToken sets the ClientToken field's value. -func (s *PutQueryDefinitionInput) SetClientToken(v string) *PutQueryDefinitionInput { - s.ClientToken = &v - return s -} - -// SetLogGroupNames sets the LogGroupNames field's value. -func (s *PutQueryDefinitionInput) SetLogGroupNames(v []*string) *PutQueryDefinitionInput { - s.LogGroupNames = v - return s -} - -// SetName sets the Name field's value. -func (s *PutQueryDefinitionInput) SetName(v string) *PutQueryDefinitionInput { - s.Name = &v - return s -} - -// SetQueryDefinitionId sets the QueryDefinitionId field's value. -func (s *PutQueryDefinitionInput) SetQueryDefinitionId(v string) *PutQueryDefinitionInput { - s.QueryDefinitionId = &v - return s -} - -// SetQueryString sets the QueryString field's value. -func (s *PutQueryDefinitionInput) SetQueryString(v string) *PutQueryDefinitionInput { - s.QueryString = &v - return s -} - -type PutQueryDefinitionOutput struct { - _ struct{} `type:"structure"` - - // The ID of the query definition. - QueryDefinitionId *string `locationName:"queryDefinitionId" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutQueryDefinitionOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutQueryDefinitionOutput) GoString() string { - return s.String() -} - -// SetQueryDefinitionId sets the QueryDefinitionId field's value. -func (s *PutQueryDefinitionOutput) SetQueryDefinitionId(v string) *PutQueryDefinitionOutput { - s.QueryDefinitionId = &v - return s -} - -type PutResourcePolicyInput struct { - _ struct{} `type:"structure"` - - // Details of the new policy, including the identity of the principal that is - // enabled to put logs to this account. This is formatted as a JSON string. - // This parameter is required. - // - // The following example creates a resource policy enabling the Route 53 service - // to put DNS query logs in to the specified log group. Replace "logArn" with - // the ARN of your CloudWatch Logs resource, such as a log group or log stream. - // - // CloudWatch Logs also supports aws:SourceArn (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn) - // and aws:SourceAccount (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount) - // condition context keys. - // - // In the example resource policy, you would replace the value of SourceArn - // with the resource making the call from Route 53 to CloudWatch Logs. You would - // also replace the value of SourceAccount with the Amazon Web Services account - // ID making that call. - // - // { "Version": "2012-10-17", "Statement": [ { "Sid": "Route53LogsToCloudWatchLogs", - // "Effect": "Allow", "Principal": { "Service": [ "route53.amazonaws.com" ] - // }, "Action": "logs:PutLogEvents", "Resource": "logArn", "Condition": { "ArnLike": - // { "aws:SourceArn": "myRoute53ResourceArn" }, "StringEquals": { "aws:SourceAccount": - // "myAwsAccountId" } } } ] } - PolicyDocument *string `locationName:"policyDocument" min:"1" type:"string"` - - // Name of the new policy. This parameter is required. - PolicyName *string `locationName:"policyName" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutResourcePolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutResourcePolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutResourcePolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutResourcePolicyInput"} - if s.PolicyDocument != nil && len(*s.PolicyDocument) < 1 { - invalidParams.Add(request.NewErrParamMinLen("PolicyDocument", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPolicyDocument sets the PolicyDocument field's value. -func (s *PutResourcePolicyInput) SetPolicyDocument(v string) *PutResourcePolicyInput { - s.PolicyDocument = &v - return s -} - -// SetPolicyName sets the PolicyName field's value. -func (s *PutResourcePolicyInput) SetPolicyName(v string) *PutResourcePolicyInput { - s.PolicyName = &v - return s -} - -type PutResourcePolicyOutput struct { - _ struct{} `type:"structure"` - - // The new policy. - ResourcePolicy *ResourcePolicy `locationName:"resourcePolicy" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutResourcePolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutResourcePolicyOutput) GoString() string { - return s.String() -} - -// SetResourcePolicy sets the ResourcePolicy field's value. -func (s *PutResourcePolicyOutput) SetResourcePolicy(v *ResourcePolicy) *PutResourcePolicyOutput { - s.ResourcePolicy = v - return s -} - -type PutRetentionPolicyInput struct { - _ struct{} `type:"structure"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The number of days to retain the log events in the specified log group. Possible - // values are: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, - // 1096, 1827, 2192, 2557, 2922, 3288, and 3653. - // - // To set a log group so that its log events do not expire, use DeleteRetentionPolicy - // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteRetentionPolicy.html). - // - // RetentionInDays is a required field - RetentionInDays *int64 `locationName:"retentionInDays" type:"integer" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutRetentionPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutRetentionPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutRetentionPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutRetentionPolicyInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.RetentionInDays == nil { - invalidParams.Add(request.NewErrParamRequired("RetentionInDays")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *PutRetentionPolicyInput) SetLogGroupName(v string) *PutRetentionPolicyInput { - s.LogGroupName = &v - return s -} - -// SetRetentionInDays sets the RetentionInDays field's value. -func (s *PutRetentionPolicyInput) SetRetentionInDays(v int64) *PutRetentionPolicyInput { - s.RetentionInDays = &v - return s -} - -type PutRetentionPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutRetentionPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutRetentionPolicyOutput) GoString() string { - return s.String() -} - -type PutSubscriptionFilterInput struct { - _ struct{} `type:"structure"` - - // The ARN of the destination to deliver matching log events to. Currently, - // the supported destinations are: - // - // * An Amazon Kinesis stream belonging to the same account as the subscription - // filter, for same-account delivery. - // - // * A logical destination (specified using an ARN) belonging to a different - // account, for cross-account delivery. If you're setting up a cross-account - // subscription, the destination must have an IAM policy associated with - // it. The IAM policy must allow the sender to send logs to the destination. - // For more information, see PutDestinationPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDestinationPolicy.html). - // - // * A Kinesis Data Firehose delivery stream belonging to the same account - // as the subscription filter, for same-account delivery. - // - // * A Lambda function belonging to the same account as the subscription - // filter, for same-account delivery. - // - // DestinationArn is a required field - DestinationArn *string `locationName:"destinationArn" min:"1" type:"string" required:"true"` - - // The method used to distribute log data to the destination. By default, log - // data is grouped by log stream, but the grouping can be set to random for - // a more even distribution. This property is only applicable when the destination - // is an Amazon Kinesis data stream. - Distribution *string `locationName:"distribution" type:"string" enum:"Distribution"` - - // A name for the subscription filter. If you are updating an existing filter, - // you must specify the correct name in filterName. To find the name of the - // filter currently associated with a log group, use DescribeSubscriptionFilters - // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeSubscriptionFilters.html). - // - // FilterName is a required field - FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"` - - // A filter pattern for subscribing to a filtered stream of log events. - // - // FilterPattern is a required field - FilterPattern *string `locationName:"filterPattern" type:"string" required:"true"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The ARN of an IAM role that grants CloudWatch Logs permissions to deliver - // ingested log events to the destination stream. You don't need to provide - // the ARN when you are working with a logical destination for cross-account - // delivery. - RoleArn *string `locationName:"roleArn" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutSubscriptionFilterInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutSubscriptionFilterInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutSubscriptionFilterInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutSubscriptionFilterInput"} - if s.DestinationArn == nil { - invalidParams.Add(request.NewErrParamRequired("DestinationArn")) - } - if s.DestinationArn != nil && len(*s.DestinationArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DestinationArn", 1)) - } - if s.FilterName == nil { - invalidParams.Add(request.NewErrParamRequired("FilterName")) - } - if s.FilterName != nil && len(*s.FilterName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("FilterName", 1)) - } - if s.FilterPattern == nil { - invalidParams.Add(request.NewErrParamRequired("FilterPattern")) - } - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.RoleArn != nil && len(*s.RoleArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestinationArn sets the DestinationArn field's value. -func (s *PutSubscriptionFilterInput) SetDestinationArn(v string) *PutSubscriptionFilterInput { - s.DestinationArn = &v - return s -} - -// SetDistribution sets the Distribution field's value. -func (s *PutSubscriptionFilterInput) SetDistribution(v string) *PutSubscriptionFilterInput { - s.Distribution = &v - return s -} - -// SetFilterName sets the FilterName field's value. -func (s *PutSubscriptionFilterInput) SetFilterName(v string) *PutSubscriptionFilterInput { - s.FilterName = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *PutSubscriptionFilterInput) SetFilterPattern(v string) *PutSubscriptionFilterInput { - s.FilterPattern = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *PutSubscriptionFilterInput) SetLogGroupName(v string) *PutSubscriptionFilterInput { - s.LogGroupName = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *PutSubscriptionFilterInput) SetRoleArn(v string) *PutSubscriptionFilterInput { - s.RoleArn = &v - return s -} - -type PutSubscriptionFilterOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutSubscriptionFilterOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PutSubscriptionFilterOutput) GoString() string { - return s.String() -} - -// Reserved. -type QueryCompileError struct { - _ struct{} `type:"structure"` - - // Reserved. - Location *QueryCompileErrorLocation `locationName:"location" type:"structure"` - - // Reserved. - Message *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryCompileError) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryCompileError) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *QueryCompileError) SetLocation(v *QueryCompileErrorLocation) *QueryCompileError { - s.Location = v - return s -} - -// SetMessage sets the Message field's value. -func (s *QueryCompileError) SetMessage(v string) *QueryCompileError { - s.Message = &v - return s -} - -// Reserved. -type QueryCompileErrorLocation struct { - _ struct{} `type:"structure"` - - // Reserved. - EndCharOffset *int64 `locationName:"endCharOffset" type:"integer"` - - // Reserved. - StartCharOffset *int64 `locationName:"startCharOffset" type:"integer"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryCompileErrorLocation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryCompileErrorLocation) GoString() string { - return s.String() -} - -// SetEndCharOffset sets the EndCharOffset field's value. -func (s *QueryCompileErrorLocation) SetEndCharOffset(v int64) *QueryCompileErrorLocation { - s.EndCharOffset = &v - return s -} - -// SetStartCharOffset sets the StartCharOffset field's value. -func (s *QueryCompileErrorLocation) SetStartCharOffset(v int64) *QueryCompileErrorLocation { - s.StartCharOffset = &v - return s -} - -// This structure contains details about a saved CloudWatch Logs Insights query -// definition. -type QueryDefinition struct { - _ struct{} `type:"structure"` - - // The date that the query definition was most recently modified. - LastModified *int64 `locationName:"lastModified" type:"long"` - - // If this query definition contains a list of log groups that it is limited - // to, that list appears here. - LogGroupNames []*string `locationName:"logGroupNames" type:"list"` - - // The name of the query definition. - Name *string `locationName:"name" min:"1" type:"string"` - - // The unique ID of the query definition. - QueryDefinitionId *string `locationName:"queryDefinitionId" type:"string"` - - // The query string to use for this definition. For more information, see CloudWatch - // Logs Insights Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). - QueryString *string `locationName:"queryString" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryDefinition) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryDefinition) GoString() string { - return s.String() -} - -// SetLastModified sets the LastModified field's value. -func (s *QueryDefinition) SetLastModified(v int64) *QueryDefinition { - s.LastModified = &v - return s -} - -// SetLogGroupNames sets the LogGroupNames field's value. -func (s *QueryDefinition) SetLogGroupNames(v []*string) *QueryDefinition { - s.LogGroupNames = v - return s -} - -// SetName sets the Name field's value. -func (s *QueryDefinition) SetName(v string) *QueryDefinition { - s.Name = &v - return s -} - -// SetQueryDefinitionId sets the QueryDefinitionId field's value. -func (s *QueryDefinition) SetQueryDefinitionId(v string) *QueryDefinition { - s.QueryDefinitionId = &v - return s -} - -// SetQueryString sets the QueryString field's value. -func (s *QueryDefinition) SetQueryString(v string) *QueryDefinition { - s.QueryString = &v - return s -} - -// Information about one CloudWatch Logs Insights query that matches the request -// in a DescribeQueries operation. -type QueryInfo struct { - _ struct{} `type:"structure"` - - // The date and time that this query was created. - CreateTime *int64 `locationName:"createTime" type:"long"` - - // The name of the log group scanned by this query. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // The unique ID number of this query. - QueryId *string `locationName:"queryId" type:"string"` - - // The query string used in this query. - QueryString *string `locationName:"queryString" type:"string"` - - // The status of this query. Possible values are Cancelled, Complete, Failed, - // Running, Scheduled, and Unknown. - Status *string `locationName:"status" type:"string" enum:"QueryStatus"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryInfo) GoString() string { - return s.String() -} - -// SetCreateTime sets the CreateTime field's value. -func (s *QueryInfo) SetCreateTime(v int64) *QueryInfo { - s.CreateTime = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *QueryInfo) SetLogGroupName(v string) *QueryInfo { - s.LogGroupName = &v - return s -} - -// SetQueryId sets the QueryId field's value. -func (s *QueryInfo) SetQueryId(v string) *QueryInfo { - s.QueryId = &v - return s -} - -// SetQueryString sets the QueryString field's value. -func (s *QueryInfo) SetQueryString(v string) *QueryInfo { - s.QueryString = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *QueryInfo) SetStatus(v string) *QueryInfo { - s.Status = &v - return s -} - -// Contains the number of log events scanned by the query, the number of log -// events that matched the query criteria, and the total number of bytes in -// the log events that were scanned. -type QueryStatistics struct { - _ struct{} `type:"structure"` - - // The total number of bytes in the log events scanned during the query. - BytesScanned *float64 `locationName:"bytesScanned" type:"double"` - - // The number of log events that matched the query string. - RecordsMatched *float64 `locationName:"recordsMatched" type:"double"` - - // The total number of log events scanned during the query. - RecordsScanned *float64 `locationName:"recordsScanned" type:"double"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryStatistics) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s QueryStatistics) GoString() string { - return s.String() -} - -// SetBytesScanned sets the BytesScanned field's value. -func (s *QueryStatistics) SetBytesScanned(v float64) *QueryStatistics { - s.BytesScanned = &v - return s -} - -// SetRecordsMatched sets the RecordsMatched field's value. -func (s *QueryStatistics) SetRecordsMatched(v float64) *QueryStatistics { - s.RecordsMatched = &v - return s -} - -// SetRecordsScanned sets the RecordsScanned field's value. -func (s *QueryStatistics) SetRecordsScanned(v float64) *QueryStatistics { - s.RecordsScanned = &v - return s -} - -// Represents the rejected events. -type RejectedLogEventsInfo struct { - _ struct{} `type:"structure"` - - // The expired log events. - ExpiredLogEventEndIndex *int64 `locationName:"expiredLogEventEndIndex" type:"integer"` - - // The index of the first log event that is too new. This field is inclusive. - TooNewLogEventStartIndex *int64 `locationName:"tooNewLogEventStartIndex" type:"integer"` - - // The index of the last log event that is too old. This field is exclusive. - TooOldLogEventEndIndex *int64 `locationName:"tooOldLogEventEndIndex" type:"integer"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RejectedLogEventsInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RejectedLogEventsInfo) GoString() string { - return s.String() -} - -// SetExpiredLogEventEndIndex sets the ExpiredLogEventEndIndex field's value. -func (s *RejectedLogEventsInfo) SetExpiredLogEventEndIndex(v int64) *RejectedLogEventsInfo { - s.ExpiredLogEventEndIndex = &v - return s -} - -// SetTooNewLogEventStartIndex sets the TooNewLogEventStartIndex field's value. -func (s *RejectedLogEventsInfo) SetTooNewLogEventStartIndex(v int64) *RejectedLogEventsInfo { - s.TooNewLogEventStartIndex = &v - return s -} - -// SetTooOldLogEventEndIndex sets the TooOldLogEventEndIndex field's value. -func (s *RejectedLogEventsInfo) SetTooOldLogEventEndIndex(v int64) *RejectedLogEventsInfo { - s.TooOldLogEventEndIndex = &v - return s -} - -// The specified resource already exists. -type ResourceAlreadyExistsException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResourceAlreadyExistsException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResourceAlreadyExistsException) GoString() string { - return s.String() -} - -func newErrorResourceAlreadyExistsException(v protocol.ResponseMetadata) error { - return &ResourceAlreadyExistsException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ResourceAlreadyExistsException) Code() string { - return "ResourceAlreadyExistsException" -} - -// Message returns the exception's message. -func (s *ResourceAlreadyExistsException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceAlreadyExistsException) OrigErr() error { - return nil -} - -func (s *ResourceAlreadyExistsException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceAlreadyExistsException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ResourceAlreadyExistsException) RequestID() string { - return s.RespMetadata.RequestID -} - -// The specified resource does not exist. -type ResourceNotFoundException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResourceNotFoundException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResourceNotFoundException) GoString() string { - return s.String() -} - -func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { - return &ResourceNotFoundException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ResourceNotFoundException) Code() string { - return "ResourceNotFoundException" -} - -// Message returns the exception's message. -func (s *ResourceNotFoundException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceNotFoundException) OrigErr() error { - return nil -} - -func (s *ResourceNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceNotFoundException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ResourceNotFoundException) RequestID() string { - return s.RespMetadata.RequestID -} - -// A policy enabling one or more entities to put logs to a log group in this -// account. -type ResourcePolicy struct { - _ struct{} `type:"structure"` - - // Timestamp showing when this policy was last updated, expressed as the number - // of milliseconds after Jan 1, 1970 00:00:00 UTC. - LastUpdatedTime *int64 `locationName:"lastUpdatedTime" type:"long"` - - // The details of the policy. - PolicyDocument *string `locationName:"policyDocument" min:"1" type:"string"` - - // The name of the resource policy. - PolicyName *string `locationName:"policyName" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResourcePolicy) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResourcePolicy) GoString() string { - return s.String() -} - -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *ResourcePolicy) SetLastUpdatedTime(v int64) *ResourcePolicy { - s.LastUpdatedTime = &v - return s -} - -// SetPolicyDocument sets the PolicyDocument field's value. -func (s *ResourcePolicy) SetPolicyDocument(v string) *ResourcePolicy { - s.PolicyDocument = &v - return s -} - -// SetPolicyName sets the PolicyName field's value. -func (s *ResourcePolicy) SetPolicyName(v string) *ResourcePolicy { - s.PolicyName = &v - return s -} - -// Contains one field from one log event returned by a CloudWatch Logs Insights -// query, along with the value of that field. -// -// For more information about the fields that are generated by CloudWatch logs, -// see Supported Logs and Discovered Fields (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_AnalyzeLogData-discoverable-fields.html). -type ResultField struct { - _ struct{} `type:"structure"` - - // The log event field. - Field *string `locationName:"field" type:"string"` - - // The value of this field. - Value *string `locationName:"value" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResultField) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResultField) GoString() string { - return s.String() -} - -// SetField sets the Field field's value. -func (s *ResultField) SetField(v string) *ResultField { - s.Field = &v - return s -} - -// SetValue sets the Value field's value. -func (s *ResultField) SetValue(v string) *ResultField { - s.Value = &v - return s -} - -// Represents the search status of a log stream. -type SearchedLogStream struct { - _ struct{} `type:"structure"` - - // The name of the log stream. - LogStreamName *string `locationName:"logStreamName" min:"1" type:"string"` - - // Indicates whether all the events in this log stream were searched. - SearchedCompletely *bool `locationName:"searchedCompletely" type:"boolean"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SearchedLogStream) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SearchedLogStream) GoString() string { - return s.String() -} - -// SetLogStreamName sets the LogStreamName field's value. -func (s *SearchedLogStream) SetLogStreamName(v string) *SearchedLogStream { - s.LogStreamName = &v - return s -} - -// SetSearchedCompletely sets the SearchedCompletely field's value. -func (s *SearchedLogStream) SetSearchedCompletely(v bool) *SearchedLogStream { - s.SearchedCompletely = &v - return s -} - -// This request exceeds a service quota. -type ServiceQuotaExceededException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ServiceQuotaExceededException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ServiceQuotaExceededException) GoString() string { - return s.String() -} - -func newErrorServiceQuotaExceededException(v protocol.ResponseMetadata) error { - return &ServiceQuotaExceededException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ServiceQuotaExceededException) Code() string { - return "ServiceQuotaExceededException" -} - -// Message returns the exception's message. -func (s *ServiceQuotaExceededException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ServiceQuotaExceededException) OrigErr() error { - return nil -} - -func (s *ServiceQuotaExceededException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ServiceQuotaExceededException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ServiceQuotaExceededException) RequestID() string { - return s.RespMetadata.RequestID -} - -// The service cannot complete the request. -type ServiceUnavailableException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ServiceUnavailableException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ServiceUnavailableException) GoString() string { - return s.String() -} - -func newErrorServiceUnavailableException(v protocol.ResponseMetadata) error { - return &ServiceUnavailableException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ServiceUnavailableException) Code() string { - return "ServiceUnavailableException" -} - -// Message returns the exception's message. -func (s *ServiceUnavailableException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ServiceUnavailableException) OrigErr() error { - return nil -} - -func (s *ServiceUnavailableException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ServiceUnavailableException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ServiceUnavailableException) RequestID() string { - return s.RespMetadata.RequestID -} - -// his exception is returned if an unknown error occurs during a Live Tail session. -type SessionStreamingException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SessionStreamingException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SessionStreamingException) GoString() string { - return s.String() -} - -// The SessionStreamingException is and event in the StartLiveTailResponseStream group of events. -func (s *SessionStreamingException) eventStartLiveTailResponseStream() {} - -// UnmarshalEvent unmarshals the EventStream Message into the SessionStreamingException value. -// This method is only used internally within the SDK's EventStream handling. -func (s *SessionStreamingException) UnmarshalEvent( - payloadUnmarshaler protocol.PayloadUnmarshaler, - msg eventstream.Message, -) error { - if err := payloadUnmarshaler.UnmarshalPayload( - bytes.NewReader(msg.Payload), s, - ); err != nil { - return err - } - return nil -} - -// MarshalEvent marshals the type into an stream event value. This method -// should only used internally within the SDK's EventStream handling. -func (s *SessionStreamingException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { - msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) - var buf bytes.Buffer - if err = pm.MarshalPayload(&buf, s); err != nil { - return eventstream.Message{}, err - } - msg.Payload = buf.Bytes() - return msg, err -} - -func newErrorSessionStreamingException(v protocol.ResponseMetadata) error { - return &SessionStreamingException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *SessionStreamingException) Code() string { - return "SessionStreamingException" -} - -// Message returns the exception's message. -func (s *SessionStreamingException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *SessionStreamingException) OrigErr() error { - return nil -} - -func (s *SessionStreamingException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *SessionStreamingException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *SessionStreamingException) RequestID() string { - return s.RespMetadata.RequestID -} - -// This exception is returned in a Live Tail stream when the Live Tail session -// times out. Live Tail sessions time out after three hours. -type SessionTimeoutException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SessionTimeoutException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SessionTimeoutException) GoString() string { - return s.String() -} - -// The SessionTimeoutException is and event in the StartLiveTailResponseStream group of events. -func (s *SessionTimeoutException) eventStartLiveTailResponseStream() {} - -// UnmarshalEvent unmarshals the EventStream Message into the SessionTimeoutException value. -// This method is only used internally within the SDK's EventStream handling. -func (s *SessionTimeoutException) UnmarshalEvent( - payloadUnmarshaler protocol.PayloadUnmarshaler, - msg eventstream.Message, -) error { - if err := payloadUnmarshaler.UnmarshalPayload( - bytes.NewReader(msg.Payload), s, - ); err != nil { - return err - } - return nil -} - -// MarshalEvent marshals the type into an stream event value. This method -// should only used internally within the SDK's EventStream handling. -func (s *SessionTimeoutException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { - msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) - var buf bytes.Buffer - if err = pm.MarshalPayload(&buf, s); err != nil { - return eventstream.Message{}, err - } - msg.Payload = buf.Bytes() - return msg, err -} - -func newErrorSessionTimeoutException(v protocol.ResponseMetadata) error { - return &SessionTimeoutException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *SessionTimeoutException) Code() string { - return "SessionTimeoutException" -} - -// Message returns the exception's message. -func (s *SessionTimeoutException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *SessionTimeoutException) OrigErr() error { - return nil -} - -func (s *SessionTimeoutException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *SessionTimeoutException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *SessionTimeoutException) RequestID() string { - return s.RespMetadata.RequestID -} - -type StartLiveTailInput struct { - _ struct{} `type:"structure"` - - // An optional pattern to use to filter the results to include only log events - // that match the pattern. For example, a filter pattern of error 404 causes - // only log events that include both error and 404 to be included in the Live - // Tail stream. - // - // Regular expression filter patterns are supported. - // - // For more information about filter pattern syntax, see Filter and Pattern - // Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html). - LogEventFilterPattern *string `locationName:"logEventFilterPattern" type:"string"` - - // An array where each item in the array is a log group to include in the Live - // Tail session. - // - // Specify each log group by its ARN. - // - // If you specify an ARN, the ARN can't end with an asterisk (*). - // - // You can include up to 10 log groups. - // - // LogGroupIdentifiers is a required field - LogGroupIdentifiers []*string `locationName:"logGroupIdentifiers" min:"1" type:"list" required:"true"` - - // If you specify this parameter, then only log events in the log streams that - // have names that start with the prefixes that you specify here are included - // in the Live Tail session. - // - // If you specify this field, you can't also specify the logStreamNames field. - // - // You can specify this parameter only if you specify only one log group in - // logGroupIdentifiers. - LogStreamNamePrefixes []*string `locationName:"logStreamNamePrefixes" min:"1" type:"list"` - - // If you specify this parameter, then only log events in the log streams that - // you specify here are included in the Live Tail session. - // - // If you specify this field, you can't also specify the logStreamNamePrefixes - // field. - // - // You can specify this parameter only if you specify only one log group in - // logGroupIdentifiers. - LogStreamNames []*string `locationName:"logStreamNames" min:"1" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartLiveTailInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartLiveTailInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StartLiveTailInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StartLiveTailInput"} - if s.LogGroupIdentifiers == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupIdentifiers")) - } - if s.LogGroupIdentifiers != nil && len(s.LogGroupIdentifiers) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupIdentifiers", 1)) - } - if s.LogStreamNamePrefixes != nil && len(s.LogStreamNamePrefixes) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamNamePrefixes", 1)) - } - if s.LogStreamNames != nil && len(s.LogStreamNames) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogStreamNames", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogEventFilterPattern sets the LogEventFilterPattern field's value. -func (s *StartLiveTailInput) SetLogEventFilterPattern(v string) *StartLiveTailInput { - s.LogEventFilterPattern = &v - return s -} - -// SetLogGroupIdentifiers sets the LogGroupIdentifiers field's value. -func (s *StartLiveTailInput) SetLogGroupIdentifiers(v []*string) *StartLiveTailInput { - s.LogGroupIdentifiers = v - return s -} - -// SetLogStreamNamePrefixes sets the LogStreamNamePrefixes field's value. -func (s *StartLiveTailInput) SetLogStreamNamePrefixes(v []*string) *StartLiveTailInput { - s.LogStreamNamePrefixes = v - return s -} - -// SetLogStreamNames sets the LogStreamNames field's value. -func (s *StartLiveTailInput) SetLogStreamNames(v []*string) *StartLiveTailInput { - s.LogStreamNames = v - return s -} - -type StartLiveTailOutput struct { - _ struct{} `type:"structure"` - - eventStream *StartLiveTailEventStream -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartLiveTailOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartLiveTailOutput) GoString() string { - return s.String() -} - -// GetStream returns the type to interact with the event stream. -func (s *StartLiveTailOutput) GetStream() *StartLiveTailEventStream { - return s.eventStream -} - -// The StartLiveTailOutput is and event in the StartLiveTailResponseStream group of events. -func (s *StartLiveTailOutput) eventStartLiveTailResponseStream() {} - -// UnmarshalEvent unmarshals the EventStream Message into the StartLiveTailOutput value. -// This method is only used internally within the SDK's EventStream handling. -func (s *StartLiveTailOutput) UnmarshalEvent( - payloadUnmarshaler protocol.PayloadUnmarshaler, - msg eventstream.Message, -) error { - if err := payloadUnmarshaler.UnmarshalPayload( - bytes.NewReader(msg.Payload), s, - ); err != nil { - return err - } - return nil -} - -// MarshalEvent marshals the type into an stream event value. This method -// should only used internally within the SDK's EventStream handling. -func (s *StartLiveTailOutput) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { - msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) - var buf bytes.Buffer - if err = pm.MarshalPayload(&buf, s); err != nil { - return eventstream.Message{}, err - } - msg.Payload = buf.Bytes() - return msg, err -} - -// StartLiveTailResponseStreamEvent groups together all EventStream -// events writes for StartLiveTailResponseStream. -// -// These events are: -// -// - LiveTailSessionStart -// - LiveTailSessionUpdate -type StartLiveTailResponseStreamEvent interface { - eventStartLiveTailResponseStream() - eventstreamapi.Marshaler - eventstreamapi.Unmarshaler -} - -// StartLiveTailResponseStreamReader provides the interface for reading to the stream. The -// default implementation for this interface will be StartLiveTailResponseStream. -// -// The reader's Close method must allow multiple concurrent calls. -// -// These events are: -// -// - LiveTailSessionStart -// - LiveTailSessionUpdate -// - StartLiveTailResponseStreamUnknownEvent -type StartLiveTailResponseStreamReader interface { - // Returns a channel of events as they are read from the event stream. - Events() <-chan StartLiveTailResponseStreamEvent - - // Close will stop the reader reading events from the stream. - Close() error - - // Returns any error that has occurred while reading from the event stream. - Err() error -} - -type readStartLiveTailResponseStream struct { - eventReader *eventstreamapi.EventReader - stream chan StartLiveTailResponseStreamEvent - err *eventstreamapi.OnceError - - done chan struct{} - closeOnce sync.Once -} - -func newReadStartLiveTailResponseStream(eventReader *eventstreamapi.EventReader) *readStartLiveTailResponseStream { - r := &readStartLiveTailResponseStream{ - eventReader: eventReader, - stream: make(chan StartLiveTailResponseStreamEvent), - done: make(chan struct{}), - err: eventstreamapi.NewOnceError(), - } - go r.readEventStream() - - return r -} - -// Close will close the underlying event stream reader. -func (r *readStartLiveTailResponseStream) Close() error { - r.closeOnce.Do(r.safeClose) - return r.Err() -} - -func (r *readStartLiveTailResponseStream) ErrorSet() <-chan struct{} { - return r.err.ErrorSet() -} - -func (r *readStartLiveTailResponseStream) Closed() <-chan struct{} { - return r.done -} - -func (r *readStartLiveTailResponseStream) safeClose() { - close(r.done) -} - -func (r *readStartLiveTailResponseStream) Err() error { - return r.err.Err() -} - -func (r *readStartLiveTailResponseStream) Events() <-chan StartLiveTailResponseStreamEvent { - return r.stream -} - -func (r *readStartLiveTailResponseStream) readEventStream() { - defer r.Close() - defer close(r.stream) - - for { - event, err := r.eventReader.ReadEvent() - if err != nil { - if err == io.EOF { - return - } - select { - case <-r.done: - // If closed already ignore the error - return - default: - } - if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok { - continue - } - r.err.SetError(err) - return - } - - select { - case r.stream <- event.(StartLiveTailResponseStreamEvent): - case <-r.done: - return - } - } -} - -type unmarshalerForStartLiveTailResponseStreamEvent struct { - metadata protocol.ResponseMetadata -} - -func (u unmarshalerForStartLiveTailResponseStreamEvent) UnmarshalerForEventName(eventType string) (eventstreamapi.Unmarshaler, error) { - switch eventType { - case "sessionStart": - return &LiveTailSessionStart{}, nil - case "sessionUpdate": - return &LiveTailSessionUpdate{}, nil - case "SessionStreamingException": - return newErrorSessionStreamingException(u.metadata).(eventstreamapi.Unmarshaler), nil - case "SessionTimeoutException": - return newErrorSessionTimeoutException(u.metadata).(eventstreamapi.Unmarshaler), nil - default: - return &StartLiveTailResponseStreamUnknownEvent{Type: eventType}, nil - } -} - -// StartLiveTailResponseStreamUnknownEvent provides a failsafe event for the -// StartLiveTailResponseStream group of events when an unknown event is received. -type StartLiveTailResponseStreamUnknownEvent struct { - Type string - Message eventstream.Message -} - -// The StartLiveTailResponseStreamUnknownEvent is and event in the StartLiveTailResponseStream -// group of events. -func (s *StartLiveTailResponseStreamUnknownEvent) eventStartLiveTailResponseStream() {} - -// MarshalEvent marshals the type into an stream event value. This method -// should only used internally within the SDK's EventStream handling. -func (e *StartLiveTailResponseStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) ( - msg eventstream.Message, err error, -) { - return e.Message.Clone(), nil -} - -// UnmarshalEvent unmarshals the EventStream Message into the StartLiveTailResponseStream value. -// This method is only used internally within the SDK's EventStream handling. -func (e *StartLiveTailResponseStreamUnknownEvent) UnmarshalEvent( - payloadUnmarshaler protocol.PayloadUnmarshaler, - msg eventstream.Message, -) error { - e.Message = msg.Clone() - return nil -} - -type StartQueryInput struct { - _ struct{} `type:"structure"` - - // The end of the time range to query. The range is inclusive, so the specified - // end time is included in the query. Specified as epoch time, the number of - // seconds since January 1, 1970, 00:00:00 UTC. - // - // EndTime is a required field - EndTime *int64 `locationName:"endTime" type:"long" required:"true"` - - // The maximum number of log events to return in the query. If the query string - // uses the fields command, only the specified fields and their values are returned. - // The default is 1000. - Limit *int64 `locationName:"limit" min:"1" type:"integer"` - - // The list of log groups to query. You can include up to 50 log groups. - // - // You can specify them by the log group name or ARN. If a log group that you're - // querying is in a source account and you're using a monitoring account, you - // must specify the ARN of the log group here. The query definition must also - // be defined in the monitoring account. - // - // If you specify an ARN, the ARN can't end with an asterisk (*). - // - // A StartQuery operation must include exactly one of the following parameters: - // logGroupName, logGroupNames, or logGroupIdentifiers. - LogGroupIdentifiers []*string `locationName:"logGroupIdentifiers" type:"list"` - - // The log group on which to perform the query. - // - // A StartQuery operation must include exactly one of the following parameters: - // logGroupName, logGroupNames, or logGroupIdentifiers. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - // The list of log groups to be queried. You can include up to 50 log groups. - // - // A StartQuery operation must include exactly one of the following parameters: - // logGroupName, logGroupNames, or logGroupIdentifiers. - LogGroupNames []*string `locationName:"logGroupNames" type:"list"` - - // The query string to use. For more information, see CloudWatch Logs Insights - // Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). - // - // QueryString is a required field - QueryString *string `locationName:"queryString" type:"string" required:"true"` - - // The beginning of the time range to query. The range is inclusive, so the - // specified start time is included in the query. Specified as epoch time, the - // number of seconds since January 1, 1970, 00:00:00 UTC. - // - // StartTime is a required field - StartTime *int64 `locationName:"startTime" type:"long" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartQueryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartQueryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StartQueryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StartQueryInput"} - if s.EndTime == nil { - invalidParams.Add(request.NewErrParamRequired("EndTime")) - } - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.QueryString == nil { - invalidParams.Add(request.NewErrParamRequired("QueryString")) - } - if s.StartTime == nil { - invalidParams.Add(request.NewErrParamRequired("StartTime")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEndTime sets the EndTime field's value. -func (s *StartQueryInput) SetEndTime(v int64) *StartQueryInput { - s.EndTime = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *StartQueryInput) SetLimit(v int64) *StartQueryInput { - s.Limit = &v - return s -} - -// SetLogGroupIdentifiers sets the LogGroupIdentifiers field's value. -func (s *StartQueryInput) SetLogGroupIdentifiers(v []*string) *StartQueryInput { - s.LogGroupIdentifiers = v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *StartQueryInput) SetLogGroupName(v string) *StartQueryInput { - s.LogGroupName = &v - return s -} - -// SetLogGroupNames sets the LogGroupNames field's value. -func (s *StartQueryInput) SetLogGroupNames(v []*string) *StartQueryInput { - s.LogGroupNames = v - return s -} - -// SetQueryString sets the QueryString field's value. -func (s *StartQueryInput) SetQueryString(v string) *StartQueryInput { - s.QueryString = &v - return s -} - -// SetStartTime sets the StartTime field's value. -func (s *StartQueryInput) SetStartTime(v int64) *StartQueryInput { - s.StartTime = &v - return s -} - -type StartQueryOutput struct { - _ struct{} `type:"structure"` - - // The unique ID of the query. - QueryId *string `locationName:"queryId" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartQueryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartQueryOutput) GoString() string { - return s.String() -} - -// SetQueryId sets the QueryId field's value. -func (s *StartQueryOutput) SetQueryId(v string) *StartQueryOutput { - s.QueryId = &v - return s -} - -type StopQueryInput struct { - _ struct{} `type:"structure"` - - // The ID number of the query to stop. To find this ID number, use DescribeQueries. - // - // QueryId is a required field - QueryId *string `locationName:"queryId" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StopQueryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StopQueryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StopQueryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StopQueryInput"} - if s.QueryId == nil { - invalidParams.Add(request.NewErrParamRequired("QueryId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetQueryId sets the QueryId field's value. -func (s *StopQueryInput) SetQueryId(v string) *StopQueryInput { - s.QueryId = &v - return s -} - -type StopQueryOutput struct { - _ struct{} `type:"structure"` - - // This is true if the query was stopped by the StopQuery operation. - Success *bool `locationName:"success" type:"boolean"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StopQueryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StopQueryOutput) GoString() string { - return s.String() -} - -// SetSuccess sets the Success field's value. -func (s *StopQueryOutput) SetSuccess(v bool) *StopQueryOutput { - s.Success = &v - return s -} - -// Represents a subscription filter. -type SubscriptionFilter struct { - _ struct{} `type:"structure"` - - // The creation time of the subscription filter, expressed as the number of - // milliseconds after Jan 1, 1970 00:00:00 UTC. - CreationTime *int64 `locationName:"creationTime" type:"long"` - - // The Amazon Resource Name (ARN) of the destination. - DestinationArn *string `locationName:"destinationArn" min:"1" type:"string"` - - // The method used to distribute log data to the destination, which can be either - // random or grouped by log stream. - Distribution *string `locationName:"distribution" type:"string" enum:"Distribution"` - - // The name of the subscription filter. - FilterName *string `locationName:"filterName" min:"1" type:"string"` - - // A symbolic description of how CloudWatch Logs should interpret the data in - // each log event. For example, a log event can contain timestamps, IP addresses, - // strings, and so on. You use the filter pattern to specify what to look for - // in the log event message. - FilterPattern *string `locationName:"filterPattern" type:"string"` - - // The name of the log group. - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string"` - - RoleArn *string `locationName:"roleArn" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SubscriptionFilter) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SubscriptionFilter) GoString() string { - return s.String() -} - -// SetCreationTime sets the CreationTime field's value. -func (s *SubscriptionFilter) SetCreationTime(v int64) *SubscriptionFilter { - s.CreationTime = &v - return s -} - -// SetDestinationArn sets the DestinationArn field's value. -func (s *SubscriptionFilter) SetDestinationArn(v string) *SubscriptionFilter { - s.DestinationArn = &v - return s -} - -// SetDistribution sets the Distribution field's value. -func (s *SubscriptionFilter) SetDistribution(v string) *SubscriptionFilter { - s.Distribution = &v - return s -} - -// SetFilterName sets the FilterName field's value. -func (s *SubscriptionFilter) SetFilterName(v string) *SubscriptionFilter { - s.FilterName = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *SubscriptionFilter) SetFilterPattern(v string) *SubscriptionFilter { - s.FilterPattern = &v - return s -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *SubscriptionFilter) SetLogGroupName(v string) *SubscriptionFilter { - s.LogGroupName = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *SubscriptionFilter) SetRoleArn(v string) *SubscriptionFilter { - s.RoleArn = &v - return s -} - -// If you are suppressing an anomaly temporariliy, this structure defines how -// long the suppression period is to be. -type SuppressionPeriod struct { - _ struct{} `type:"structure"` - - // Specifies whether the value of value is in seconds, minutes, or hours. - SuppressionUnit *string `locationName:"suppressionUnit" type:"string" enum:"SuppressionUnit"` - - // Specifies the number of seconds, minutes or hours to suppress this anomaly. - // There is no maximum. - Value *int64 `locationName:"value" type:"integer"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SuppressionPeriod) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SuppressionPeriod) GoString() string { - return s.String() -} - -// SetSuppressionUnit sets the SuppressionUnit field's value. -func (s *SuppressionPeriod) SetSuppressionUnit(v string) *SuppressionPeriod { - s.SuppressionUnit = &v - return s -} - -// SetValue sets the Value field's value. -func (s *SuppressionPeriod) SetValue(v int64) *SuppressionPeriod { - s.Value = &v - return s -} - -// Deprecated: Please use the generic tagging API model TagResourceRequest -type TagLogGroupInput struct { - _ struct{} `deprecated:"true" type:"structure"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The key-value pairs to use for the tags. - // - // Tags is a required field - Tags map[string]*string `locationName:"tags" min:"1" type:"map" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TagLogGroupInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TagLogGroupInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *TagLogGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TagLogGroupInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.Tags == nil { - invalidParams.Add(request.NewErrParamRequired("Tags")) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *TagLogGroupInput) SetLogGroupName(v string) *TagLogGroupInput { - s.LogGroupName = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *TagLogGroupInput) SetTags(v map[string]*string) *TagLogGroupInput { - s.Tags = v - return s -} - -type TagLogGroupOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TagLogGroupOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TagLogGroupOutput) GoString() string { - return s.String() -} - -type TagResourceInput struct { - _ struct{} `type:"structure"` - - // The ARN of the resource that you're adding tags to. - // - // The ARN format of a log group is arn:aws:logs:Region:account-id:log-group:log-group-name - // - // The ARN format of a destination is arn:aws:logs:Region:account-id:destination:destination-name - // - // For more information about ARN format, see CloudWatch Logs resources and - // operations (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html). - // - // ResourceArn is a required field - ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` - - // The list of key-value pairs to associate with the resource. - // - // Tags is a required field - Tags map[string]*string `locationName:"tags" min:"1" type:"map" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TagResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TagResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *TagResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) - } - if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) - } - if s.Tags == nil { - invalidParams.Add(request.NewErrParamRequired("Tags")) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetResourceArn sets the ResourceArn field's value. -func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { - s.ResourceArn = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *TagResourceInput) SetTags(v map[string]*string) *TagResourceInput { - s.Tags = v - return s -} - -type TagResourceOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TagResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TagResourceOutput) GoString() string { - return s.String() -} - -type TestMetricFilterInput struct { - _ struct{} `type:"structure"` - - // A symbolic description of how CloudWatch Logs should interpret the data in - // each log event. For example, a log event can contain timestamps, IP addresses, - // strings, and so on. You use the filter pattern to specify what to look for - // in the log event message. - // - // FilterPattern is a required field - FilterPattern *string `locationName:"filterPattern" type:"string" required:"true"` - - // The log event messages to test. - // - // LogEventMessages is a required field - LogEventMessages []*string `locationName:"logEventMessages" min:"1" type:"list" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TestMetricFilterInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TestMetricFilterInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *TestMetricFilterInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TestMetricFilterInput"} - if s.FilterPattern == nil { - invalidParams.Add(request.NewErrParamRequired("FilterPattern")) - } - if s.LogEventMessages == nil { - invalidParams.Add(request.NewErrParamRequired("LogEventMessages")) - } - if s.LogEventMessages != nil && len(s.LogEventMessages) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogEventMessages", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *TestMetricFilterInput) SetFilterPattern(v string) *TestMetricFilterInput { - s.FilterPattern = &v - return s -} - -// SetLogEventMessages sets the LogEventMessages field's value. -func (s *TestMetricFilterInput) SetLogEventMessages(v []*string) *TestMetricFilterInput { - s.LogEventMessages = v - return s -} - -type TestMetricFilterOutput struct { - _ struct{} `type:"structure"` - - // The matched events. - Matches []*MetricFilterMatchRecord `locationName:"matches" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TestMetricFilterOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TestMetricFilterOutput) GoString() string { - return s.String() -} - -// SetMatches sets the Matches field's value. -func (s *TestMetricFilterOutput) SetMatches(v []*MetricFilterMatchRecord) *TestMetricFilterOutput { - s.Matches = v - return s -} - -// The request was throttled because of quota limits. -type ThrottlingException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ThrottlingException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ThrottlingException) GoString() string { - return s.String() -} - -func newErrorThrottlingException(v protocol.ResponseMetadata) error { - return &ThrottlingException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ThrottlingException) Code() string { - return "ThrottlingException" -} - -// Message returns the exception's message. -func (s *ThrottlingException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ThrottlingException) OrigErr() error { - return nil -} - -func (s *ThrottlingException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ThrottlingException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ThrottlingException) RequestID() string { - return s.RespMetadata.RequestID -} - -// A resource can have no more than 50 tags. -type TooManyTagsException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` - - // The name of the resource. - ResourceName *string `locationName:"resourceName" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TooManyTagsException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TooManyTagsException) GoString() string { - return s.String() -} - -func newErrorTooManyTagsException(v protocol.ResponseMetadata) error { - return &TooManyTagsException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *TooManyTagsException) Code() string { - return "TooManyTagsException" -} - -// Message returns the exception's message. -func (s *TooManyTagsException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *TooManyTagsException) OrigErr() error { - return nil -} - -func (s *TooManyTagsException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *TooManyTagsException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *TooManyTagsException) RequestID() string { - return s.RespMetadata.RequestID -} - -// The most likely cause is an Amazon Web Services access key ID or secret key -// that's not valid. -type UnrecognizedClientException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UnrecognizedClientException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UnrecognizedClientException) GoString() string { - return s.String() -} - -func newErrorUnrecognizedClientException(v protocol.ResponseMetadata) error { - return &UnrecognizedClientException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *UnrecognizedClientException) Code() string { - return "UnrecognizedClientException" -} - -// Message returns the exception's message. -func (s *UnrecognizedClientException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *UnrecognizedClientException) OrigErr() error { - return nil -} - -func (s *UnrecognizedClientException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *UnrecognizedClientException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *UnrecognizedClientException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Deprecated: Please use the generic tagging API model UntagResourceRequest -type UntagLogGroupInput struct { - _ struct{} `deprecated:"true" type:"structure"` - - // The name of the log group. - // - // LogGroupName is a required field - LogGroupName *string `locationName:"logGroupName" min:"1" type:"string" required:"true"` - - // The tag keys. The corresponding tags are removed from the log group. - // - // Tags is a required field - Tags []*string `locationName:"tags" min:"1" type:"list" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UntagLogGroupInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UntagLogGroupInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UntagLogGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UntagLogGroupInput"} - if s.LogGroupName == nil { - invalidParams.Add(request.NewErrParamRequired("LogGroupName")) - } - if s.LogGroupName != nil && len(*s.LogGroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogGroupName", 1)) - } - if s.Tags == nil { - invalidParams.Add(request.NewErrParamRequired("Tags")) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLogGroupName sets the LogGroupName field's value. -func (s *UntagLogGroupInput) SetLogGroupName(v string) *UntagLogGroupInput { - s.LogGroupName = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *UntagLogGroupInput) SetTags(v []*string) *UntagLogGroupInput { - s.Tags = v - return s -} - -type UntagLogGroupOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UntagLogGroupOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UntagLogGroupOutput) GoString() string { - return s.String() -} - -type UntagResourceInput struct { - _ struct{} `type:"structure"` - - // The ARN of the CloudWatch Logs resource that you're removing tags from. - // - // The ARN format of a log group is arn:aws:logs:Region:account-id:log-group:log-group-name - // - // The ARN format of a destination is arn:aws:logs:Region:account-id:destination:destination-name - // - // For more information about ARN format, see CloudWatch Logs resources and - // operations (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html). - // - // ResourceArn is a required field - ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` - - // The list of tag keys to remove from the resource. - // - // TagKeys is a required field - TagKeys []*string `locationName:"tagKeys" type:"list" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UntagResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UntagResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UntagResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) - } - if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) - } - if s.TagKeys == nil { - invalidParams.Add(request.NewErrParamRequired("TagKeys")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetResourceArn sets the ResourceArn field's value. -func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { - s.ResourceArn = &v - return s -} - -// SetTagKeys sets the TagKeys field's value. -func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { - s.TagKeys = v - return s -} - -type UntagResourceOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UntagResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UntagResourceOutput) GoString() string { - return s.String() -} - -type UpdateAnomalyInput struct { - _ struct{} `type:"structure"` - - // The ARN of the anomaly detector that this operation is to act on. - // - // AnomalyDetectorArn is a required field - AnomalyDetectorArn *string `locationName:"anomalyDetectorArn" min:"1" type:"string" required:"true"` - - // If you are suppressing or unsuppressing an anomaly, specify its unique ID - // here. You can find anomaly IDs by using the ListAnomalies (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListAnomalies.html) - // operation. - AnomalyId *string `locationName:"anomalyId" min:"36" type:"string"` - - // If you are suppressing or unsuppressing an pattern, specify its unique ID - // here. You can find pattern IDs by using the ListAnomalies (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListAnomalies.html) - // operation. - PatternId *string `locationName:"patternId" min:"32" type:"string"` - - // If you are temporarily suppressing an anomaly or pattern, use this structure - // to specify how long the suppression is to last. - SuppressionPeriod *SuppressionPeriod `locationName:"suppressionPeriod" type:"structure"` - - // Use this to specify whether the suppression to be temporary or infinite. - // If you specify LIMITED, you must also specify a suppressionPeriod. If you - // specify INFINITE, any value for suppressionPeriod is ignored. - SuppressionType *string `locationName:"suppressionType" type:"string" enum:"SuppressionType"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UpdateAnomalyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UpdateAnomalyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateAnomalyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateAnomalyInput"} - if s.AnomalyDetectorArn == nil { - invalidParams.Add(request.NewErrParamRequired("AnomalyDetectorArn")) - } - if s.AnomalyDetectorArn != nil && len(*s.AnomalyDetectorArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AnomalyDetectorArn", 1)) - } - if s.AnomalyId != nil && len(*s.AnomalyId) < 36 { - invalidParams.Add(request.NewErrParamMinLen("AnomalyId", 36)) - } - if s.PatternId != nil && len(*s.PatternId) < 32 { - invalidParams.Add(request.NewErrParamMinLen("PatternId", 32)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnomalyDetectorArn sets the AnomalyDetectorArn field's value. -func (s *UpdateAnomalyInput) SetAnomalyDetectorArn(v string) *UpdateAnomalyInput { - s.AnomalyDetectorArn = &v - return s -} - -// SetAnomalyId sets the AnomalyId field's value. -func (s *UpdateAnomalyInput) SetAnomalyId(v string) *UpdateAnomalyInput { - s.AnomalyId = &v - return s -} - -// SetPatternId sets the PatternId field's value. -func (s *UpdateAnomalyInput) SetPatternId(v string) *UpdateAnomalyInput { - s.PatternId = &v - return s -} - -// SetSuppressionPeriod sets the SuppressionPeriod field's value. -func (s *UpdateAnomalyInput) SetSuppressionPeriod(v *SuppressionPeriod) *UpdateAnomalyInput { - s.SuppressionPeriod = v - return s -} - -// SetSuppressionType sets the SuppressionType field's value. -func (s *UpdateAnomalyInput) SetSuppressionType(v string) *UpdateAnomalyInput { - s.SuppressionType = &v - return s -} - -type UpdateAnomalyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UpdateAnomalyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UpdateAnomalyOutput) GoString() string { - return s.String() -} - -type UpdateLogAnomalyDetectorInput struct { - _ struct{} `type:"structure"` - - // The ARN of the anomaly detector that you want to update. - // - // AnomalyDetectorArn is a required field - AnomalyDetectorArn *string `locationName:"anomalyDetectorArn" min:"1" type:"string" required:"true"` - - // The number of days to use as the life cycle of anomalies. After this time, - // anomalies are automatically baselined and the anomaly detector model will - // treat new occurrences of similar event as normal. Therefore, if you do not - // correct the cause of an anomaly during this time, it will be considered normal - // going forward and will not be detected. - AnomalyVisibilityTime *int64 `locationName:"anomalyVisibilityTime" min:"7" type:"long"` - - // Use this parameter to pause or restart the anomaly detector. - // - // Enabled is a required field - Enabled *bool `locationName:"enabled" type:"boolean" required:"true"` - - // Specifies how often the anomaly detector runs and look for anomalies. Set - // this value according to the frequency that the log group receives new logs. - // For example, if the log group receives new log events every 10 minutes, then - // setting evaluationFrequency to FIFTEEN_MIN might be appropriate. - EvaluationFrequency *string `locationName:"evaluationFrequency" type:"string" enum:"EvaluationFrequency"` - - // A symbolic description of how CloudWatch Logs should interpret the data in - // each log event. For example, a log event can contain timestamps, IP addresses, - // strings, and so on. You use the filter pattern to specify what to look for - // in the log event message. - FilterPattern *string `locationName:"filterPattern" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UpdateLogAnomalyDetectorInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UpdateLogAnomalyDetectorInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateLogAnomalyDetectorInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateLogAnomalyDetectorInput"} - if s.AnomalyDetectorArn == nil { - invalidParams.Add(request.NewErrParamRequired("AnomalyDetectorArn")) - } - if s.AnomalyDetectorArn != nil && len(*s.AnomalyDetectorArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AnomalyDetectorArn", 1)) - } - if s.AnomalyVisibilityTime != nil && *s.AnomalyVisibilityTime < 7 { - invalidParams.Add(request.NewErrParamMinValue("AnomalyVisibilityTime", 7)) - } - if s.Enabled == nil { - invalidParams.Add(request.NewErrParamRequired("Enabled")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnomalyDetectorArn sets the AnomalyDetectorArn field's value. -func (s *UpdateLogAnomalyDetectorInput) SetAnomalyDetectorArn(v string) *UpdateLogAnomalyDetectorInput { - s.AnomalyDetectorArn = &v - return s -} - -// SetAnomalyVisibilityTime sets the AnomalyVisibilityTime field's value. -func (s *UpdateLogAnomalyDetectorInput) SetAnomalyVisibilityTime(v int64) *UpdateLogAnomalyDetectorInput { - s.AnomalyVisibilityTime = &v - return s -} - -// SetEnabled sets the Enabled field's value. -func (s *UpdateLogAnomalyDetectorInput) SetEnabled(v bool) *UpdateLogAnomalyDetectorInput { - s.Enabled = &v - return s -} - -// SetEvaluationFrequency sets the EvaluationFrequency field's value. -func (s *UpdateLogAnomalyDetectorInput) SetEvaluationFrequency(v string) *UpdateLogAnomalyDetectorInput { - s.EvaluationFrequency = &v - return s -} - -// SetFilterPattern sets the FilterPattern field's value. -func (s *UpdateLogAnomalyDetectorInput) SetFilterPattern(v string) *UpdateLogAnomalyDetectorInput { - s.FilterPattern = &v - return s -} - -type UpdateLogAnomalyDetectorOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UpdateLogAnomalyDetectorOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UpdateLogAnomalyDetectorOutput) GoString() string { - return s.String() -} - -// One of the parameters for the request is not valid. -type ValidationException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ValidationException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ValidationException) GoString() string { - return s.String() -} - -func newErrorValidationException(v protocol.ResponseMetadata) error { - return &ValidationException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ValidationException) Code() string { - return "ValidationException" -} - -// Message returns the exception's message. -func (s *ValidationException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ValidationException) OrigErr() error { - return nil -} - -func (s *ValidationException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ValidationException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ValidationException) RequestID() string { - return s.RespMetadata.RequestID -} - -const ( - // AnomalyDetectorStatusInitializing is a AnomalyDetectorStatus enum value - AnomalyDetectorStatusInitializing = "INITIALIZING" - - // AnomalyDetectorStatusTraining is a AnomalyDetectorStatus enum value - AnomalyDetectorStatusTraining = "TRAINING" - - // AnomalyDetectorStatusAnalyzing is a AnomalyDetectorStatus enum value - AnomalyDetectorStatusAnalyzing = "ANALYZING" - - // AnomalyDetectorStatusFailed is a AnomalyDetectorStatus enum value - AnomalyDetectorStatusFailed = "FAILED" - - // AnomalyDetectorStatusDeleted is a AnomalyDetectorStatus enum value - AnomalyDetectorStatusDeleted = "DELETED" - - // AnomalyDetectorStatusPaused is a AnomalyDetectorStatus enum value - AnomalyDetectorStatusPaused = "PAUSED" -) - -// AnomalyDetectorStatus_Values returns all elements of the AnomalyDetectorStatus enum -func AnomalyDetectorStatus_Values() []string { - return []string{ - AnomalyDetectorStatusInitializing, - AnomalyDetectorStatusTraining, - AnomalyDetectorStatusAnalyzing, - AnomalyDetectorStatusFailed, - AnomalyDetectorStatusDeleted, - AnomalyDetectorStatusPaused, - } -} - -const ( - // DataProtectionStatusActivated is a DataProtectionStatus enum value - DataProtectionStatusActivated = "ACTIVATED" - - // DataProtectionStatusDeleted is a DataProtectionStatus enum value - DataProtectionStatusDeleted = "DELETED" - - // DataProtectionStatusArchived is a DataProtectionStatus enum value - DataProtectionStatusArchived = "ARCHIVED" - - // DataProtectionStatusDisabled is a DataProtectionStatus enum value - DataProtectionStatusDisabled = "DISABLED" -) - -// DataProtectionStatus_Values returns all elements of the DataProtectionStatus enum -func DataProtectionStatus_Values() []string { - return []string{ - DataProtectionStatusActivated, - DataProtectionStatusDeleted, - DataProtectionStatusArchived, - DataProtectionStatusDisabled, - } -} - -const ( - // DeliveryDestinationTypeS3 is a DeliveryDestinationType enum value - DeliveryDestinationTypeS3 = "S3" - - // DeliveryDestinationTypeCwl is a DeliveryDestinationType enum value - DeliveryDestinationTypeCwl = "CWL" - - // DeliveryDestinationTypeFh is a DeliveryDestinationType enum value - DeliveryDestinationTypeFh = "FH" -) - -// DeliveryDestinationType_Values returns all elements of the DeliveryDestinationType enum -func DeliveryDestinationType_Values() []string { - return []string{ - DeliveryDestinationTypeS3, - DeliveryDestinationTypeCwl, - DeliveryDestinationTypeFh, - } -} - -// The method used to distribute log data to the destination, which can be either -// random or grouped by log stream. -const ( - // DistributionRandom is a Distribution enum value - DistributionRandom = "Random" - - // DistributionByLogStream is a Distribution enum value - DistributionByLogStream = "ByLogStream" -) - -// Distribution_Values returns all elements of the Distribution enum -func Distribution_Values() []string { - return []string{ - DistributionRandom, - DistributionByLogStream, - } -} - -const ( - // EvaluationFrequencyOneMin is a EvaluationFrequency enum value - EvaluationFrequencyOneMin = "ONE_MIN" - - // EvaluationFrequencyFiveMin is a EvaluationFrequency enum value - EvaluationFrequencyFiveMin = "FIVE_MIN" - - // EvaluationFrequencyTenMin is a EvaluationFrequency enum value - EvaluationFrequencyTenMin = "TEN_MIN" - - // EvaluationFrequencyFifteenMin is a EvaluationFrequency enum value - EvaluationFrequencyFifteenMin = "FIFTEEN_MIN" - - // EvaluationFrequencyThirtyMin is a EvaluationFrequency enum value - EvaluationFrequencyThirtyMin = "THIRTY_MIN" - - // EvaluationFrequencyOneHour is a EvaluationFrequency enum value - EvaluationFrequencyOneHour = "ONE_HOUR" -) - -// EvaluationFrequency_Values returns all elements of the EvaluationFrequency enum -func EvaluationFrequency_Values() []string { - return []string{ - EvaluationFrequencyOneMin, - EvaluationFrequencyFiveMin, - EvaluationFrequencyTenMin, - EvaluationFrequencyFifteenMin, - EvaluationFrequencyThirtyMin, - EvaluationFrequencyOneHour, - } -} - -const ( - // ExportTaskStatusCodeCancelled is a ExportTaskStatusCode enum value - ExportTaskStatusCodeCancelled = "CANCELLED" - - // ExportTaskStatusCodeCompleted is a ExportTaskStatusCode enum value - ExportTaskStatusCodeCompleted = "COMPLETED" - - // ExportTaskStatusCodeFailed is a ExportTaskStatusCode enum value - ExportTaskStatusCodeFailed = "FAILED" - - // ExportTaskStatusCodePending is a ExportTaskStatusCode enum value - ExportTaskStatusCodePending = "PENDING" - - // ExportTaskStatusCodePendingCancel is a ExportTaskStatusCode enum value - ExportTaskStatusCodePendingCancel = "PENDING_CANCEL" - - // ExportTaskStatusCodeRunning is a ExportTaskStatusCode enum value - ExportTaskStatusCodeRunning = "RUNNING" -) - -// ExportTaskStatusCode_Values returns all elements of the ExportTaskStatusCode enum -func ExportTaskStatusCode_Values() []string { - return []string{ - ExportTaskStatusCodeCancelled, - ExportTaskStatusCodeCompleted, - ExportTaskStatusCodeFailed, - ExportTaskStatusCodePending, - ExportTaskStatusCodePendingCancel, - ExportTaskStatusCodeRunning, - } -} - -const ( - // InheritedPropertyAccountDataProtection is a InheritedProperty enum value - InheritedPropertyAccountDataProtection = "ACCOUNT_DATA_PROTECTION" -) - -// InheritedProperty_Values returns all elements of the InheritedProperty enum -func InheritedProperty_Values() []string { - return []string{ - InheritedPropertyAccountDataProtection, - } -} - -const ( - // LogGroupClassStandard is a LogGroupClass enum value - LogGroupClassStandard = "STANDARD" - - // LogGroupClassInfrequentAccess is a LogGroupClass enum value - LogGroupClassInfrequentAccess = "INFREQUENT_ACCESS" -) - -// LogGroupClass_Values returns all elements of the LogGroupClass enum -func LogGroupClass_Values() []string { - return []string{ - LogGroupClassStandard, - LogGroupClassInfrequentAccess, - } -} - -const ( - // OrderByLogStreamName is a OrderBy enum value - OrderByLogStreamName = "LogStreamName" - - // OrderByLastEventTime is a OrderBy enum value - OrderByLastEventTime = "LastEventTime" -) - -// OrderBy_Values returns all elements of the OrderBy enum -func OrderBy_Values() []string { - return []string{ - OrderByLogStreamName, - OrderByLastEventTime, - } -} - -const ( - // OutputFormatJson is a OutputFormat enum value - OutputFormatJson = "json" - - // OutputFormatPlain is a OutputFormat enum value - OutputFormatPlain = "plain" - - // OutputFormatW3c is a OutputFormat enum value - OutputFormatW3c = "w3c" - - // OutputFormatRaw is a OutputFormat enum value - OutputFormatRaw = "raw" - - // OutputFormatParquet is a OutputFormat enum value - OutputFormatParquet = "parquet" -) - -// OutputFormat_Values returns all elements of the OutputFormat enum -func OutputFormat_Values() []string { - return []string{ - OutputFormatJson, - OutputFormatPlain, - OutputFormatW3c, - OutputFormatRaw, - OutputFormatParquet, - } -} - -const ( - // PolicyTypeDataProtectionPolicy is a PolicyType enum value - PolicyTypeDataProtectionPolicy = "DATA_PROTECTION_POLICY" - - // PolicyTypeSubscriptionFilterPolicy is a PolicyType enum value - PolicyTypeSubscriptionFilterPolicy = "SUBSCRIPTION_FILTER_POLICY" -) - -// PolicyType_Values returns all elements of the PolicyType enum -func PolicyType_Values() []string { - return []string{ - PolicyTypeDataProtectionPolicy, - PolicyTypeSubscriptionFilterPolicy, - } -} - -const ( - // QueryStatusScheduled is a QueryStatus enum value - QueryStatusScheduled = "Scheduled" - - // QueryStatusRunning is a QueryStatus enum value - QueryStatusRunning = "Running" - - // QueryStatusComplete is a QueryStatus enum value - QueryStatusComplete = "Complete" - - // QueryStatusFailed is a QueryStatus enum value - QueryStatusFailed = "Failed" - - // QueryStatusCancelled is a QueryStatus enum value - QueryStatusCancelled = "Cancelled" - - // QueryStatusTimeout is a QueryStatus enum value - QueryStatusTimeout = "Timeout" - - // QueryStatusUnknown is a QueryStatus enum value - QueryStatusUnknown = "Unknown" -) - -// QueryStatus_Values returns all elements of the QueryStatus enum -func QueryStatus_Values() []string { - return []string{ - QueryStatusScheduled, - QueryStatusRunning, - QueryStatusComplete, - QueryStatusFailed, - QueryStatusCancelled, - QueryStatusTimeout, - QueryStatusUnknown, - } -} - -const ( - // ScopeAll is a Scope enum value - ScopeAll = "ALL" -) - -// Scope_Values returns all elements of the Scope enum -func Scope_Values() []string { - return []string{ - ScopeAll, - } -} - -const ( - // StandardUnitSeconds is a StandardUnit enum value - StandardUnitSeconds = "Seconds" - - // StandardUnitMicroseconds is a StandardUnit enum value - StandardUnitMicroseconds = "Microseconds" - - // StandardUnitMilliseconds is a StandardUnit enum value - StandardUnitMilliseconds = "Milliseconds" - - // StandardUnitBytes is a StandardUnit enum value - StandardUnitBytes = "Bytes" - - // StandardUnitKilobytes is a StandardUnit enum value - StandardUnitKilobytes = "Kilobytes" - - // StandardUnitMegabytes is a StandardUnit enum value - StandardUnitMegabytes = "Megabytes" - - // StandardUnitGigabytes is a StandardUnit enum value - StandardUnitGigabytes = "Gigabytes" - - // StandardUnitTerabytes is a StandardUnit enum value - StandardUnitTerabytes = "Terabytes" - - // StandardUnitBits is a StandardUnit enum value - StandardUnitBits = "Bits" - - // StandardUnitKilobits is a StandardUnit enum value - StandardUnitKilobits = "Kilobits" - - // StandardUnitMegabits is a StandardUnit enum value - StandardUnitMegabits = "Megabits" - - // StandardUnitGigabits is a StandardUnit enum value - StandardUnitGigabits = "Gigabits" - - // StandardUnitTerabits is a StandardUnit enum value - StandardUnitTerabits = "Terabits" - - // StandardUnitPercent is a StandardUnit enum value - StandardUnitPercent = "Percent" - - // StandardUnitCount is a StandardUnit enum value - StandardUnitCount = "Count" - - // StandardUnitBytesSecond is a StandardUnit enum value - StandardUnitBytesSecond = "Bytes/Second" - - // StandardUnitKilobytesSecond is a StandardUnit enum value - StandardUnitKilobytesSecond = "Kilobytes/Second" - - // StandardUnitMegabytesSecond is a StandardUnit enum value - StandardUnitMegabytesSecond = "Megabytes/Second" - - // StandardUnitGigabytesSecond is a StandardUnit enum value - StandardUnitGigabytesSecond = "Gigabytes/Second" - - // StandardUnitTerabytesSecond is a StandardUnit enum value - StandardUnitTerabytesSecond = "Terabytes/Second" - - // StandardUnitBitsSecond is a StandardUnit enum value - StandardUnitBitsSecond = "Bits/Second" - - // StandardUnitKilobitsSecond is a StandardUnit enum value - StandardUnitKilobitsSecond = "Kilobits/Second" - - // StandardUnitMegabitsSecond is a StandardUnit enum value - StandardUnitMegabitsSecond = "Megabits/Second" - - // StandardUnitGigabitsSecond is a StandardUnit enum value - StandardUnitGigabitsSecond = "Gigabits/Second" - - // StandardUnitTerabitsSecond is a StandardUnit enum value - StandardUnitTerabitsSecond = "Terabits/Second" - - // StandardUnitCountSecond is a StandardUnit enum value - StandardUnitCountSecond = "Count/Second" - - // StandardUnitNone is a StandardUnit enum value - StandardUnitNone = "None" -) - -// StandardUnit_Values returns all elements of the StandardUnit enum -func StandardUnit_Values() []string { - return []string{ - StandardUnitSeconds, - StandardUnitMicroseconds, - StandardUnitMilliseconds, - StandardUnitBytes, - StandardUnitKilobytes, - StandardUnitMegabytes, - StandardUnitGigabytes, - StandardUnitTerabytes, - StandardUnitBits, - StandardUnitKilobits, - StandardUnitMegabits, - StandardUnitGigabits, - StandardUnitTerabits, - StandardUnitPercent, - StandardUnitCount, - StandardUnitBytesSecond, - StandardUnitKilobytesSecond, - StandardUnitMegabytesSecond, - StandardUnitGigabytesSecond, - StandardUnitTerabytesSecond, - StandardUnitBitsSecond, - StandardUnitKilobitsSecond, - StandardUnitMegabitsSecond, - StandardUnitGigabitsSecond, - StandardUnitTerabitsSecond, - StandardUnitCountSecond, - StandardUnitNone, - } -} - -const ( - // StateActive is a State enum value - StateActive = "Active" - - // StateSuppressed is a State enum value - StateSuppressed = "Suppressed" - - // StateBaseline is a State enum value - StateBaseline = "Baseline" -) - -// State_Values returns all elements of the State enum -func State_Values() []string { - return []string{ - StateActive, - StateSuppressed, - StateBaseline, - } -} - -const ( - // SuppressionStateSuppressed is a SuppressionState enum value - SuppressionStateSuppressed = "SUPPRESSED" - - // SuppressionStateUnsuppressed is a SuppressionState enum value - SuppressionStateUnsuppressed = "UNSUPPRESSED" -) - -// SuppressionState_Values returns all elements of the SuppressionState enum -func SuppressionState_Values() []string { - return []string{ - SuppressionStateSuppressed, - SuppressionStateUnsuppressed, - } -} - -const ( - // SuppressionTypeLimited is a SuppressionType enum value - SuppressionTypeLimited = "LIMITED" - - // SuppressionTypeInfinite is a SuppressionType enum value - SuppressionTypeInfinite = "INFINITE" -) - -// SuppressionType_Values returns all elements of the SuppressionType enum -func SuppressionType_Values() []string { - return []string{ - SuppressionTypeLimited, - SuppressionTypeInfinite, - } -} - -const ( - // SuppressionUnitSeconds is a SuppressionUnit enum value - SuppressionUnitSeconds = "SECONDS" - - // SuppressionUnitMinutes is a SuppressionUnit enum value - SuppressionUnitMinutes = "MINUTES" - - // SuppressionUnitHours is a SuppressionUnit enum value - SuppressionUnitHours = "HOURS" -) - -// SuppressionUnit_Values returns all elements of the SuppressionUnit enum -func SuppressionUnit_Values() []string { - return []string{ - SuppressionUnitSeconds, - SuppressionUnitMinutes, - SuppressionUnitHours, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/doc.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/doc.go deleted file mode 100644 index bd52e9d9f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/doc.go +++ /dev/null @@ -1,57 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package cloudwatchlogs provides the client and types for making API -// requests to Amazon CloudWatch Logs. -// -// You can use Amazon CloudWatch Logs to monitor, store, and access your log -// files from EC2 instances, CloudTrail, and other sources. You can then retrieve -// the associated log data from CloudWatch Logs using the CloudWatch console. -// Alternatively, you can use CloudWatch Logs commands in the Amazon Web Services -// CLI, CloudWatch Logs API, or CloudWatch Logs SDK. -// -// You can use CloudWatch Logs to: -// -// - Monitor logs from EC2 instances in real time: You can use CloudWatch -// Logs to monitor applications and systems using log data. For example, -// CloudWatch Logs can track the number of errors that occur in your application -// logs. Then, it can send you a notification whenever the rate of errors -// exceeds a threshold that you specify. CloudWatch Logs uses your log data -// for monitoring so no code changes are required. For example, you can monitor -// application logs for specific literal terms (such as "NullReferenceException"). -// You can also count the number of occurrences of a literal term at a particular -// position in log data (such as "404" status codes in an Apache access log). -// When the term you are searching for is found, CloudWatch Logs reports -// the data to a CloudWatch metric that you specify. -// -// - Monitor CloudTrail logged events: You can create alarms in CloudWatch -// and receive notifications of particular API activity as captured by CloudTrail. -// You can use the notification to perform troubleshooting. -// -// - Archive log data: You can use CloudWatch Logs to store your log data -// in highly durable storage. You can change the log retention setting so -// that any log events earlier than this setting are automatically deleted. -// The CloudWatch Logs agent helps to quickly send both rotated and non-rotated -// log data off of a host and into the log service. You can then access the -// raw log data when you need it. -// -// See https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28 for more information on this service. -// -// See cloudwatchlogs package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchlogs/ -// -// # Using the Client -// -// To contact Amazon CloudWatch Logs with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the Amazon CloudWatch Logs client CloudWatchLogs for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchlogs/#New -package cloudwatchlogs diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/errors.go deleted file mode 100644 index 4c4ff1b55..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/errors.go +++ /dev/null @@ -1,159 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package cloudwatchlogs - -import ( - "github.com/aws/aws-sdk-go/private/protocol" -) - -const ( - - // ErrCodeAccessDeniedException for service response error code - // "AccessDeniedException". - // - // You don't have sufficient permissions to perform this action. - ErrCodeAccessDeniedException = "AccessDeniedException" - - // ErrCodeConflictException for service response error code - // "ConflictException". - // - // This operation attempted to create a resource that already exists. - ErrCodeConflictException = "ConflictException" - - // ErrCodeDataAlreadyAcceptedException for service response error code - // "DataAlreadyAcceptedException". - // - // The event was already logged. - // - // PutLogEvents actions are now always accepted and never return DataAlreadyAcceptedException - // regardless of whether a given batch of log events has already been accepted. - ErrCodeDataAlreadyAcceptedException = "DataAlreadyAcceptedException" - - // ErrCodeInvalidOperationException for service response error code - // "InvalidOperationException". - // - // The operation is not valid on the specified resource. - ErrCodeInvalidOperationException = "InvalidOperationException" - - // ErrCodeInvalidParameterException for service response error code - // "InvalidParameterException". - // - // A parameter is specified incorrectly. - ErrCodeInvalidParameterException = "InvalidParameterException" - - // ErrCodeInvalidSequenceTokenException for service response error code - // "InvalidSequenceTokenException". - // - // The sequence token is not valid. You can get the correct sequence token in - // the expectedSequenceToken field in the InvalidSequenceTokenException message. - // - // PutLogEvents actions are now always accepted and never return InvalidSequenceTokenException - // regardless of receiving an invalid sequence token. - ErrCodeInvalidSequenceTokenException = "InvalidSequenceTokenException" - - // ErrCodeLimitExceededException for service response error code - // "LimitExceededException". - // - // You have reached the maximum number of resources that can be created. - ErrCodeLimitExceededException = "LimitExceededException" - - // ErrCodeMalformedQueryException for service response error code - // "MalformedQueryException". - // - // The query string is not valid. Details about this error are displayed in - // a QueryCompileError object. For more information, see QueryCompileError (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_QueryCompileError.html). - // - // For more information about valid query syntax, see CloudWatch Logs Insights - // Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). - ErrCodeMalformedQueryException = "MalformedQueryException" - - // ErrCodeOperationAbortedException for service response error code - // "OperationAbortedException". - // - // Multiple concurrent requests to update the same resource were in conflict. - ErrCodeOperationAbortedException = "OperationAbortedException" - - // ErrCodeResourceAlreadyExistsException for service response error code - // "ResourceAlreadyExistsException". - // - // The specified resource already exists. - ErrCodeResourceAlreadyExistsException = "ResourceAlreadyExistsException" - - // ErrCodeResourceNotFoundException for service response error code - // "ResourceNotFoundException". - // - // The specified resource does not exist. - ErrCodeResourceNotFoundException = "ResourceNotFoundException" - - // ErrCodeServiceQuotaExceededException for service response error code - // "ServiceQuotaExceededException". - // - // This request exceeds a service quota. - ErrCodeServiceQuotaExceededException = "ServiceQuotaExceededException" - - // ErrCodeServiceUnavailableException for service response error code - // "ServiceUnavailableException". - // - // The service cannot complete the request. - ErrCodeServiceUnavailableException = "ServiceUnavailableException" - - // ErrCodeSessionStreamingException for service response error code - // "SessionStreamingException". - // - // his exception is returned if an unknown error occurs during a Live Tail session. - ErrCodeSessionStreamingException = "SessionStreamingException" - - // ErrCodeSessionTimeoutException for service response error code - // "SessionTimeoutException". - // - // This exception is returned in a Live Tail stream when the Live Tail session - // times out. Live Tail sessions time out after three hours. - ErrCodeSessionTimeoutException = "SessionTimeoutException" - - // ErrCodeThrottlingException for service response error code - // "ThrottlingException". - // - // The request was throttled because of quota limits. - ErrCodeThrottlingException = "ThrottlingException" - - // ErrCodeTooManyTagsException for service response error code - // "TooManyTagsException". - // - // A resource can have no more than 50 tags. - ErrCodeTooManyTagsException = "TooManyTagsException" - - // ErrCodeUnrecognizedClientException for service response error code - // "UnrecognizedClientException". - // - // The most likely cause is an Amazon Web Services access key ID or secret key - // that's not valid. - ErrCodeUnrecognizedClientException = "UnrecognizedClientException" - - // ErrCodeValidationException for service response error code - // "ValidationException". - // - // One of the parameters for the request is not valid. - ErrCodeValidationException = "ValidationException" -) - -var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ - "AccessDeniedException": newErrorAccessDeniedException, - "ConflictException": newErrorConflictException, - "DataAlreadyAcceptedException": newErrorDataAlreadyAcceptedException, - "InvalidOperationException": newErrorInvalidOperationException, - "InvalidParameterException": newErrorInvalidParameterException, - "InvalidSequenceTokenException": newErrorInvalidSequenceTokenException, - "LimitExceededException": newErrorLimitExceededException, - "MalformedQueryException": newErrorMalformedQueryException, - "OperationAbortedException": newErrorOperationAbortedException, - "ResourceAlreadyExistsException": newErrorResourceAlreadyExistsException, - "ResourceNotFoundException": newErrorResourceNotFoundException, - "ServiceQuotaExceededException": newErrorServiceQuotaExceededException, - "ServiceUnavailableException": newErrorServiceUnavailableException, - "SessionStreamingException": newErrorSessionStreamingException, - "SessionTimeoutException": newErrorSessionTimeoutException, - "ThrottlingException": newErrorThrottlingException, - "TooManyTagsException": newErrorTooManyTagsException, - "UnrecognizedClientException": newErrorUnrecognizedClientException, - "ValidationException": newErrorValidationException, -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go b/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go deleted file mode 100644 index d6d00aeb4..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudwatchlogs/service.go +++ /dev/null @@ -1,112 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package cloudwatchlogs - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" -) - -// CloudWatchLogs provides the API operation methods for making requests to -// Amazon CloudWatch Logs. See this package's package overview docs -// for details on the service. -// -// CloudWatchLogs methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type CloudWatchLogs struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "logs" // Name of service. - EndpointsID = ServiceName // ID to lookup a service endpoint with. - ServiceID = "CloudWatch Logs" // ServiceID is a unique identifier of a specific service. -) - -// New creates a new instance of the CloudWatchLogs client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// -// mySession := session.Must(session.NewSession()) -// -// // Create a CloudWatchLogs client from just a session. -// svc := cloudwatchlogs.New(mySession) -// -// // Create a CloudWatchLogs client with additional configuration -// svc := cloudwatchlogs.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *CloudWatchLogs { - c := p.ClientConfig(EndpointsID, cfgs...) - if c.SigningNameDerived || len(c.SigningName) == 0 { - c.SigningName = EndpointsID - // No Fallback - } - return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *CloudWatchLogs { - svc := &CloudWatchLogs{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - ServiceID: ServiceID, - SigningName: signingName, - SigningRegion: signingRegion, - PartitionID: partitionID, - Endpoint: endpoint, - APIVersion: "2014-03-28", - ResolvedRegion: resolvedRegion, - JSONVersion: "1.1", - TargetPrefix: "Logs_20140328", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed( - protocol.NewUnmarshalErrorHandler(jsonrpc.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), - ) - - svc.Handlers.BuildStream.PushBackNamed(jsonrpc.BuildHandler) - svc.Handlers.UnmarshalStream.PushBackNamed(jsonrpc.UnmarshalHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a CloudWatchLogs operation and runs any -// custom request initialization. -func (c *CloudWatchLogs) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sso/api.go b/vendor/github.com/aws/aws-sdk-go/service/sso/api.go deleted file mode 100644 index b8f590f71..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sso/api.go +++ /dev/null @@ -1,1367 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sso - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/restjson" -) - -const opGetRoleCredentials = "GetRoleCredentials" - -// GetRoleCredentialsRequest generates a "aws/request.Request" representing the -// client's request for the GetRoleCredentials operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetRoleCredentials for more information on using the GetRoleCredentials -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetRoleCredentialsRequest method. -// req, resp := client.GetRoleCredentialsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/GetRoleCredentials -func (c *SSO) GetRoleCredentialsRequest(input *GetRoleCredentialsInput) (req *request.Request, output *GetRoleCredentialsOutput) { - op := &request.Operation{ - Name: opGetRoleCredentials, - HTTPMethod: "GET", - HTTPPath: "/federation/credentials", - } - - if input == nil { - input = &GetRoleCredentialsInput{} - } - - output = &GetRoleCredentialsOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - return -} - -// GetRoleCredentials API operation for AWS Single Sign-On. -// -// Returns the STS short-term credentials for a given role name that is assigned -// to the user. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Single Sign-On's -// API operation GetRoleCredentials for usage and error information. -// -// Returned Error Types: -// -// - InvalidRequestException -// Indicates that a problem occurred with the input to the request. For example, -// a required parameter might be missing or out of range. -// -// - UnauthorizedException -// Indicates that the request is not authorized. This can happen due to an invalid -// access token in the request. -// -// - TooManyRequestsException -// Indicates that the request is being made too frequently and is more than -// what the server can handle. -// -// - ResourceNotFoundException -// The specified resource doesn't exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/GetRoleCredentials -func (c *SSO) GetRoleCredentials(input *GetRoleCredentialsInput) (*GetRoleCredentialsOutput, error) { - req, out := c.GetRoleCredentialsRequest(input) - return out, req.Send() -} - -// GetRoleCredentialsWithContext is the same as GetRoleCredentials with the addition of -// the ability to pass a context and additional request options. -// -// See GetRoleCredentials for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSO) GetRoleCredentialsWithContext(ctx aws.Context, input *GetRoleCredentialsInput, opts ...request.Option) (*GetRoleCredentialsOutput, error) { - req, out := c.GetRoleCredentialsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListAccountRoles = "ListAccountRoles" - -// ListAccountRolesRequest generates a "aws/request.Request" representing the -// client's request for the ListAccountRoles operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListAccountRoles for more information on using the ListAccountRoles -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the ListAccountRolesRequest method. -// req, resp := client.ListAccountRolesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccountRoles -func (c *SSO) ListAccountRolesRequest(input *ListAccountRolesInput) (req *request.Request, output *ListAccountRolesOutput) { - op := &request.Operation{ - Name: opListAccountRoles, - HTTPMethod: "GET", - HTTPPath: "/assignment/roles", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "maxResults", - TruncationToken: "", - }, - } - - if input == nil { - input = &ListAccountRolesInput{} - } - - output = &ListAccountRolesOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - return -} - -// ListAccountRoles API operation for AWS Single Sign-On. -// -// Lists all roles that are assigned to the user for a given AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Single Sign-On's -// API operation ListAccountRoles for usage and error information. -// -// Returned Error Types: -// -// - InvalidRequestException -// Indicates that a problem occurred with the input to the request. For example, -// a required parameter might be missing or out of range. -// -// - UnauthorizedException -// Indicates that the request is not authorized. This can happen due to an invalid -// access token in the request. -// -// - TooManyRequestsException -// Indicates that the request is being made too frequently and is more than -// what the server can handle. -// -// - ResourceNotFoundException -// The specified resource doesn't exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccountRoles -func (c *SSO) ListAccountRoles(input *ListAccountRolesInput) (*ListAccountRolesOutput, error) { - req, out := c.ListAccountRolesRequest(input) - return out, req.Send() -} - -// ListAccountRolesWithContext is the same as ListAccountRoles with the addition of -// the ability to pass a context and additional request options. -// -// See ListAccountRoles for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSO) ListAccountRolesWithContext(ctx aws.Context, input *ListAccountRolesInput, opts ...request.Option) (*ListAccountRolesOutput, error) { - req, out := c.ListAccountRolesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListAccountRolesPages iterates over the pages of a ListAccountRoles operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListAccountRoles method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListAccountRoles operation. -// pageNum := 0 -// err := client.ListAccountRolesPages(params, -// func(page *sso.ListAccountRolesOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *SSO) ListAccountRolesPages(input *ListAccountRolesInput, fn func(*ListAccountRolesOutput, bool) bool) error { - return c.ListAccountRolesPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListAccountRolesPagesWithContext same as ListAccountRolesPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSO) ListAccountRolesPagesWithContext(ctx aws.Context, input *ListAccountRolesInput, fn func(*ListAccountRolesOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListAccountRolesInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListAccountRolesRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListAccountRolesOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListAccounts = "ListAccounts" - -// ListAccountsRequest generates a "aws/request.Request" representing the -// client's request for the ListAccounts operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListAccounts for more information on using the ListAccounts -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the ListAccountsRequest method. -// req, resp := client.ListAccountsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccounts -func (c *SSO) ListAccountsRequest(input *ListAccountsInput) (req *request.Request, output *ListAccountsOutput) { - op := &request.Operation{ - Name: opListAccounts, - HTTPMethod: "GET", - HTTPPath: "/assignment/accounts", - Paginator: &request.Paginator{ - InputTokens: []string{"nextToken"}, - OutputTokens: []string{"nextToken"}, - LimitToken: "maxResults", - TruncationToken: "", - }, - } - - if input == nil { - input = &ListAccountsInput{} - } - - output = &ListAccountsOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - return -} - -// ListAccounts API operation for AWS Single Sign-On. -// -// Lists all AWS accounts assigned to the user. These AWS accounts are assigned -// by the administrator of the account. For more information, see Assign User -// Access (https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#assignusers) -// in the IAM Identity Center User Guide. This operation returns a paginated -// response. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Single Sign-On's -// API operation ListAccounts for usage and error information. -// -// Returned Error Types: -// -// - InvalidRequestException -// Indicates that a problem occurred with the input to the request. For example, -// a required parameter might be missing or out of range. -// -// - UnauthorizedException -// Indicates that the request is not authorized. This can happen due to an invalid -// access token in the request. -// -// - TooManyRequestsException -// Indicates that the request is being made too frequently and is more than -// what the server can handle. -// -// - ResourceNotFoundException -// The specified resource doesn't exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/ListAccounts -func (c *SSO) ListAccounts(input *ListAccountsInput) (*ListAccountsOutput, error) { - req, out := c.ListAccountsRequest(input) - return out, req.Send() -} - -// ListAccountsWithContext is the same as ListAccounts with the addition of -// the ability to pass a context and additional request options. -// -// See ListAccounts for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSO) ListAccountsWithContext(ctx aws.Context, input *ListAccountsInput, opts ...request.Option) (*ListAccountsOutput, error) { - req, out := c.ListAccountsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListAccountsPages iterates over the pages of a ListAccounts operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListAccounts method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListAccounts operation. -// pageNum := 0 -// err := client.ListAccountsPages(params, -// func(page *sso.ListAccountsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -func (c *SSO) ListAccountsPages(input *ListAccountsInput, fn func(*ListAccountsOutput, bool) bool) error { - return c.ListAccountsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListAccountsPagesWithContext same as ListAccountsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSO) ListAccountsPagesWithContext(ctx aws.Context, input *ListAccountsInput, fn func(*ListAccountsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListAccountsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListAccountsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListAccountsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opLogout = "Logout" - -// LogoutRequest generates a "aws/request.Request" representing the -// client's request for the Logout operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See Logout for more information on using the Logout -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the LogoutRequest method. -// req, resp := client.LogoutRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/Logout -func (c *SSO) LogoutRequest(input *LogoutInput) (req *request.Request, output *LogoutOutput) { - op := &request.Operation{ - Name: opLogout, - HTTPMethod: "POST", - HTTPPath: "/logout", - } - - if input == nil { - input = &LogoutInput{} - } - - output = &LogoutOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - return -} - -// Logout API operation for AWS Single Sign-On. -// -// Removes the locally stored SSO tokens from the client-side cache and sends -// an API call to the IAM Identity Center service to invalidate the corresponding -// server-side IAM Identity Center sign in session. -// -// If a user uses IAM Identity Center to access the AWS CLI, the user’s IAM -// Identity Center sign in session is used to obtain an IAM session, as specified -// in the corresponding IAM Identity Center permission set. More specifically, -// IAM Identity Center assumes an IAM role in the target account on behalf of -// the user, and the corresponding temporary AWS credentials are returned to -// the client. -// -// After user logout, any existing IAM role sessions that were created by using -// IAM Identity Center permission sets continue based on the duration configured -// in the permission set. For more information, see User authentications (https://docs.aws.amazon.com/singlesignon/latest/userguide/authconcept.html) -// in the IAM Identity Center User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Single Sign-On's -// API operation Logout for usage and error information. -// -// Returned Error Types: -// -// - InvalidRequestException -// Indicates that a problem occurred with the input to the request. For example, -// a required parameter might be missing or out of range. -// -// - UnauthorizedException -// Indicates that the request is not authorized. This can happen due to an invalid -// access token in the request. -// -// - TooManyRequestsException -// Indicates that the request is being made too frequently and is more than -// what the server can handle. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10/Logout -func (c *SSO) Logout(input *LogoutInput) (*LogoutOutput, error) { - req, out := c.LogoutRequest(input) - return out, req.Send() -} - -// LogoutWithContext is the same as Logout with the addition of -// the ability to pass a context and additional request options. -// -// See Logout for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSO) LogoutWithContext(ctx aws.Context, input *LogoutInput, opts ...request.Option) (*LogoutOutput, error) { - req, out := c.LogoutRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// Provides information about your AWS account. -type AccountInfo struct { - _ struct{} `type:"structure"` - - // The identifier of the AWS account that is assigned to the user. - AccountId *string `locationName:"accountId" type:"string"` - - // The display name of the AWS account that is assigned to the user. - AccountName *string `locationName:"accountName" type:"string"` - - // The email address of the AWS account that is assigned to the user. - EmailAddress *string `locationName:"emailAddress" min:"1" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AccountInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AccountInfo) GoString() string { - return s.String() -} - -// SetAccountId sets the AccountId field's value. -func (s *AccountInfo) SetAccountId(v string) *AccountInfo { - s.AccountId = &v - return s -} - -// SetAccountName sets the AccountName field's value. -func (s *AccountInfo) SetAccountName(v string) *AccountInfo { - s.AccountName = &v - return s -} - -// SetEmailAddress sets the EmailAddress field's value. -func (s *AccountInfo) SetEmailAddress(v string) *AccountInfo { - s.EmailAddress = &v - return s -} - -type GetRoleCredentialsInput struct { - _ struct{} `type:"structure" nopayload:"true"` - - // The token issued by the CreateToken API call. For more information, see CreateToken - // (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // AccessToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by GetRoleCredentialsInput's - // String and GoString methods. - // - // AccessToken is a required field - AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"` - - // The identifier for the AWS account that is assigned to the user. - // - // AccountId is a required field - AccountId *string `location:"querystring" locationName:"account_id" type:"string" required:"true"` - - // The friendly name of the role that is assigned to the user. - // - // RoleName is a required field - RoleName *string `location:"querystring" locationName:"role_name" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetRoleCredentialsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetRoleCredentialsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetRoleCredentialsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetRoleCredentialsInput"} - if s.AccessToken == nil { - invalidParams.Add(request.NewErrParamRequired("AccessToken")) - } - if s.AccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AccountId")) - } - if s.RoleName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccessToken sets the AccessToken field's value. -func (s *GetRoleCredentialsInput) SetAccessToken(v string) *GetRoleCredentialsInput { - s.AccessToken = &v - return s -} - -// SetAccountId sets the AccountId field's value. -func (s *GetRoleCredentialsInput) SetAccountId(v string) *GetRoleCredentialsInput { - s.AccountId = &v - return s -} - -// SetRoleName sets the RoleName field's value. -func (s *GetRoleCredentialsInput) SetRoleName(v string) *GetRoleCredentialsInput { - s.RoleName = &v - return s -} - -type GetRoleCredentialsOutput struct { - _ struct{} `type:"structure"` - - // The credentials for the role that is assigned to the user. - RoleCredentials *RoleCredentials `locationName:"roleCredentials" type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetRoleCredentialsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetRoleCredentialsOutput) GoString() string { - return s.String() -} - -// SetRoleCredentials sets the RoleCredentials field's value. -func (s *GetRoleCredentialsOutput) SetRoleCredentials(v *RoleCredentials) *GetRoleCredentialsOutput { - s.RoleCredentials = v - return s -} - -// Indicates that a problem occurred with the input to the request. For example, -// a required parameter might be missing or out of range. -type InvalidRequestException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidRequestException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidRequestException) GoString() string { - return s.String() -} - -func newErrorInvalidRequestException(v protocol.ResponseMetadata) error { - return &InvalidRequestException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidRequestException) Code() string { - return "InvalidRequestException" -} - -// Message returns the exception's message. -func (s *InvalidRequestException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidRequestException) OrigErr() error { - return nil -} - -func (s *InvalidRequestException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidRequestException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidRequestException) RequestID() string { - return s.RespMetadata.RequestID -} - -type ListAccountRolesInput struct { - _ struct{} `type:"structure" nopayload:"true"` - - // The token issued by the CreateToken API call. For more information, see CreateToken - // (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // AccessToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by ListAccountRolesInput's - // String and GoString methods. - // - // AccessToken is a required field - AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"` - - // The identifier for the AWS account that is assigned to the user. - // - // AccountId is a required field - AccountId *string `location:"querystring" locationName:"account_id" type:"string" required:"true"` - - // The number of items that clients can request per page. - MaxResults *int64 `location:"querystring" locationName:"max_result" min:"1" type:"integer"` - - // The page token from the previous response output when you request subsequent - // pages. - NextToken *string `location:"querystring" locationName:"next_token" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAccountRolesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAccountRolesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListAccountRolesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListAccountRolesInput"} - if s.AccessToken == nil { - invalidParams.Add(request.NewErrParamRequired("AccessToken")) - } - if s.AccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AccountId")) - } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccessToken sets the AccessToken field's value. -func (s *ListAccountRolesInput) SetAccessToken(v string) *ListAccountRolesInput { - s.AccessToken = &v - return s -} - -// SetAccountId sets the AccountId field's value. -func (s *ListAccountRolesInput) SetAccountId(v string) *ListAccountRolesInput { - s.AccountId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListAccountRolesInput) SetMaxResults(v int64) *ListAccountRolesInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListAccountRolesInput) SetNextToken(v string) *ListAccountRolesInput { - s.NextToken = &v - return s -} - -type ListAccountRolesOutput struct { - _ struct{} `type:"structure"` - - // The page token client that is used to retrieve the list of accounts. - NextToken *string `locationName:"nextToken" type:"string"` - - // A paginated response with the list of roles and the next token if more results - // are available. - RoleList []*RoleInfo `locationName:"roleList" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAccountRolesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAccountRolesOutput) GoString() string { - return s.String() -} - -// SetNextToken sets the NextToken field's value. -func (s *ListAccountRolesOutput) SetNextToken(v string) *ListAccountRolesOutput { - s.NextToken = &v - return s -} - -// SetRoleList sets the RoleList field's value. -func (s *ListAccountRolesOutput) SetRoleList(v []*RoleInfo) *ListAccountRolesOutput { - s.RoleList = v - return s -} - -type ListAccountsInput struct { - _ struct{} `type:"structure" nopayload:"true"` - - // The token issued by the CreateToken API call. For more information, see CreateToken - // (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // AccessToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by ListAccountsInput's - // String and GoString methods. - // - // AccessToken is a required field - AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"` - - // This is the number of items clients can request per page. - MaxResults *int64 `location:"querystring" locationName:"max_result" min:"1" type:"integer"` - - // (Optional) When requesting subsequent pages, this is the page token from - // the previous response output. - NextToken *string `location:"querystring" locationName:"next_token" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAccountsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAccountsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListAccountsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListAccountsInput"} - if s.AccessToken == nil { - invalidParams.Add(request.NewErrParamRequired("AccessToken")) - } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccessToken sets the AccessToken field's value. -func (s *ListAccountsInput) SetAccessToken(v string) *ListAccountsInput { - s.AccessToken = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListAccountsInput) SetMaxResults(v int64) *ListAccountsInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListAccountsInput) SetNextToken(v string) *ListAccountsInput { - s.NextToken = &v - return s -} - -type ListAccountsOutput struct { - _ struct{} `type:"structure"` - - // A paginated response with the list of account information and the next token - // if more results are available. - AccountList []*AccountInfo `locationName:"accountList" type:"list"` - - // The page token client that is used to retrieve the list of accounts. - NextToken *string `locationName:"nextToken" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAccountsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ListAccountsOutput) GoString() string { - return s.String() -} - -// SetAccountList sets the AccountList field's value. -func (s *ListAccountsOutput) SetAccountList(v []*AccountInfo) *ListAccountsOutput { - s.AccountList = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListAccountsOutput) SetNextToken(v string) *ListAccountsOutput { - s.NextToken = &v - return s -} - -type LogoutInput struct { - _ struct{} `type:"structure" nopayload:"true"` - - // The token issued by the CreateToken API call. For more information, see CreateToken - // (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // AccessToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by LogoutInput's - // String and GoString methods. - // - // AccessToken is a required field - AccessToken *string `location:"header" locationName:"x-amz-sso_bearer_token" type:"string" required:"true" sensitive:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogoutInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogoutInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *LogoutInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LogoutInput"} - if s.AccessToken == nil { - invalidParams.Add(request.NewErrParamRequired("AccessToken")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccessToken sets the AccessToken field's value. -func (s *LogoutInput) SetAccessToken(v string) *LogoutInput { - s.AccessToken = &v - return s -} - -type LogoutOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogoutOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s LogoutOutput) GoString() string { - return s.String() -} - -// The specified resource doesn't exist. -type ResourceNotFoundException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResourceNotFoundException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ResourceNotFoundException) GoString() string { - return s.String() -} - -func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { - return &ResourceNotFoundException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ResourceNotFoundException) Code() string { - return "ResourceNotFoundException" -} - -// Message returns the exception's message. -func (s *ResourceNotFoundException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceNotFoundException) OrigErr() error { - return nil -} - -func (s *ResourceNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceNotFoundException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ResourceNotFoundException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Provides information about the role credentials that are assigned to the -// user. -type RoleCredentials struct { - _ struct{} `type:"structure"` - - // The identifier used for the temporary security credentials. For more information, - // see Using Temporary Security Credentials to Request Access to AWS Resources - // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - AccessKeyId *string `locationName:"accessKeyId" type:"string"` - - // The date on which temporary security credentials expire. - Expiration *int64 `locationName:"expiration" type:"long"` - - // The key that is used to sign the request. For more information, see Using - // Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - // - // SecretAccessKey is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by RoleCredentials's - // String and GoString methods. - SecretAccessKey *string `locationName:"secretAccessKey" type:"string" sensitive:"true"` - - // The token used for temporary credentials. For more information, see Using - // Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - // - // SessionToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by RoleCredentials's - // String and GoString methods. - SessionToken *string `locationName:"sessionToken" type:"string" sensitive:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RoleCredentials) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RoleCredentials) GoString() string { - return s.String() -} - -// SetAccessKeyId sets the AccessKeyId field's value. -func (s *RoleCredentials) SetAccessKeyId(v string) *RoleCredentials { - s.AccessKeyId = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *RoleCredentials) SetExpiration(v int64) *RoleCredentials { - s.Expiration = &v - return s -} - -// SetSecretAccessKey sets the SecretAccessKey field's value. -func (s *RoleCredentials) SetSecretAccessKey(v string) *RoleCredentials { - s.SecretAccessKey = &v - return s -} - -// SetSessionToken sets the SessionToken field's value. -func (s *RoleCredentials) SetSessionToken(v string) *RoleCredentials { - s.SessionToken = &v - return s -} - -// Provides information about the role that is assigned to the user. -type RoleInfo struct { - _ struct{} `type:"structure"` - - // The identifier of the AWS account assigned to the user. - AccountId *string `locationName:"accountId" type:"string"` - - // The friendly name of the role that is assigned to the user. - RoleName *string `locationName:"roleName" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RoleInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RoleInfo) GoString() string { - return s.String() -} - -// SetAccountId sets the AccountId field's value. -func (s *RoleInfo) SetAccountId(v string) *RoleInfo { - s.AccountId = &v - return s -} - -// SetRoleName sets the RoleName field's value. -func (s *RoleInfo) SetRoleName(v string) *RoleInfo { - s.RoleName = &v - return s -} - -// Indicates that the request is being made too frequently and is more than -// what the server can handle. -type TooManyRequestsException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TooManyRequestsException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s TooManyRequestsException) GoString() string { - return s.String() -} - -func newErrorTooManyRequestsException(v protocol.ResponseMetadata) error { - return &TooManyRequestsException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *TooManyRequestsException) Code() string { - return "TooManyRequestsException" -} - -// Message returns the exception's message. -func (s *TooManyRequestsException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *TooManyRequestsException) OrigErr() error { - return nil -} - -func (s *TooManyRequestsException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *TooManyRequestsException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *TooManyRequestsException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that the request is not authorized. This can happen due to an invalid -// access token in the request. -type UnauthorizedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UnauthorizedException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UnauthorizedException) GoString() string { - return s.String() -} - -func newErrorUnauthorizedException(v protocol.ResponseMetadata) error { - return &UnauthorizedException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *UnauthorizedException) Code() string { - return "UnauthorizedException" -} - -// Message returns the exception's message. -func (s *UnauthorizedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *UnauthorizedException) OrigErr() error { - return nil -} - -func (s *UnauthorizedException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *UnauthorizedException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *UnauthorizedException) RequestID() string { - return s.RespMetadata.RequestID -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sso/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sso/doc.go deleted file mode 100644 index 15e61a322..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sso/doc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package sso provides the client and types for making API -// requests to AWS Single Sign-On. -// -// AWS IAM Identity Center (successor to AWS Single Sign-On) Portal is a web -// service that makes it easy for you to assign user access to IAM Identity -// Center resources such as the AWS access portal. Users can get AWS account -// applications and roles assigned to them and get federated into the application. -// -// Although AWS Single Sign-On was renamed, the sso and identitystore API namespaces -// will continue to retain their original name for backward compatibility purposes. -// For more information, see IAM Identity Center rename (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html#renamed). -// -// This reference guide describes the IAM Identity Center Portal operations -// that you can call programatically and includes detailed information on data -// types and errors. -// -// AWS provides SDKs that consist of libraries and sample code for various programming -// languages and platforms, such as Java, Ruby, .Net, iOS, or Android. The SDKs -// provide a convenient way to create programmatic access to IAM Identity Center -// and other AWS services. For more information about the AWS SDKs, including -// how to download and install them, see Tools for Amazon Web Services (http://aws.amazon.com/tools/). -// -// See https://docs.aws.amazon.com/goto/WebAPI/sso-2019-06-10 for more information on this service. -// -// See sso package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sso/ -// -// # Using the Client -// -// To contact AWS Single Sign-On with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the AWS Single Sign-On client SSO for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sso/#New -package sso diff --git a/vendor/github.com/aws/aws-sdk-go/service/sso/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sso/errors.go deleted file mode 100644 index 77a6792e3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sso/errors.go +++ /dev/null @@ -1,44 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sso - -import ( - "github.com/aws/aws-sdk-go/private/protocol" -) - -const ( - - // ErrCodeInvalidRequestException for service response error code - // "InvalidRequestException". - // - // Indicates that a problem occurred with the input to the request. For example, - // a required parameter might be missing or out of range. - ErrCodeInvalidRequestException = "InvalidRequestException" - - // ErrCodeResourceNotFoundException for service response error code - // "ResourceNotFoundException". - // - // The specified resource doesn't exist. - ErrCodeResourceNotFoundException = "ResourceNotFoundException" - - // ErrCodeTooManyRequestsException for service response error code - // "TooManyRequestsException". - // - // Indicates that the request is being made too frequently and is more than - // what the server can handle. - ErrCodeTooManyRequestsException = "TooManyRequestsException" - - // ErrCodeUnauthorizedException for service response error code - // "UnauthorizedException". - // - // Indicates that the request is not authorized. This can happen due to an invalid - // access token in the request. - ErrCodeUnauthorizedException = "UnauthorizedException" -) - -var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ - "InvalidRequestException": newErrorInvalidRequestException, - "ResourceNotFoundException": newErrorResourceNotFoundException, - "TooManyRequestsException": newErrorTooManyRequestsException, - "UnauthorizedException": newErrorUnauthorizedException, -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sso/service.go b/vendor/github.com/aws/aws-sdk-go/service/sso/service.go deleted file mode 100644 index 7094cfe41..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sso/service.go +++ /dev/null @@ -1,106 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sso - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/restjson" -) - -// SSO provides the API operation methods for making requests to -// AWS Single Sign-On. See this package's package overview docs -// for details on the service. -// -// SSO methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type SSO struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "SSO" // Name of service. - EndpointsID = "portal.sso" // ID to lookup a service endpoint with. - ServiceID = "SSO" // ServiceID is a unique identifier of a specific service. -) - -// New creates a new instance of the SSO client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// -// mySession := session.Must(session.NewSession()) -// -// // Create a SSO client from just a session. -// svc := sso.New(mySession) -// -// // Create a SSO client with additional configuration -// svc := sso.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *SSO { - c := p.ClientConfig(EndpointsID, cfgs...) - if c.SigningNameDerived || len(c.SigningName) == 0 { - c.SigningName = "awsssoportal" - } - return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *SSO { - svc := &SSO{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - ServiceID: ServiceID, - SigningName: signingName, - SigningRegion: signingRegion, - PartitionID: partitionID, - Endpoint: endpoint, - APIVersion: "2019-06-10", - ResolvedRegion: resolvedRegion, - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(restjson.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed( - protocol.NewUnmarshalErrorHandler(restjson.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), - ) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a SSO operation and runs any -// custom request initialization. -func (c *SSO) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sso/ssoiface/interface.go b/vendor/github.com/aws/aws-sdk-go/service/sso/ssoiface/interface.go deleted file mode 100644 index 818cab7cd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sso/ssoiface/interface.go +++ /dev/null @@ -1,86 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package ssoiface provides an interface to enable mocking the AWS Single Sign-On service client -// for testing your code. -// -// It is important to note that this interface will have breaking changes -// when the service model is updated and adds new API operations, paginators, -// and waiters. -package ssoiface - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/service/sso" -) - -// SSOAPI provides an interface to enable mocking the -// sso.SSO service client's API operation, -// paginators, and waiters. This make unit testing your code that calls out -// to the SDK's service client's calls easier. -// -// The best way to use this interface is so the SDK's service client's calls -// can be stubbed out for unit testing your code with the SDK without needing -// to inject custom request handlers into the SDK's request pipeline. -// -// // myFunc uses an SDK service client to make a request to -// // AWS Single Sign-On. -// func myFunc(svc ssoiface.SSOAPI) bool { -// // Make svc.GetRoleCredentials request -// } -// -// func main() { -// sess := session.New() -// svc := sso.New(sess) -// -// myFunc(svc) -// } -// -// In your _test.go file: -// -// // Define a mock struct to be used in your unit tests of myFunc. -// type mockSSOClient struct { -// ssoiface.SSOAPI -// } -// func (m *mockSSOClient) GetRoleCredentials(input *sso.GetRoleCredentialsInput) (*sso.GetRoleCredentialsOutput, error) { -// // mock response/functionality -// } -// -// func TestMyFunc(t *testing.T) { -// // Setup Test -// mockSvc := &mockSSOClient{} -// -// myfunc(mockSvc) -// -// // Verify myFunc's functionality -// } -// -// It is important to note that this interface will have breaking changes -// when the service model is updated and adds new API operations, paginators, -// and waiters. Its suggested to use the pattern above for testing, or using -// tooling to generate mocks to satisfy the interfaces. -type SSOAPI interface { - GetRoleCredentials(*sso.GetRoleCredentialsInput) (*sso.GetRoleCredentialsOutput, error) - GetRoleCredentialsWithContext(aws.Context, *sso.GetRoleCredentialsInput, ...request.Option) (*sso.GetRoleCredentialsOutput, error) - GetRoleCredentialsRequest(*sso.GetRoleCredentialsInput) (*request.Request, *sso.GetRoleCredentialsOutput) - - ListAccountRoles(*sso.ListAccountRolesInput) (*sso.ListAccountRolesOutput, error) - ListAccountRolesWithContext(aws.Context, *sso.ListAccountRolesInput, ...request.Option) (*sso.ListAccountRolesOutput, error) - ListAccountRolesRequest(*sso.ListAccountRolesInput) (*request.Request, *sso.ListAccountRolesOutput) - - ListAccountRolesPages(*sso.ListAccountRolesInput, func(*sso.ListAccountRolesOutput, bool) bool) error - ListAccountRolesPagesWithContext(aws.Context, *sso.ListAccountRolesInput, func(*sso.ListAccountRolesOutput, bool) bool, ...request.Option) error - - ListAccounts(*sso.ListAccountsInput) (*sso.ListAccountsOutput, error) - ListAccountsWithContext(aws.Context, *sso.ListAccountsInput, ...request.Option) (*sso.ListAccountsOutput, error) - ListAccountsRequest(*sso.ListAccountsInput) (*request.Request, *sso.ListAccountsOutput) - - ListAccountsPages(*sso.ListAccountsInput, func(*sso.ListAccountsOutput, bool) bool) error - ListAccountsPagesWithContext(aws.Context, *sso.ListAccountsInput, func(*sso.ListAccountsOutput, bool) bool, ...request.Option) error - - Logout(*sso.LogoutInput) (*sso.LogoutOutput, error) - LogoutWithContext(aws.Context, *sso.LogoutInput, ...request.Option) (*sso.LogoutOutput, error) - LogoutRequest(*sso.LogoutInput) (*request.Request, *sso.LogoutOutput) -} - -var _ SSOAPI = (*sso.SSO)(nil) diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/api.go b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/api.go deleted file mode 100644 index 827bd5194..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/api.go +++ /dev/null @@ -1,2406 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package ssooidc - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" -) - -const opCreateToken = "CreateToken" - -// CreateTokenRequest generates a "aws/request.Request" representing the -// client's request for the CreateToken operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateToken for more information on using the CreateToken -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the CreateTokenRequest method. -// req, resp := client.CreateTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateToken -func (c *SSOOIDC) CreateTokenRequest(input *CreateTokenInput) (req *request.Request, output *CreateTokenOutput) { - op := &request.Operation{ - Name: opCreateToken, - HTTPMethod: "POST", - HTTPPath: "/token", - } - - if input == nil { - input = &CreateTokenInput{} - } - - output = &CreateTokenOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - return -} - -// CreateToken API operation for AWS SSO OIDC. -// -// Creates and returns access and refresh tokens for clients that are authenticated -// using client secrets. The access token can be used to fetch short-term credentials -// for the assigned AWS accounts or to access application APIs using bearer -// authentication. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS SSO OIDC's -// API operation CreateToken for usage and error information. -// -// Returned Error Types: -// -// - InvalidRequestException -// Indicates that something is wrong with the input to the request. For example, -// a required parameter might be missing or out of range. -// -// - InvalidClientException -// Indicates that the clientId or clientSecret in the request is invalid. For -// example, this can occur when a client sends an incorrect clientId or an expired -// clientSecret. -// -// - InvalidGrantException -// Indicates that a request contains an invalid grant. This can occur if a client -// makes a CreateToken request with an invalid grant type. -// -// - UnauthorizedClientException -// Indicates that the client is not currently authorized to make the request. -// This can happen when a clientId is not issued for a public client. -// -// - UnsupportedGrantTypeException -// Indicates that the grant type in the request is not supported by the service. -// -// - InvalidScopeException -// Indicates that the scope provided in the request is invalid. -// -// - AuthorizationPendingException -// Indicates that a request to authorize a client with an access user session -// token is pending. -// -// - SlowDownException -// Indicates that the client is making the request too frequently and is more -// than the service can handle. -// -// - AccessDeniedException -// You do not have sufficient access to perform this action. -// -// - ExpiredTokenException -// Indicates that the token issued by the service is expired and is no longer -// valid. -// -// - InternalServerException -// Indicates that an error from the service occurred while trying to process -// a request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateToken -func (c *SSOOIDC) CreateToken(input *CreateTokenInput) (*CreateTokenOutput, error) { - req, out := c.CreateTokenRequest(input) - return out, req.Send() -} - -// CreateTokenWithContext is the same as CreateToken with the addition of -// the ability to pass a context and additional request options. -// -// See CreateToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSOOIDC) CreateTokenWithContext(ctx aws.Context, input *CreateTokenInput, opts ...request.Option) (*CreateTokenOutput, error) { - req, out := c.CreateTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateTokenWithIAM = "CreateTokenWithIAM" - -// CreateTokenWithIAMRequest generates a "aws/request.Request" representing the -// client's request for the CreateTokenWithIAM operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateTokenWithIAM for more information on using the CreateTokenWithIAM -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the CreateTokenWithIAMRequest method. -// req, resp := client.CreateTokenWithIAMRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateTokenWithIAM -func (c *SSOOIDC) CreateTokenWithIAMRequest(input *CreateTokenWithIAMInput) (req *request.Request, output *CreateTokenWithIAMOutput) { - op := &request.Operation{ - Name: opCreateTokenWithIAM, - HTTPMethod: "POST", - HTTPPath: "/token?aws_iam=t", - } - - if input == nil { - input = &CreateTokenWithIAMInput{} - } - - output = &CreateTokenWithIAMOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateTokenWithIAM API operation for AWS SSO OIDC. -// -// Creates and returns access and refresh tokens for clients and applications -// that are authenticated using IAM entities. The access token can be used to -// fetch short-term credentials for the assigned Amazon Web Services accounts -// or to access application APIs using bearer authentication. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS SSO OIDC's -// API operation CreateTokenWithIAM for usage and error information. -// -// Returned Error Types: -// -// - InvalidRequestException -// Indicates that something is wrong with the input to the request. For example, -// a required parameter might be missing or out of range. -// -// - InvalidClientException -// Indicates that the clientId or clientSecret in the request is invalid. For -// example, this can occur when a client sends an incorrect clientId or an expired -// clientSecret. -// -// - InvalidGrantException -// Indicates that a request contains an invalid grant. This can occur if a client -// makes a CreateToken request with an invalid grant type. -// -// - UnauthorizedClientException -// Indicates that the client is not currently authorized to make the request. -// This can happen when a clientId is not issued for a public client. -// -// - UnsupportedGrantTypeException -// Indicates that the grant type in the request is not supported by the service. -// -// - InvalidScopeException -// Indicates that the scope provided in the request is invalid. -// -// - AuthorizationPendingException -// Indicates that a request to authorize a client with an access user session -// token is pending. -// -// - SlowDownException -// Indicates that the client is making the request too frequently and is more -// than the service can handle. -// -// - AccessDeniedException -// You do not have sufficient access to perform this action. -// -// - ExpiredTokenException -// Indicates that the token issued by the service is expired and is no longer -// valid. -// -// - InternalServerException -// Indicates that an error from the service occurred while trying to process -// a request. -// -// - InvalidRequestRegionException -// Indicates that a token provided as input to the request was issued by and -// is only usable by calling IAM Identity Center endpoints in another region. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/CreateTokenWithIAM -func (c *SSOOIDC) CreateTokenWithIAM(input *CreateTokenWithIAMInput) (*CreateTokenWithIAMOutput, error) { - req, out := c.CreateTokenWithIAMRequest(input) - return out, req.Send() -} - -// CreateTokenWithIAMWithContext is the same as CreateTokenWithIAM with the addition of -// the ability to pass a context and additional request options. -// -// See CreateTokenWithIAM for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSOOIDC) CreateTokenWithIAMWithContext(ctx aws.Context, input *CreateTokenWithIAMInput, opts ...request.Option) (*CreateTokenWithIAMOutput, error) { - req, out := c.CreateTokenWithIAMRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opRegisterClient = "RegisterClient" - -// RegisterClientRequest generates a "aws/request.Request" representing the -// client's request for the RegisterClient operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See RegisterClient for more information on using the RegisterClient -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the RegisterClientRequest method. -// req, resp := client.RegisterClientRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/RegisterClient -func (c *SSOOIDC) RegisterClientRequest(input *RegisterClientInput) (req *request.Request, output *RegisterClientOutput) { - op := &request.Operation{ - Name: opRegisterClient, - HTTPMethod: "POST", - HTTPPath: "/client/register", - } - - if input == nil { - input = &RegisterClientInput{} - } - - output = &RegisterClientOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - return -} - -// RegisterClient API operation for AWS SSO OIDC. -// -// Registers a client with IAM Identity Center. This allows clients to initiate -// device authorization. The output should be persisted for reuse through many -// authentication requests. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS SSO OIDC's -// API operation RegisterClient for usage and error information. -// -// Returned Error Types: -// -// - InvalidRequestException -// Indicates that something is wrong with the input to the request. For example, -// a required parameter might be missing or out of range. -// -// - InvalidScopeException -// Indicates that the scope provided in the request is invalid. -// -// - InvalidClientMetadataException -// Indicates that the client information sent in the request during registration -// is invalid. -// -// - InternalServerException -// Indicates that an error from the service occurred while trying to process -// a request. -// -// - InvalidRedirectUriException -// Indicates that one or more redirect URI in the request is not supported for -// this operation. -// -// - UnsupportedGrantTypeException -// Indicates that the grant type in the request is not supported by the service. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/RegisterClient -func (c *SSOOIDC) RegisterClient(input *RegisterClientInput) (*RegisterClientOutput, error) { - req, out := c.RegisterClientRequest(input) - return out, req.Send() -} - -// RegisterClientWithContext is the same as RegisterClient with the addition of -// the ability to pass a context and additional request options. -// -// See RegisterClient for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSOOIDC) RegisterClientWithContext(ctx aws.Context, input *RegisterClientInput, opts ...request.Option) (*RegisterClientOutput, error) { - req, out := c.RegisterClientRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opStartDeviceAuthorization = "StartDeviceAuthorization" - -// StartDeviceAuthorizationRequest generates a "aws/request.Request" representing the -// client's request for the StartDeviceAuthorization operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See StartDeviceAuthorization for more information on using the StartDeviceAuthorization -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the StartDeviceAuthorizationRequest method. -// req, resp := client.StartDeviceAuthorizationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/StartDeviceAuthorization -func (c *SSOOIDC) StartDeviceAuthorizationRequest(input *StartDeviceAuthorizationInput) (req *request.Request, output *StartDeviceAuthorizationOutput) { - op := &request.Operation{ - Name: opStartDeviceAuthorization, - HTTPMethod: "POST", - HTTPPath: "/device_authorization", - } - - if input == nil { - input = &StartDeviceAuthorizationInput{} - } - - output = &StartDeviceAuthorizationOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - return -} - -// StartDeviceAuthorization API operation for AWS SSO OIDC. -// -// Initiates device authorization by requesting a pair of verification codes -// from the authorization service. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS SSO OIDC's -// API operation StartDeviceAuthorization for usage and error information. -// -// Returned Error Types: -// -// - InvalidRequestException -// Indicates that something is wrong with the input to the request. For example, -// a required parameter might be missing or out of range. -// -// - InvalidClientException -// Indicates that the clientId or clientSecret in the request is invalid. For -// example, this can occur when a client sends an incorrect clientId or an expired -// clientSecret. -// -// - UnauthorizedClientException -// Indicates that the client is not currently authorized to make the request. -// This can happen when a clientId is not issued for a public client. -// -// - SlowDownException -// Indicates that the client is making the request too frequently and is more -// than the service can handle. -// -// - InternalServerException -// Indicates that an error from the service occurred while trying to process -// a request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/StartDeviceAuthorization -func (c *SSOOIDC) StartDeviceAuthorization(input *StartDeviceAuthorizationInput) (*StartDeviceAuthorizationOutput, error) { - req, out := c.StartDeviceAuthorizationRequest(input) - return out, req.Send() -} - -// StartDeviceAuthorizationWithContext is the same as StartDeviceAuthorization with the addition of -// the ability to pass a context and additional request options. -// -// See StartDeviceAuthorization for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *SSOOIDC) StartDeviceAuthorizationWithContext(ctx aws.Context, input *StartDeviceAuthorizationInput, opts ...request.Option) (*StartDeviceAuthorizationOutput, error) { - req, out := c.StartDeviceAuthorizationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// You do not have sufficient access to perform this action. -type AccessDeniedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be access_denied. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AccessDeniedException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AccessDeniedException) GoString() string { - return s.String() -} - -func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { - return &AccessDeniedException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *AccessDeniedException) Code() string { - return "AccessDeniedException" -} - -// Message returns the exception's message. -func (s *AccessDeniedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *AccessDeniedException) OrigErr() error { - return nil -} - -func (s *AccessDeniedException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *AccessDeniedException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *AccessDeniedException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that a request to authorize a client with an access user session -// token is pending. -type AuthorizationPendingException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be authorization_pending. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AuthorizationPendingException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AuthorizationPendingException) GoString() string { - return s.String() -} - -func newErrorAuthorizationPendingException(v protocol.ResponseMetadata) error { - return &AuthorizationPendingException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *AuthorizationPendingException) Code() string { - return "AuthorizationPendingException" -} - -// Message returns the exception's message. -func (s *AuthorizationPendingException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *AuthorizationPendingException) OrigErr() error { - return nil -} - -func (s *AuthorizationPendingException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *AuthorizationPendingException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *AuthorizationPendingException) RequestID() string { - return s.RespMetadata.RequestID -} - -type CreateTokenInput struct { - _ struct{} `type:"structure"` - - // The unique identifier string for the client or application. This value comes - // from the result of the RegisterClient API. - // - // ClientId is a required field - ClientId *string `locationName:"clientId" type:"string" required:"true"` - - // A secret string generated for the client. This value should come from the - // persisted result of the RegisterClient API. - // - // ClientSecret is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenInput's - // String and GoString methods. - // - // ClientSecret is a required field - ClientSecret *string `locationName:"clientSecret" type:"string" required:"true" sensitive:"true"` - - // Used only when calling this API for the Authorization Code grant type. The - // short-term code is used to identify this authorization request. This grant - // type is currently unsupported for the CreateToken API. - Code *string `locationName:"code" type:"string"` - - // Used only when calling this API for the Authorization Code grant type. This - // value is generated by the client and presented to validate the original code - // challenge value the client passed at authorization time. - // - // CodeVerifier is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenInput's - // String and GoString methods. - CodeVerifier *string `locationName:"codeVerifier" type:"string" sensitive:"true"` - - // Used only when calling this API for the Device Code grant type. This short-term - // code is used to identify this authorization request. This comes from the - // result of the StartDeviceAuthorization API. - DeviceCode *string `locationName:"deviceCode" type:"string"` - - // Supports the following OAuth grant types: Device Code and Refresh Token. - // Specify either of the following values, depending on the grant type that - // you want: - // - // * Device Code - urn:ietf:params:oauth:grant-type:device_code - // - // * Refresh Token - refresh_token - // - // For information about how to obtain the device code, see the StartDeviceAuthorization - // topic. - // - // GrantType is a required field - GrantType *string `locationName:"grantType" type:"string" required:"true"` - - // Used only when calling this API for the Authorization Code grant type. This - // value specifies the location of the client or application that has registered - // to receive the authorization code. - RedirectUri *string `locationName:"redirectUri" type:"string"` - - // Used only when calling this API for the Refresh Token grant type. This token - // is used to refresh short-term tokens, such as the access token, that might - // expire. - // - // For more information about the features and limitations of the current IAM - // Identity Center OIDC implementation, see Considerations for Using this Guide - // in the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). - // - // RefreshToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenInput's - // String and GoString methods. - RefreshToken *string `locationName:"refreshToken" type:"string" sensitive:"true"` - - // The list of scopes for which authorization is requested. The access token - // that is issued is limited to the scopes that are granted. If this value is - // not specified, IAM Identity Center authorizes all scopes that are configured - // for the client during the call to RegisterClient. - Scope []*string `locationName:"scope" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTokenInput"} - if s.ClientId == nil { - invalidParams.Add(request.NewErrParamRequired("ClientId")) - } - if s.ClientSecret == nil { - invalidParams.Add(request.NewErrParamRequired("ClientSecret")) - } - if s.GrantType == nil { - invalidParams.Add(request.NewErrParamRequired("GrantType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetClientId sets the ClientId field's value. -func (s *CreateTokenInput) SetClientId(v string) *CreateTokenInput { - s.ClientId = &v - return s -} - -// SetClientSecret sets the ClientSecret field's value. -func (s *CreateTokenInput) SetClientSecret(v string) *CreateTokenInput { - s.ClientSecret = &v - return s -} - -// SetCode sets the Code field's value. -func (s *CreateTokenInput) SetCode(v string) *CreateTokenInput { - s.Code = &v - return s -} - -// SetCodeVerifier sets the CodeVerifier field's value. -func (s *CreateTokenInput) SetCodeVerifier(v string) *CreateTokenInput { - s.CodeVerifier = &v - return s -} - -// SetDeviceCode sets the DeviceCode field's value. -func (s *CreateTokenInput) SetDeviceCode(v string) *CreateTokenInput { - s.DeviceCode = &v - return s -} - -// SetGrantType sets the GrantType field's value. -func (s *CreateTokenInput) SetGrantType(v string) *CreateTokenInput { - s.GrantType = &v - return s -} - -// SetRedirectUri sets the RedirectUri field's value. -func (s *CreateTokenInput) SetRedirectUri(v string) *CreateTokenInput { - s.RedirectUri = &v - return s -} - -// SetRefreshToken sets the RefreshToken field's value. -func (s *CreateTokenInput) SetRefreshToken(v string) *CreateTokenInput { - s.RefreshToken = &v - return s -} - -// SetScope sets the Scope field's value. -func (s *CreateTokenInput) SetScope(v []*string) *CreateTokenInput { - s.Scope = v - return s -} - -type CreateTokenOutput struct { - _ struct{} `type:"structure"` - - // A bearer token to access Amazon Web Services accounts and applications assigned - // to a user. - // - // AccessToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenOutput's - // String and GoString methods. - AccessToken *string `locationName:"accessToken" type:"string" sensitive:"true"` - - // Indicates the time in seconds when an access token will expire. - ExpiresIn *int64 `locationName:"expiresIn" type:"integer"` - - // The idToken is not implemented or supported. For more information about the - // features and limitations of the current IAM Identity Center OIDC implementation, - // see Considerations for Using this Guide in the IAM Identity Center OIDC API - // Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). - // - // A JSON Web Token (JWT) that identifies who is associated with the issued - // access token. - // - // IdToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenOutput's - // String and GoString methods. - IdToken *string `locationName:"idToken" type:"string" sensitive:"true"` - - // A token that, if present, can be used to refresh a previously issued access - // token that might have expired. - // - // For more information about the features and limitations of the current IAM - // Identity Center OIDC implementation, see Considerations for Using this Guide - // in the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). - // - // RefreshToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenOutput's - // String and GoString methods. - RefreshToken *string `locationName:"refreshToken" type:"string" sensitive:"true"` - - // Used to notify the client that the returned token is an access token. The - // supported token type is Bearer. - TokenType *string `locationName:"tokenType" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateTokenOutput) GoString() string { - return s.String() -} - -// SetAccessToken sets the AccessToken field's value. -func (s *CreateTokenOutput) SetAccessToken(v string) *CreateTokenOutput { - s.AccessToken = &v - return s -} - -// SetExpiresIn sets the ExpiresIn field's value. -func (s *CreateTokenOutput) SetExpiresIn(v int64) *CreateTokenOutput { - s.ExpiresIn = &v - return s -} - -// SetIdToken sets the IdToken field's value. -func (s *CreateTokenOutput) SetIdToken(v string) *CreateTokenOutput { - s.IdToken = &v - return s -} - -// SetRefreshToken sets the RefreshToken field's value. -func (s *CreateTokenOutput) SetRefreshToken(v string) *CreateTokenOutput { - s.RefreshToken = &v - return s -} - -// SetTokenType sets the TokenType field's value. -func (s *CreateTokenOutput) SetTokenType(v string) *CreateTokenOutput { - s.TokenType = &v - return s -} - -type CreateTokenWithIAMInput struct { - _ struct{} `type:"structure"` - - // Used only when calling this API for the JWT Bearer grant type. This value - // specifies the JSON Web Token (JWT) issued by a trusted token issuer. To authorize - // a trusted token issuer, configure the JWT Bearer GrantOptions for the application. - // - // Assertion is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenWithIAMInput's - // String and GoString methods. - Assertion *string `locationName:"assertion" type:"string" sensitive:"true"` - - // The unique identifier string for the client or application. This value is - // an application ARN that has OAuth grants configured. - // - // ClientId is a required field - ClientId *string `locationName:"clientId" type:"string" required:"true"` - - // Used only when calling this API for the Authorization Code grant type. This - // short-term code is used to identify this authorization request. The code - // is obtained through a redirect from IAM Identity Center to a redirect URI - // persisted in the Authorization Code GrantOptions for the application. - Code *string `locationName:"code" type:"string"` - - // Used only when calling this API for the Authorization Code grant type. This - // value is generated by the client and presented to validate the original code - // challenge value the client passed at authorization time. - // - // CodeVerifier is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenWithIAMInput's - // String and GoString methods. - CodeVerifier *string `locationName:"codeVerifier" type:"string" sensitive:"true"` - - // Supports the following OAuth grant types: Authorization Code, Refresh Token, - // JWT Bearer, and Token Exchange. Specify one of the following values, depending - // on the grant type that you want: - // - // * Authorization Code - authorization_code - // - // * Refresh Token - refresh_token - // - // * JWT Bearer - urn:ietf:params:oauth:grant-type:jwt-bearer - // - // * Token Exchange - urn:ietf:params:oauth:grant-type:token-exchange - // - // GrantType is a required field - GrantType *string `locationName:"grantType" type:"string" required:"true"` - - // Used only when calling this API for the Authorization Code grant type. This - // value specifies the location of the client or application that has registered - // to receive the authorization code. - RedirectUri *string `locationName:"redirectUri" type:"string"` - - // Used only when calling this API for the Refresh Token grant type. This token - // is used to refresh short-term tokens, such as the access token, that might - // expire. - // - // For more information about the features and limitations of the current IAM - // Identity Center OIDC implementation, see Considerations for Using this Guide - // in the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). - // - // RefreshToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenWithIAMInput's - // String and GoString methods. - RefreshToken *string `locationName:"refreshToken" type:"string" sensitive:"true"` - - // Used only when calling this API for the Token Exchange grant type. This value - // specifies the type of token that the requester can receive. The following - // values are supported: - // - // * Access Token - urn:ietf:params:oauth:token-type:access_token - // - // * Refresh Token - urn:ietf:params:oauth:token-type:refresh_token - RequestedTokenType *string `locationName:"requestedTokenType" type:"string"` - - // The list of scopes for which authorization is requested. The access token - // that is issued is limited to the scopes that are granted. If the value is - // not specified, IAM Identity Center authorizes all scopes configured for the - // application, including the following default scopes: openid, aws, sts:identity_context. - Scope []*string `locationName:"scope" type:"list"` - - // Used only when calling this API for the Token Exchange grant type. This value - // specifies the subject of the exchange. The value of the subject token must - // be an access token issued by IAM Identity Center to a different client or - // application. The access token must have authorized scopes that indicate the - // requested application as a target audience. - // - // SubjectToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenWithIAMInput's - // String and GoString methods. - SubjectToken *string `locationName:"subjectToken" type:"string" sensitive:"true"` - - // Used only when calling this API for the Token Exchange grant type. This value - // specifies the type of token that is passed as the subject of the exchange. - // The following value is supported: - // - // * Access Token - urn:ietf:params:oauth:token-type:access_token - SubjectTokenType *string `locationName:"subjectTokenType" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateTokenWithIAMInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateTokenWithIAMInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTokenWithIAMInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTokenWithIAMInput"} - if s.ClientId == nil { - invalidParams.Add(request.NewErrParamRequired("ClientId")) - } - if s.GrantType == nil { - invalidParams.Add(request.NewErrParamRequired("GrantType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAssertion sets the Assertion field's value. -func (s *CreateTokenWithIAMInput) SetAssertion(v string) *CreateTokenWithIAMInput { - s.Assertion = &v - return s -} - -// SetClientId sets the ClientId field's value. -func (s *CreateTokenWithIAMInput) SetClientId(v string) *CreateTokenWithIAMInput { - s.ClientId = &v - return s -} - -// SetCode sets the Code field's value. -func (s *CreateTokenWithIAMInput) SetCode(v string) *CreateTokenWithIAMInput { - s.Code = &v - return s -} - -// SetCodeVerifier sets the CodeVerifier field's value. -func (s *CreateTokenWithIAMInput) SetCodeVerifier(v string) *CreateTokenWithIAMInput { - s.CodeVerifier = &v - return s -} - -// SetGrantType sets the GrantType field's value. -func (s *CreateTokenWithIAMInput) SetGrantType(v string) *CreateTokenWithIAMInput { - s.GrantType = &v - return s -} - -// SetRedirectUri sets the RedirectUri field's value. -func (s *CreateTokenWithIAMInput) SetRedirectUri(v string) *CreateTokenWithIAMInput { - s.RedirectUri = &v - return s -} - -// SetRefreshToken sets the RefreshToken field's value. -func (s *CreateTokenWithIAMInput) SetRefreshToken(v string) *CreateTokenWithIAMInput { - s.RefreshToken = &v - return s -} - -// SetRequestedTokenType sets the RequestedTokenType field's value. -func (s *CreateTokenWithIAMInput) SetRequestedTokenType(v string) *CreateTokenWithIAMInput { - s.RequestedTokenType = &v - return s -} - -// SetScope sets the Scope field's value. -func (s *CreateTokenWithIAMInput) SetScope(v []*string) *CreateTokenWithIAMInput { - s.Scope = v - return s -} - -// SetSubjectToken sets the SubjectToken field's value. -func (s *CreateTokenWithIAMInput) SetSubjectToken(v string) *CreateTokenWithIAMInput { - s.SubjectToken = &v - return s -} - -// SetSubjectTokenType sets the SubjectTokenType field's value. -func (s *CreateTokenWithIAMInput) SetSubjectTokenType(v string) *CreateTokenWithIAMInput { - s.SubjectTokenType = &v - return s -} - -type CreateTokenWithIAMOutput struct { - _ struct{} `type:"structure"` - - // A bearer token to access Amazon Web Services accounts and applications assigned - // to a user. - // - // AccessToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenWithIAMOutput's - // String and GoString methods. - AccessToken *string `locationName:"accessToken" type:"string" sensitive:"true"` - - // Indicates the time in seconds when an access token will expire. - ExpiresIn *int64 `locationName:"expiresIn" type:"integer"` - - // A JSON Web Token (JWT) that identifies the user associated with the issued - // access token. - // - // IdToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenWithIAMOutput's - // String and GoString methods. - IdToken *string `locationName:"idToken" type:"string" sensitive:"true"` - - // Indicates the type of tokens that are issued by IAM Identity Center. The - // following values are supported: - // - // * Access Token - urn:ietf:params:oauth:token-type:access_token - // - // * Refresh Token - urn:ietf:params:oauth:token-type:refresh_token - IssuedTokenType *string `locationName:"issuedTokenType" type:"string"` - - // A token that, if present, can be used to refresh a previously issued access - // token that might have expired. - // - // For more information about the features and limitations of the current IAM - // Identity Center OIDC implementation, see Considerations for Using this Guide - // in the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html). - // - // RefreshToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateTokenWithIAMOutput's - // String and GoString methods. - RefreshToken *string `locationName:"refreshToken" type:"string" sensitive:"true"` - - // The list of scopes for which authorization is granted. The access token that - // is issued is limited to the scopes that are granted. - Scope []*string `locationName:"scope" type:"list"` - - // Used to notify the requester that the returned token is an access token. - // The supported token type is Bearer. - TokenType *string `locationName:"tokenType" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateTokenWithIAMOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s CreateTokenWithIAMOutput) GoString() string { - return s.String() -} - -// SetAccessToken sets the AccessToken field's value. -func (s *CreateTokenWithIAMOutput) SetAccessToken(v string) *CreateTokenWithIAMOutput { - s.AccessToken = &v - return s -} - -// SetExpiresIn sets the ExpiresIn field's value. -func (s *CreateTokenWithIAMOutput) SetExpiresIn(v int64) *CreateTokenWithIAMOutput { - s.ExpiresIn = &v - return s -} - -// SetIdToken sets the IdToken field's value. -func (s *CreateTokenWithIAMOutput) SetIdToken(v string) *CreateTokenWithIAMOutput { - s.IdToken = &v - return s -} - -// SetIssuedTokenType sets the IssuedTokenType field's value. -func (s *CreateTokenWithIAMOutput) SetIssuedTokenType(v string) *CreateTokenWithIAMOutput { - s.IssuedTokenType = &v - return s -} - -// SetRefreshToken sets the RefreshToken field's value. -func (s *CreateTokenWithIAMOutput) SetRefreshToken(v string) *CreateTokenWithIAMOutput { - s.RefreshToken = &v - return s -} - -// SetScope sets the Scope field's value. -func (s *CreateTokenWithIAMOutput) SetScope(v []*string) *CreateTokenWithIAMOutput { - s.Scope = v - return s -} - -// SetTokenType sets the TokenType field's value. -func (s *CreateTokenWithIAMOutput) SetTokenType(v string) *CreateTokenWithIAMOutput { - s.TokenType = &v - return s -} - -// Indicates that the token issued by the service is expired and is no longer -// valid. -type ExpiredTokenException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be expired_token. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ExpiredTokenException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ExpiredTokenException) GoString() string { - return s.String() -} - -func newErrorExpiredTokenException(v protocol.ResponseMetadata) error { - return &ExpiredTokenException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ExpiredTokenException) Code() string { - return "ExpiredTokenException" -} - -// Message returns the exception's message. -func (s *ExpiredTokenException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ExpiredTokenException) OrigErr() error { - return nil -} - -func (s *ExpiredTokenException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ExpiredTokenException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ExpiredTokenException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that an error from the service occurred while trying to process -// a request. -type InternalServerException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be server_error. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InternalServerException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InternalServerException) GoString() string { - return s.String() -} - -func newErrorInternalServerException(v protocol.ResponseMetadata) error { - return &InternalServerException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InternalServerException) Code() string { - return "InternalServerException" -} - -// Message returns the exception's message. -func (s *InternalServerException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InternalServerException) OrigErr() error { - return nil -} - -func (s *InternalServerException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InternalServerException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InternalServerException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that the clientId or clientSecret in the request is invalid. For -// example, this can occur when a client sends an incorrect clientId or an expired -// clientSecret. -type InvalidClientException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be invalid_client. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidClientException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidClientException) GoString() string { - return s.String() -} - -func newErrorInvalidClientException(v protocol.ResponseMetadata) error { - return &InvalidClientException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidClientException) Code() string { - return "InvalidClientException" -} - -// Message returns the exception's message. -func (s *InvalidClientException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidClientException) OrigErr() error { - return nil -} - -func (s *InvalidClientException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidClientException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidClientException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that the client information sent in the request during registration -// is invalid. -type InvalidClientMetadataException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be invalid_client_metadata. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidClientMetadataException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidClientMetadataException) GoString() string { - return s.String() -} - -func newErrorInvalidClientMetadataException(v protocol.ResponseMetadata) error { - return &InvalidClientMetadataException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidClientMetadataException) Code() string { - return "InvalidClientMetadataException" -} - -// Message returns the exception's message. -func (s *InvalidClientMetadataException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidClientMetadataException) OrigErr() error { - return nil -} - -func (s *InvalidClientMetadataException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidClientMetadataException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidClientMetadataException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that a request contains an invalid grant. This can occur if a client -// makes a CreateToken request with an invalid grant type. -type InvalidGrantException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be invalid_grant. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidGrantException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidGrantException) GoString() string { - return s.String() -} - -func newErrorInvalidGrantException(v protocol.ResponseMetadata) error { - return &InvalidGrantException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidGrantException) Code() string { - return "InvalidGrantException" -} - -// Message returns the exception's message. -func (s *InvalidGrantException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidGrantException) OrigErr() error { - return nil -} - -func (s *InvalidGrantException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidGrantException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidGrantException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that one or more redirect URI in the request is not supported for -// this operation. -type InvalidRedirectUriException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be invalid_redirect_uri. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidRedirectUriException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidRedirectUriException) GoString() string { - return s.String() -} - -func newErrorInvalidRedirectUriException(v protocol.ResponseMetadata) error { - return &InvalidRedirectUriException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidRedirectUriException) Code() string { - return "InvalidRedirectUriException" -} - -// Message returns the exception's message. -func (s *InvalidRedirectUriException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidRedirectUriException) OrigErr() error { - return nil -} - -func (s *InvalidRedirectUriException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidRedirectUriException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidRedirectUriException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that something is wrong with the input to the request. For example, -// a required parameter might be missing or out of range. -type InvalidRequestException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be invalid_request. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidRequestException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidRequestException) GoString() string { - return s.String() -} - -func newErrorInvalidRequestException(v protocol.ResponseMetadata) error { - return &InvalidRequestException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidRequestException) Code() string { - return "InvalidRequestException" -} - -// Message returns the exception's message. -func (s *InvalidRequestException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidRequestException) OrigErr() error { - return nil -} - -func (s *InvalidRequestException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidRequestException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidRequestException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that a token provided as input to the request was issued by and -// is only usable by calling IAM Identity Center endpoints in another region. -type InvalidRequestRegionException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Indicates the IAM Identity Center endpoint which the requester may call with - // this token. - Endpoint *string `locationName:"endpoint" type:"string"` - - // Single error code. For this exception the value will be invalid_request. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` - - // Indicates the region which the requester may call with this token. - Region *string `locationName:"region" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidRequestRegionException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidRequestRegionException) GoString() string { - return s.String() -} - -func newErrorInvalidRequestRegionException(v protocol.ResponseMetadata) error { - return &InvalidRequestRegionException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidRequestRegionException) Code() string { - return "InvalidRequestRegionException" -} - -// Message returns the exception's message. -func (s *InvalidRequestRegionException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidRequestRegionException) OrigErr() error { - return nil -} - -func (s *InvalidRequestRegionException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidRequestRegionException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidRequestRegionException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that the scope provided in the request is invalid. -type InvalidScopeException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be invalid_scope. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidScopeException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s InvalidScopeException) GoString() string { - return s.String() -} - -func newErrorInvalidScopeException(v protocol.ResponseMetadata) error { - return &InvalidScopeException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidScopeException) Code() string { - return "InvalidScopeException" -} - -// Message returns the exception's message. -func (s *InvalidScopeException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidScopeException) OrigErr() error { - return nil -} - -func (s *InvalidScopeException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidScopeException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *InvalidScopeException) RequestID() string { - return s.RespMetadata.RequestID -} - -type RegisterClientInput struct { - _ struct{} `type:"structure"` - - // The friendly name of the client. - // - // ClientName is a required field - ClientName *string `locationName:"clientName" type:"string" required:"true"` - - // The type of client. The service supports only public as a client type. Anything - // other than public will be rejected by the service. - // - // ClientType is a required field - ClientType *string `locationName:"clientType" type:"string" required:"true"` - - // This IAM Identity Center application ARN is used to define administrator-managed - // configuration for public client access to resources. At authorization, the - // scopes, grants, and redirect URI available to this client will be restricted - // by this application resource. - EntitledApplicationArn *string `locationName:"entitledApplicationArn" type:"string"` - - // The list of OAuth 2.0 grant types that are defined by the client. This list - // is used to restrict the token granting flows available to the client. - GrantTypes []*string `locationName:"grantTypes" type:"list"` - - // The IAM Identity Center Issuer URL associated with an instance of IAM Identity - // Center. This value is needed for user access to resources through the client. - IssuerUrl *string `locationName:"issuerUrl" type:"string"` - - // The list of redirect URI that are defined by the client. At completion of - // authorization, this list is used to restrict what locations the user agent - // can be redirected back to. - RedirectUris []*string `locationName:"redirectUris" type:"list"` - - // The list of scopes that are defined by the client. Upon authorization, this - // list is used to restrict permissions when granting an access token. - Scopes []*string `locationName:"scopes" type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RegisterClientInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RegisterClientInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *RegisterClientInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RegisterClientInput"} - if s.ClientName == nil { - invalidParams.Add(request.NewErrParamRequired("ClientName")) - } - if s.ClientType == nil { - invalidParams.Add(request.NewErrParamRequired("ClientType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetClientName sets the ClientName field's value. -func (s *RegisterClientInput) SetClientName(v string) *RegisterClientInput { - s.ClientName = &v - return s -} - -// SetClientType sets the ClientType field's value. -func (s *RegisterClientInput) SetClientType(v string) *RegisterClientInput { - s.ClientType = &v - return s -} - -// SetEntitledApplicationArn sets the EntitledApplicationArn field's value. -func (s *RegisterClientInput) SetEntitledApplicationArn(v string) *RegisterClientInput { - s.EntitledApplicationArn = &v - return s -} - -// SetGrantTypes sets the GrantTypes field's value. -func (s *RegisterClientInput) SetGrantTypes(v []*string) *RegisterClientInput { - s.GrantTypes = v - return s -} - -// SetIssuerUrl sets the IssuerUrl field's value. -func (s *RegisterClientInput) SetIssuerUrl(v string) *RegisterClientInput { - s.IssuerUrl = &v - return s -} - -// SetRedirectUris sets the RedirectUris field's value. -func (s *RegisterClientInput) SetRedirectUris(v []*string) *RegisterClientInput { - s.RedirectUris = v - return s -} - -// SetScopes sets the Scopes field's value. -func (s *RegisterClientInput) SetScopes(v []*string) *RegisterClientInput { - s.Scopes = v - return s -} - -type RegisterClientOutput struct { - _ struct{} `type:"structure"` - - // An endpoint that the client can use to request authorization. - AuthorizationEndpoint *string `locationName:"authorizationEndpoint" type:"string"` - - // The unique identifier string for each client. This client uses this identifier - // to get authenticated by the service in subsequent calls. - ClientId *string `locationName:"clientId" type:"string"` - - // Indicates the time at which the clientId and clientSecret were issued. - ClientIdIssuedAt *int64 `locationName:"clientIdIssuedAt" type:"long"` - - // A secret string generated for the client. The client will use this string - // to get authenticated by the service in subsequent calls. - // - // ClientSecret is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by RegisterClientOutput's - // String and GoString methods. - ClientSecret *string `locationName:"clientSecret" type:"string" sensitive:"true"` - - // Indicates the time at which the clientId and clientSecret will become invalid. - ClientSecretExpiresAt *int64 `locationName:"clientSecretExpiresAt" type:"long"` - - // An endpoint that the client can use to create tokens. - TokenEndpoint *string `locationName:"tokenEndpoint" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RegisterClientOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s RegisterClientOutput) GoString() string { - return s.String() -} - -// SetAuthorizationEndpoint sets the AuthorizationEndpoint field's value. -func (s *RegisterClientOutput) SetAuthorizationEndpoint(v string) *RegisterClientOutput { - s.AuthorizationEndpoint = &v - return s -} - -// SetClientId sets the ClientId field's value. -func (s *RegisterClientOutput) SetClientId(v string) *RegisterClientOutput { - s.ClientId = &v - return s -} - -// SetClientIdIssuedAt sets the ClientIdIssuedAt field's value. -func (s *RegisterClientOutput) SetClientIdIssuedAt(v int64) *RegisterClientOutput { - s.ClientIdIssuedAt = &v - return s -} - -// SetClientSecret sets the ClientSecret field's value. -func (s *RegisterClientOutput) SetClientSecret(v string) *RegisterClientOutput { - s.ClientSecret = &v - return s -} - -// SetClientSecretExpiresAt sets the ClientSecretExpiresAt field's value. -func (s *RegisterClientOutput) SetClientSecretExpiresAt(v int64) *RegisterClientOutput { - s.ClientSecretExpiresAt = &v - return s -} - -// SetTokenEndpoint sets the TokenEndpoint field's value. -func (s *RegisterClientOutput) SetTokenEndpoint(v string) *RegisterClientOutput { - s.TokenEndpoint = &v - return s -} - -// Indicates that the client is making the request too frequently and is more -// than the service can handle. -type SlowDownException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be slow_down. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SlowDownException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s SlowDownException) GoString() string { - return s.String() -} - -func newErrorSlowDownException(v protocol.ResponseMetadata) error { - return &SlowDownException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *SlowDownException) Code() string { - return "SlowDownException" -} - -// Message returns the exception's message. -func (s *SlowDownException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *SlowDownException) OrigErr() error { - return nil -} - -func (s *SlowDownException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *SlowDownException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *SlowDownException) RequestID() string { - return s.RespMetadata.RequestID -} - -type StartDeviceAuthorizationInput struct { - _ struct{} `type:"structure"` - - // The unique identifier string for the client that is registered with IAM Identity - // Center. This value should come from the persisted result of the RegisterClient - // API operation. - // - // ClientId is a required field - ClientId *string `locationName:"clientId" type:"string" required:"true"` - - // A secret string that is generated for the client. This value should come - // from the persisted result of the RegisterClient API operation. - // - // ClientSecret is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by StartDeviceAuthorizationInput's - // String and GoString methods. - // - // ClientSecret is a required field - ClientSecret *string `locationName:"clientSecret" type:"string" required:"true" sensitive:"true"` - - // The URL for the Amazon Web Services access portal. For more information, - // see Using the Amazon Web Services access portal (https://docs.aws.amazon.com/singlesignon/latest/userguide/using-the-portal.html) - // in the IAM Identity Center User Guide. - // - // StartUrl is a required field - StartUrl *string `locationName:"startUrl" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartDeviceAuthorizationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartDeviceAuthorizationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StartDeviceAuthorizationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StartDeviceAuthorizationInput"} - if s.ClientId == nil { - invalidParams.Add(request.NewErrParamRequired("ClientId")) - } - if s.ClientSecret == nil { - invalidParams.Add(request.NewErrParamRequired("ClientSecret")) - } - if s.StartUrl == nil { - invalidParams.Add(request.NewErrParamRequired("StartUrl")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetClientId sets the ClientId field's value. -func (s *StartDeviceAuthorizationInput) SetClientId(v string) *StartDeviceAuthorizationInput { - s.ClientId = &v - return s -} - -// SetClientSecret sets the ClientSecret field's value. -func (s *StartDeviceAuthorizationInput) SetClientSecret(v string) *StartDeviceAuthorizationInput { - s.ClientSecret = &v - return s -} - -// SetStartUrl sets the StartUrl field's value. -func (s *StartDeviceAuthorizationInput) SetStartUrl(v string) *StartDeviceAuthorizationInput { - s.StartUrl = &v - return s -} - -type StartDeviceAuthorizationOutput struct { - _ struct{} `type:"structure"` - - // The short-lived code that is used by the device when polling for a session - // token. - DeviceCode *string `locationName:"deviceCode" type:"string"` - - // Indicates the number of seconds in which the verification code will become - // invalid. - ExpiresIn *int64 `locationName:"expiresIn" type:"integer"` - - // Indicates the number of seconds the client must wait between attempts when - // polling for a session. - Interval *int64 `locationName:"interval" type:"integer"` - - // A one-time user verification code. This is needed to authorize an in-use - // device. - UserCode *string `locationName:"userCode" type:"string"` - - // The URI of the verification page that takes the userCode to authorize the - // device. - VerificationUri *string `locationName:"verificationUri" type:"string"` - - // An alternate URL that the client can use to automatically launch a browser. - // This process skips the manual step in which the user visits the verification - // page and enters their code. - VerificationUriComplete *string `locationName:"verificationUriComplete" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartDeviceAuthorizationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s StartDeviceAuthorizationOutput) GoString() string { - return s.String() -} - -// SetDeviceCode sets the DeviceCode field's value. -func (s *StartDeviceAuthorizationOutput) SetDeviceCode(v string) *StartDeviceAuthorizationOutput { - s.DeviceCode = &v - return s -} - -// SetExpiresIn sets the ExpiresIn field's value. -func (s *StartDeviceAuthorizationOutput) SetExpiresIn(v int64) *StartDeviceAuthorizationOutput { - s.ExpiresIn = &v - return s -} - -// SetInterval sets the Interval field's value. -func (s *StartDeviceAuthorizationOutput) SetInterval(v int64) *StartDeviceAuthorizationOutput { - s.Interval = &v - return s -} - -// SetUserCode sets the UserCode field's value. -func (s *StartDeviceAuthorizationOutput) SetUserCode(v string) *StartDeviceAuthorizationOutput { - s.UserCode = &v - return s -} - -// SetVerificationUri sets the VerificationUri field's value. -func (s *StartDeviceAuthorizationOutput) SetVerificationUri(v string) *StartDeviceAuthorizationOutput { - s.VerificationUri = &v - return s -} - -// SetVerificationUriComplete sets the VerificationUriComplete field's value. -func (s *StartDeviceAuthorizationOutput) SetVerificationUriComplete(v string) *StartDeviceAuthorizationOutput { - s.VerificationUriComplete = &v - return s -} - -// Indicates that the client is not currently authorized to make the request. -// This can happen when a clientId is not issued for a public client. -type UnauthorizedClientException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be unauthorized_client. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UnauthorizedClientException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UnauthorizedClientException) GoString() string { - return s.String() -} - -func newErrorUnauthorizedClientException(v protocol.ResponseMetadata) error { - return &UnauthorizedClientException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *UnauthorizedClientException) Code() string { - return "UnauthorizedClientException" -} - -// Message returns the exception's message. -func (s *UnauthorizedClientException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *UnauthorizedClientException) OrigErr() error { - return nil -} - -func (s *UnauthorizedClientException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *UnauthorizedClientException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *UnauthorizedClientException) RequestID() string { - return s.RespMetadata.RequestID -} - -// Indicates that the grant type in the request is not supported by the service. -type UnsupportedGrantTypeException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - // Single error code. For this exception the value will be unsupported_grant_type. - Error_ *string `locationName:"error" type:"string"` - - // Human-readable text providing additional information, used to assist the - // client developer in understanding the error that occurred. - Error_description *string `locationName:"error_description" type:"string"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UnsupportedGrantTypeException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s UnsupportedGrantTypeException) GoString() string { - return s.String() -} - -func newErrorUnsupportedGrantTypeException(v protocol.ResponseMetadata) error { - return &UnsupportedGrantTypeException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *UnsupportedGrantTypeException) Code() string { - return "UnsupportedGrantTypeException" -} - -// Message returns the exception's message. -func (s *UnsupportedGrantTypeException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *UnsupportedGrantTypeException) OrigErr() error { - return nil -} - -func (s *UnsupportedGrantTypeException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *UnsupportedGrantTypeException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *UnsupportedGrantTypeException) RequestID() string { - return s.RespMetadata.RequestID -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/doc.go b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/doc.go deleted file mode 100644 index 083568c61..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/doc.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package ssooidc provides the client and types for making API -// requests to AWS SSO OIDC. -// -// IAM Identity Center OpenID Connect (OIDC) is a web service that enables a -// client (such as CLI or a native application) to register with IAM Identity -// Center. The service also enables the client to fetch the user’s access -// token upon successful authentication and authorization with IAM Identity -// Center. -// -// IAM Identity Center uses the sso and identitystore API namespaces. -// -// # Considerations for Using This Guide -// -// Before you begin using this guide, we recommend that you first review the -// following important information about how the IAM Identity Center OIDC service -// works. -// -// - The IAM Identity Center OIDC service currently implements only the portions -// of the OAuth 2.0 Device Authorization Grant standard (https://tools.ietf.org/html/rfc8628 -// (https://tools.ietf.org/html/rfc8628)) that are necessary to enable single -// sign-on authentication with the CLI. -// -// - With older versions of the CLI, the service only emits OIDC access tokens, -// so to obtain a new token, users must explicitly re-authenticate. To access -// the OIDC flow that supports token refresh and doesn’t require re-authentication, -// update to the latest CLI version (1.27.10 for CLI V1 and 2.9.0 for CLI -// V2) with support for OIDC token refresh and configurable IAM Identity -// Center session durations. For more information, see Configure Amazon Web -// Services access portal session duration (https://docs.aws.amazon.com/singlesignon/latest/userguide/configure-user-session.html). -// -// - The access tokens provided by this service grant access to all Amazon -// Web Services account entitlements assigned to an IAM Identity Center user, -// not just a particular application. -// -// - The documentation in this guide does not describe the mechanism to convert -// the access token into Amazon Web Services Auth (“sigv4”) credentials -// for use with IAM-protected Amazon Web Services service endpoints. For -// more information, see GetRoleCredentials (https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html) -// in the IAM Identity Center Portal API Reference Guide. -// -// For general information about IAM Identity Center, see What is IAM Identity -// Center? (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) -// in the IAM Identity Center User Guide. -// -// See https://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10 for more information on this service. -// -// See ssooidc package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/ssooidc/ -// -// # Using the Client -// -// To contact AWS SSO OIDC with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the AWS SSO OIDC client SSOOIDC for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/ssooidc/#New -package ssooidc diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/errors.go b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/errors.go deleted file mode 100644 index cadf4584d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/errors.go +++ /dev/null @@ -1,123 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package ssooidc - -import ( - "github.com/aws/aws-sdk-go/private/protocol" -) - -const ( - - // ErrCodeAccessDeniedException for service response error code - // "AccessDeniedException". - // - // You do not have sufficient access to perform this action. - ErrCodeAccessDeniedException = "AccessDeniedException" - - // ErrCodeAuthorizationPendingException for service response error code - // "AuthorizationPendingException". - // - // Indicates that a request to authorize a client with an access user session - // token is pending. - ErrCodeAuthorizationPendingException = "AuthorizationPendingException" - - // ErrCodeExpiredTokenException for service response error code - // "ExpiredTokenException". - // - // Indicates that the token issued by the service is expired and is no longer - // valid. - ErrCodeExpiredTokenException = "ExpiredTokenException" - - // ErrCodeInternalServerException for service response error code - // "InternalServerException". - // - // Indicates that an error from the service occurred while trying to process - // a request. - ErrCodeInternalServerException = "InternalServerException" - - // ErrCodeInvalidClientException for service response error code - // "InvalidClientException". - // - // Indicates that the clientId or clientSecret in the request is invalid. For - // example, this can occur when a client sends an incorrect clientId or an expired - // clientSecret. - ErrCodeInvalidClientException = "InvalidClientException" - - // ErrCodeInvalidClientMetadataException for service response error code - // "InvalidClientMetadataException". - // - // Indicates that the client information sent in the request during registration - // is invalid. - ErrCodeInvalidClientMetadataException = "InvalidClientMetadataException" - - // ErrCodeInvalidGrantException for service response error code - // "InvalidGrantException". - // - // Indicates that a request contains an invalid grant. This can occur if a client - // makes a CreateToken request with an invalid grant type. - ErrCodeInvalidGrantException = "InvalidGrantException" - - // ErrCodeInvalidRedirectUriException for service response error code - // "InvalidRedirectUriException". - // - // Indicates that one or more redirect URI in the request is not supported for - // this operation. - ErrCodeInvalidRedirectUriException = "InvalidRedirectUriException" - - // ErrCodeInvalidRequestException for service response error code - // "InvalidRequestException". - // - // Indicates that something is wrong with the input to the request. For example, - // a required parameter might be missing or out of range. - ErrCodeInvalidRequestException = "InvalidRequestException" - - // ErrCodeInvalidRequestRegionException for service response error code - // "InvalidRequestRegionException". - // - // Indicates that a token provided as input to the request was issued by and - // is only usable by calling IAM Identity Center endpoints in another region. - ErrCodeInvalidRequestRegionException = "InvalidRequestRegionException" - - // ErrCodeInvalidScopeException for service response error code - // "InvalidScopeException". - // - // Indicates that the scope provided in the request is invalid. - ErrCodeInvalidScopeException = "InvalidScopeException" - - // ErrCodeSlowDownException for service response error code - // "SlowDownException". - // - // Indicates that the client is making the request too frequently and is more - // than the service can handle. - ErrCodeSlowDownException = "SlowDownException" - - // ErrCodeUnauthorizedClientException for service response error code - // "UnauthorizedClientException". - // - // Indicates that the client is not currently authorized to make the request. - // This can happen when a clientId is not issued for a public client. - ErrCodeUnauthorizedClientException = "UnauthorizedClientException" - - // ErrCodeUnsupportedGrantTypeException for service response error code - // "UnsupportedGrantTypeException". - // - // Indicates that the grant type in the request is not supported by the service. - ErrCodeUnsupportedGrantTypeException = "UnsupportedGrantTypeException" -) - -var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ - "AccessDeniedException": newErrorAccessDeniedException, - "AuthorizationPendingException": newErrorAuthorizationPendingException, - "ExpiredTokenException": newErrorExpiredTokenException, - "InternalServerException": newErrorInternalServerException, - "InvalidClientException": newErrorInvalidClientException, - "InvalidClientMetadataException": newErrorInvalidClientMetadataException, - "InvalidGrantException": newErrorInvalidGrantException, - "InvalidRedirectUriException": newErrorInvalidRedirectUriException, - "InvalidRequestException": newErrorInvalidRequestException, - "InvalidRequestRegionException": newErrorInvalidRequestRegionException, - "InvalidScopeException": newErrorInvalidScopeException, - "SlowDownException": newErrorSlowDownException, - "UnauthorizedClientException": newErrorUnauthorizedClientException, - "UnsupportedGrantTypeException": newErrorUnsupportedGrantTypeException, -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/service.go b/vendor/github.com/aws/aws-sdk-go/service/ssooidc/service.go deleted file mode 100644 index 782bae369..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/ssooidc/service.go +++ /dev/null @@ -1,106 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package ssooidc - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/restjson" -) - -// SSOOIDC provides the API operation methods for making requests to -// AWS SSO OIDC. See this package's package overview docs -// for details on the service. -// -// SSOOIDC methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type SSOOIDC struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "SSO OIDC" // Name of service. - EndpointsID = "oidc" // ID to lookup a service endpoint with. - ServiceID = "SSO OIDC" // ServiceID is a unique identifier of a specific service. -) - -// New creates a new instance of the SSOOIDC client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// -// mySession := session.Must(session.NewSession()) -// -// // Create a SSOOIDC client from just a session. -// svc := ssooidc.New(mySession) -// -// // Create a SSOOIDC client with additional configuration -// svc := ssooidc.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *SSOOIDC { - c := p.ClientConfig(EndpointsID, cfgs...) - if c.SigningNameDerived || len(c.SigningName) == 0 { - c.SigningName = "sso-oauth" - } - return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *SSOOIDC { - svc := &SSOOIDC{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - ServiceID: ServiceID, - SigningName: signingName, - SigningRegion: signingRegion, - PartitionID: partitionID, - Endpoint: endpoint, - APIVersion: "2019-06-10", - ResolvedRegion: resolvedRegion, - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(restjson.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed( - protocol.NewUnmarshalErrorHandler(restjson.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), - ) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a SSOOIDC operation and runs any -// custom request initialization. -func (c *SSOOIDC) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go deleted file mode 100644 index 2c395f5f6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ /dev/null @@ -1,3553 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -const opAssumeRole = "AssumeRole" - -// AssumeRoleRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRole operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRole for more information on using the AssumeRole -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the AssumeRoleRequest method. -// req, resp := client.AssumeRoleRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole -func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, output *AssumeRoleOutput) { - op := &request.Operation{ - Name: opAssumeRole, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleInput{} - } - - output = &AssumeRoleOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRole API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials that you can use to access -// Amazon Web Services resources. These temporary credentials consist of an -// access key ID, a secret access key, and a security token. Typically, you -// use AssumeRole within your account or for cross-account access. For a comparison -// of AssumeRole with other API operations that produce temporary credentials, -// see Requesting Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// # Permissions -// -// The temporary security credentials created by AssumeRole can be used to make -// API calls to any Amazon Web Services service with the following exception: -// You cannot call the Amazon Web Services STS GetFederationToken or GetSessionToken -// API operations. -// -// (Optional) You can pass inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that -// you use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's identity-based -// policy and the session policies. You can use the role's temporary credentials -// in subsequent Amazon Web Services API calls to access resources in the account -// that owns the role. You cannot use session policies to grant more permissions -// than those allowed by the identity-based policy of the role that is being -// assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. -// -// When you create a role, you create two policies: a role trust policy that -// specifies who can assume the role, and a permissions policy that specifies -// what can be done with the role. You specify the trusted principal that is -// allowed to assume the role in the role trust policy. -// -// To assume a role from a different account, your Amazon Web Services account -// must be trusted by the role. The trust relationship is defined in the role's -// trust policy when the role is created. That trust policy states which accounts -// are allowed to delegate that access to users in the account. -// -// A user who wants to access a role in a different account must also have permissions -// that are delegated from the account administrator. The administrator must -// attach a policy that allows the user to call AssumeRole for the ARN of the -// role in the other account. -// -// To allow a user to assume a role in the same account, you can do either of -// the following: -// -// - Attach a policy to the user that allows the user to call AssumeRole -// (as long as the role's trust policy trusts the account). -// -// - Add the user as a principal directly in the role's trust policy. -// -// You can do either because the role’s trust policy acts as an IAM resource-based -// policy. When a resource-based policy grants access to a principal in the -// same account, no additional identity-based policy is required. For more information -// about trust policies and resource-based policies, see IAM Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) -// in the IAM User Guide. -// -// # Tags -// -// (Optional) You can pass tag key-value pairs to your session. These tags are -// called session tags. For more information about session tags, see Passing -// Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -// -// An administrator must grant you the permissions necessary to pass session -// tags. The administrator can also create granular permissions to allow you -// to pass only specific session tags. For more information, see Tutorial: Using -// Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. -// -// You can set the session tags as transitive. Transitive tags persist during -// role chaining. For more information, see Chaining Roles with Session Tags -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. -// -// # Using MFA with AssumeRole -// -// (Optional) You can include multi-factor authentication (MFA) information -// when you call AssumeRole. This is useful for cross-account scenarios to ensure -// that the user that assumes the role has been authenticated with an Amazon -// Web Services MFA device. In that scenario, the trust policy of the role being -// assumed includes a condition that tests for MFA authentication. If the caller -// does not include valid MFA information, the request to assume the role is -// denied. The condition in a trust policy that tests for MFA authentication -// might look like the following example. -// -// "Condition": {"Bool": {"aws:MultiFactorAuthPresent": true}} -// -// For more information, see Configuring MFA-Protected API Access (https://docs.aws.amazon.com/IAM/latest/UserGuide/MFAProtectedAPI.html) -// in the IAM User Guide guide. -// -// To use MFA with AssumeRole, you pass values for the SerialNumber and TokenCode -// parameters. The SerialNumber value identifies the user's hardware or virtual -// MFA device. The TokenCode is the time-based one-time password (TOTP) that -// the MFA device produces. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRole for usage and error information. -// -// Returned Error Codes: -// -// - ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// - ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the total packed size of the session policies -// and session tags combined was too large. An Amazon Web Services conversion -// compresses the session policy document, session policy ARNs, and session -// tags into a packed binary format that has a separate limit. The error message -// indicates by percentage how close the policies and tags are to the upper -// size limit. For more information, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -// -// You could receive this error even though you meet other defined session policy -// and session tag limits. For more information, see IAM and STS Entity Character -// Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-limits-entity-length) -// in the IAM User Guide. -// -// - ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating Amazon Web Services STS in an Amazon Web Services Region -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// - ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole -func (c *STS) AssumeRole(input *AssumeRoleInput) (*AssumeRoleOutput, error) { - req, out := c.AssumeRoleRequest(input) - return out, req.Send() -} - -// AssumeRoleWithContext is the same as AssumeRole with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRole for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithContext(ctx aws.Context, input *AssumeRoleInput, opts ...request.Option) (*AssumeRoleOutput, error) { - req, out := c.AssumeRoleRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAssumeRoleWithSAML = "AssumeRoleWithSAML" - -// AssumeRoleWithSAMLRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRoleWithSAML operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRoleWithSAML for more information on using the AssumeRoleWithSAML -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the AssumeRoleWithSAMLRequest method. -// req, resp := client.AssumeRoleWithSAMLRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML -func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *request.Request, output *AssumeRoleWithSAMLOutput) { - op := &request.Operation{ - Name: opAssumeRoleWithSAML, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleWithSAMLInput{} - } - - output = &AssumeRoleWithSAMLOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - return -} - -// AssumeRoleWithSAML API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials for users who have been authenticated -// via a SAML authentication response. This operation provides a mechanism for -// tying an enterprise identity store or directory to role-based Amazon Web -// Services access without user-specific credentials or configuration. For a -// comparison of AssumeRoleWithSAML with the other API operations that produce -// temporary credentials, see Requesting Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The temporary security credentials returned by this operation consist of -// an access key ID, a secret access key, and a security token. Applications -// can use these temporary security credentials to sign calls to Amazon Web -// Services services. -// -// # Session Duration -// -// By default, the temporary security credentials created by AssumeRoleWithSAML -// last for one hour. However, you can use the optional DurationSeconds parameter -// to specify the duration of your session. Your role session lasts for the -// duration that you specify, or until the time specified in the SAML authentication -// response's SessionNotOnOrAfter value, whichever is shorter. You can provide -// a DurationSeconds value from 900 seconds (15 minutes) up to the maximum session -// duration setting for the role. This setting can have a value from 1 hour -// to 12 hours. To learn how to view the maximum value for your role, see View -// the Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you -// use the AssumeRole* API operations or the assume-role* CLI commands. However -// the limit does not apply when you use those operations to create a console -// URL. For more information, see Using IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. -// -// Role chaining (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-role-chaining) -// limits your CLI or Amazon Web Services API role session to a maximum of one -// hour. When you use the AssumeRole API operation to assume a role, you can -// specify the duration of your role session with the DurationSeconds parameter. -// You can specify a parameter value of up to 43200 seconds (12 hours), depending -// on the maximum session duration setting for your role. However, if you assume -// a role using role chaining and provide a DurationSeconds parameter value -// greater than one hour, the operation fails. -// -// # Permissions -// -// The temporary security credentials created by AssumeRoleWithSAML can be used -// to make API calls to any Amazon Web Services service with the following exception: -// you cannot call the STS GetFederationToken or GetSessionToken API operations. -// -// (Optional) You can pass inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that -// you use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's identity-based -// policy and the session policies. You can use the role's temporary credentials -// in subsequent Amazon Web Services API calls to access resources in the account -// that owns the role. You cannot use session policies to grant more permissions -// than those allowed by the identity-based policy of the role that is being -// assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. -// -// Calling AssumeRoleWithSAML does not require the use of Amazon Web Services -// security credentials. The identity of the caller is validated by using keys -// in the metadata document that is uploaded for the SAML provider entity for -// your identity provider. -// -// Calling AssumeRoleWithSAML can result in an entry in your CloudTrail logs. -// The entry includes the value in the NameID element of the SAML assertion. -// We recommend that you use a NameIDType that is not associated with any personally -// identifiable information (PII). For example, you could instead use the persistent -// identifier (urn:oasis:names:tc:SAML:2.0:nameid-format:persistent). -// -// # Tags -// -// (Optional) You can configure your IdP to pass attributes into your SAML assertion -// as session tags. Each session tag consists of a key name and an associated -// value. For more information about session tags, see Passing Session Tags -// in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -// -// You can pass up to 50 session tags. The plaintext session tag keys can’t -// exceed 128 characters and the values can’t exceed 256 characters. For these -// and additional limits, see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) -// in the IAM User Guide. -// -// An Amazon Web Services conversion compresses the passed inline session policy, -// managed policy ARNs, and session tags into a packed binary format that has -// a separate limit. Your request can fail for this limit even if your plaintext -// meets the other requirements. The PackedPolicySize response element indicates -// by percentage how close the policies and tags for your request are to the -// upper size limit. -// -// You can pass a session tag with the same key as a tag that is attached to -// the role. When you do, session tags override the role's tags with the same -// key. -// -// An administrator must grant you the permissions necessary to pass session -// tags. The administrator can also create granular permissions to allow you -// to pass only specific session tags. For more information, see Tutorial: Using -// Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. -// -// You can set the session tags as transitive. Transitive tags persist during -// role chaining. For more information, see Chaining Roles with Session Tags -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. -// -// # SAML Configuration -// -// Before your application can call AssumeRoleWithSAML, you must configure your -// SAML identity provider (IdP) to issue the claims required by Amazon Web Services. -// Additionally, you must use Identity and Access Management (IAM) to create -// a SAML provider entity in your Amazon Web Services account that represents -// your identity provider. You must also create an IAM role that specifies this -// SAML provider in its trust policy. -// -// For more information, see the following resources: -// -// - About SAML 2.0-based Federation (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) -// in the IAM User Guide. -// -// - Creating SAML Identity Providers (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) -// in the IAM User Guide. -// -// - Configuring a Relying Party and Claims (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html) -// in the IAM User Guide. -// -// - Creating a Role for SAML 2.0 Federation (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRoleWithSAML for usage and error information. -// -// Returned Error Codes: -// -// - ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// - ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the total packed size of the session policies -// and session tags combined was too large. An Amazon Web Services conversion -// compresses the session policy document, session policy ARNs, and session -// tags into a packed binary format that has a separate limit. The error message -// indicates by percentage how close the policies and tags are to the upper -// size limit. For more information, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -// -// You could receive this error even though you meet other defined session policy -// and session tag limits. For more information, see IAM and STS Entity Character -// Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-limits-entity-length) -// in the IAM User Guide. -// -// - ErrCodeIDPRejectedClaimException "IDPRejectedClaim" -// The identity provider (IdP) reported that authentication failed. This might -// be because the claim is invalid. -// -// If this error is returned for the AssumeRoleWithWebIdentity operation, it -// can also mean that the claim has expired or has been explicitly revoked. -// -// - ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" -// The web identity token that was passed could not be validated by Amazon Web -// Services. Get a new identity token from the identity provider and then retry -// the request. -// -// - ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// - ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating Amazon Web Services STS in an Amazon Web Services Region -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML -func (c *STS) AssumeRoleWithSAML(input *AssumeRoleWithSAMLInput) (*AssumeRoleWithSAMLOutput, error) { - req, out := c.AssumeRoleWithSAMLRequest(input) - return out, req.Send() -} - -// AssumeRoleWithSAMLWithContext is the same as AssumeRoleWithSAML with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRoleWithSAML for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithSAMLWithContext(ctx aws.Context, input *AssumeRoleWithSAMLInput, opts ...request.Option) (*AssumeRoleWithSAMLOutput, error) { - req, out := c.AssumeRoleWithSAMLRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity" - -// AssumeRoleWithWebIdentityRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRoleWithWebIdentity operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRoleWithWebIdentity for more information on using the AssumeRoleWithWebIdentity -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the AssumeRoleWithWebIdentityRequest method. -// req, resp := client.AssumeRoleWithWebIdentityRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity -func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityInput) (req *request.Request, output *AssumeRoleWithWebIdentityOutput) { - op := &request.Operation{ - Name: opAssumeRoleWithWebIdentity, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleWithWebIdentityInput{} - } - - output = &AssumeRoleWithWebIdentityOutput{} - req = c.newRequest(op, input, output) - req.Config.Credentials = credentials.AnonymousCredentials - return -} - -// AssumeRoleWithWebIdentity API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials for users who have been authenticated -// in a mobile or web application with a web identity provider. Example providers -// include the OAuth 2.0 providers Login with Amazon and Facebook, or any OpenID -// Connect-compatible identity provider such as Google or Amazon Cognito federated -// identities (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html). -// -// For mobile applications, we recommend that you use Amazon Cognito. You can -// use Amazon Cognito with the Amazon Web Services SDK for iOS Developer Guide -// (http://aws.amazon.com/sdkforios/) and the Amazon Web Services SDK for Android -// Developer Guide (http://aws.amazon.com/sdkforandroid/) to uniquely identify -// a user. You can also supply the user with a consistent identity throughout -// the lifetime of an application. -// -// To learn more about Amazon Cognito, see Amazon Cognito identity pools (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) -// in Amazon Cognito Developer Guide. -// -// Calling AssumeRoleWithWebIdentity does not require the use of Amazon Web -// Services security credentials. Therefore, you can distribute an application -// (for example, on mobile devices) that requests temporary security credentials -// without including long-term Amazon Web Services credentials in the application. -// You also don't need to deploy server-based proxy services that use long-term -// Amazon Web Services credentials. Instead, the identity of the caller is validated -// by using a token from the web identity provider. For a comparison of AssumeRoleWithWebIdentity -// with the other API operations that produce temporary credentials, see Requesting -// Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The temporary security credentials returned by this API consist of an access -// key ID, a secret access key, and a security token. Applications can use these -// temporary security credentials to sign calls to Amazon Web Services service -// API operations. -// -// # Session Duration -// -// By default, the temporary security credentials created by AssumeRoleWithWebIdentity -// last for one hour. However, you can use the optional DurationSeconds parameter -// to specify the duration of your session. You can provide a value from 900 -// seconds (15 minutes) up to the maximum session duration setting for the role. -// This setting can have a value from 1 hour to 12 hours. To learn how to view -// the maximum value for your role, see View the Maximum Session Duration Setting -// for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you -// use the AssumeRole* API operations or the assume-role* CLI commands. However -// the limit does not apply when you use those operations to create a console -// URL. For more information, see Using IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. -// -// # Permissions -// -// The temporary security credentials created by AssumeRoleWithWebIdentity can -// be used to make API calls to any Amazon Web Services service with the following -// exception: you cannot call the STS GetFederationToken or GetSessionToken -// API operations. -// -// (Optional) You can pass inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that -// you use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's identity-based -// policy and the session policies. You can use the role's temporary credentials -// in subsequent Amazon Web Services API calls to access resources in the account -// that owns the role. You cannot use session policies to grant more permissions -// than those allowed by the identity-based policy of the role that is being -// assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. -// -// # Tags -// -// (Optional) You can configure your IdP to pass attributes into your web identity -// token as session tags. Each session tag consists of a key name and an associated -// value. For more information about session tags, see Passing Session Tags -// in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -// -// You can pass up to 50 session tags. The plaintext session tag keys can’t -// exceed 128 characters and the values can’t exceed 256 characters. For these -// and additional limits, see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) -// in the IAM User Guide. -// -// An Amazon Web Services conversion compresses the passed inline session policy, -// managed policy ARNs, and session tags into a packed binary format that has -// a separate limit. Your request can fail for this limit even if your plaintext -// meets the other requirements. The PackedPolicySize response element indicates -// by percentage how close the policies and tags for your request are to the -// upper size limit. -// -// You can pass a session tag with the same key as a tag that is attached to -// the role. When you do, the session tag overrides the role tag with the same -// key. -// -// An administrator must grant you the permissions necessary to pass session -// tags. The administrator can also create granular permissions to allow you -// to pass only specific session tags. For more information, see Tutorial: Using -// Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. -// -// You can set the session tags as transitive. Transitive tags persist during -// role chaining. For more information, see Chaining Roles with Session Tags -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. -// -// # Identities -// -// Before your application can call AssumeRoleWithWebIdentity, you must have -// an identity token from a supported identity provider and create a role that -// the application can assume. The role that your application assumes must trust -// the identity provider that is associated with the identity token. In other -// words, the identity provider must be specified in the role's trust policy. -// -// Calling AssumeRoleWithWebIdentity can result in an entry in your CloudTrail -// logs. The entry includes the Subject (http://openid.net/specs/openid-connect-core-1_0.html#Claims) -// of the provided web identity token. We recommend that you avoid using any -// personally identifiable information (PII) in this field. For example, you -// could instead use a GUID or a pairwise identifier, as suggested in the OIDC -// specification (http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes). -// -// For more information about how to use web identity federation and the AssumeRoleWithWebIdentity -// API, see the following resources: -// -// - Using Web Identity Federation API Operations for Mobile Apps (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html) -// and Federation Through a Web-based Identity Provider (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity). -// -// - Web Identity Federation Playground (https://aws.amazon.com/blogs/aws/the-aws-web-identity-federation-playground/). -// Walk through the process of authenticating through Login with Amazon, -// Facebook, or Google, getting temporary security credentials, and then -// using those credentials to make a request to Amazon Web Services. -// -// - Amazon Web Services SDK for iOS Developer Guide (http://aws.amazon.com/sdkforios/) -// and Amazon Web Services SDK for Android Developer Guide (http://aws.amazon.com/sdkforandroid/). -// These toolkits contain sample apps that show how to invoke the identity -// providers. The toolkits then show how to use the information from these -// providers to get and use temporary security credentials. -// -// - Web Identity Federation with Mobile Applications (http://aws.amazon.com/articles/web-identity-federation-with-mobile-applications). -// This article discusses web identity federation and shows an example of -// how to use web identity federation to get access to content in Amazon -// S3. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRoleWithWebIdentity for usage and error information. -// -// Returned Error Codes: -// -// - ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// - ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the total packed size of the session policies -// and session tags combined was too large. An Amazon Web Services conversion -// compresses the session policy document, session policy ARNs, and session -// tags into a packed binary format that has a separate limit. The error message -// indicates by percentage how close the policies and tags are to the upper -// size limit. For more information, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -// -// You could receive this error even though you meet other defined session policy -// and session tag limits. For more information, see IAM and STS Entity Character -// Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-limits-entity-length) -// in the IAM User Guide. -// -// - ErrCodeIDPRejectedClaimException "IDPRejectedClaim" -// The identity provider (IdP) reported that authentication failed. This might -// be because the claim is invalid. -// -// If this error is returned for the AssumeRoleWithWebIdentity operation, it -// can also mean that the claim has expired or has been explicitly revoked. -// -// - ErrCodeIDPCommunicationErrorException "IDPCommunicationError" -// The request could not be fulfilled because the identity provider (IDP) that -// was asked to verify the incoming identity token could not be reached. This -// is often a transient error caused by network conditions. Retry the request -// a limited number of times so that you don't exceed the request rate. If the -// error persists, the identity provider might be down or not responding. -// -// - ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" -// The web identity token that was passed could not be validated by Amazon Web -// Services. Get a new identity token from the identity provider and then retry -// the request. -// -// - ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// - ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating Amazon Web Services STS in an Amazon Web Services Region -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity -func (c *STS) AssumeRoleWithWebIdentity(input *AssumeRoleWithWebIdentityInput) (*AssumeRoleWithWebIdentityOutput, error) { - req, out := c.AssumeRoleWithWebIdentityRequest(input) - return out, req.Send() -} - -// AssumeRoleWithWebIdentityWithContext is the same as AssumeRoleWithWebIdentity with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRoleWithWebIdentity for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithWebIdentityWithContext(ctx aws.Context, input *AssumeRoleWithWebIdentityInput, opts ...request.Option) (*AssumeRoleWithWebIdentityOutput, error) { - req, out := c.AssumeRoleWithWebIdentityRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage" - -// DecodeAuthorizationMessageRequest generates a "aws/request.Request" representing the -// client's request for the DecodeAuthorizationMessage operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DecodeAuthorizationMessage for more information on using the DecodeAuthorizationMessage -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the DecodeAuthorizationMessageRequest method. -// req, resp := client.DecodeAuthorizationMessageRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage -func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessageInput) (req *request.Request, output *DecodeAuthorizationMessageOutput) { - op := &request.Operation{ - Name: opDecodeAuthorizationMessage, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DecodeAuthorizationMessageInput{} - } - - output = &DecodeAuthorizationMessageOutput{} - req = c.newRequest(op, input, output) - return -} - -// DecodeAuthorizationMessage API operation for AWS Security Token Service. -// -// Decodes additional information about the authorization status of a request -// from an encoded message returned in response to an Amazon Web Services request. -// -// For example, if a user is not authorized to perform an operation that he -// or she has requested, the request returns a Client.UnauthorizedOperation -// response (an HTTP 403 response). Some Amazon Web Services operations additionally -// return an encoded message that can provide details about this authorization -// failure. -// -// Only certain Amazon Web Services operations return an encoded authorization -// message. The documentation for an individual operation indicates whether -// that operation returns an encoded message in addition to returning an HTTP -// code. -// -// The message is encoded because the details of the authorization status can -// contain privileged information that the user who requested the operation -// should not see. To decode an authorization status message, a user must be -// granted permissions through an IAM policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) -// to request the DecodeAuthorizationMessage (sts:DecodeAuthorizationMessage) -// action. -// -// The decoded message includes the following type of information: -// -// - Whether the request was denied due to an explicit deny or due to the -// absence of an explicit allow. For more information, see Determining Whether -// a Request is Allowed or Denied (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow) -// in the IAM User Guide. -// -// - The principal who made the request. -// -// - The requested action. -// -// - The requested resource. -// -// - The values of condition keys in the context of the user's request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation DecodeAuthorizationMessage for usage and error information. -// -// Returned Error Codes: -// - ErrCodeInvalidAuthorizationMessageException "InvalidAuthorizationMessageException" -// The error returned if the message passed to DecodeAuthorizationMessage was -// invalid. This can happen if the token contains invalid characters, such as -// linebreaks. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage -func (c *STS) DecodeAuthorizationMessage(input *DecodeAuthorizationMessageInput) (*DecodeAuthorizationMessageOutput, error) { - req, out := c.DecodeAuthorizationMessageRequest(input) - return out, req.Send() -} - -// DecodeAuthorizationMessageWithContext is the same as DecodeAuthorizationMessage with the addition of -// the ability to pass a context and additional request options. -// -// See DecodeAuthorizationMessage for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) DecodeAuthorizationMessageWithContext(ctx aws.Context, input *DecodeAuthorizationMessageInput, opts ...request.Option) (*DecodeAuthorizationMessageOutput, error) { - req, out := c.DecodeAuthorizationMessageRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetAccessKeyInfo = "GetAccessKeyInfo" - -// GetAccessKeyInfoRequest generates a "aws/request.Request" representing the -// client's request for the GetAccessKeyInfo operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetAccessKeyInfo for more information on using the GetAccessKeyInfo -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetAccessKeyInfoRequest method. -// req, resp := client.GetAccessKeyInfoRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetAccessKeyInfo -func (c *STS) GetAccessKeyInfoRequest(input *GetAccessKeyInfoInput) (req *request.Request, output *GetAccessKeyInfoOutput) { - op := &request.Operation{ - Name: opGetAccessKeyInfo, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetAccessKeyInfoInput{} - } - - output = &GetAccessKeyInfoOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetAccessKeyInfo API operation for AWS Security Token Service. -// -// Returns the account identifier for the specified access key ID. -// -// Access keys consist of two parts: an access key ID (for example, AKIAIOSFODNN7EXAMPLE) -// and a secret access key (for example, wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY). -// For more information about access keys, see Managing Access Keys for IAM -// Users (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) -// in the IAM User Guide. -// -// When you pass an access key ID to this operation, it returns the ID of the -// Amazon Web Services account to which the keys belong. Access key IDs beginning -// with AKIA are long-term credentials for an IAM user or the Amazon Web Services -// account root user. Access key IDs beginning with ASIA are temporary credentials -// that are created using STS operations. If the account in the response belongs -// to you, you can sign in as the root user and review your root user access -// keys. Then, you can pull a credentials report (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html) -// to learn which IAM user owns the keys. To learn who requested the temporary -// credentials for an ASIA access key, view the STS events in your CloudTrail -// logs (https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html) -// in the IAM User Guide. -// -// This operation does not indicate the state of the access key. The key might -// be active, inactive, or deleted. Active keys might not have permissions to -// perform an operation. Providing a deleted access key might return an error -// that the key doesn't exist. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetAccessKeyInfo for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetAccessKeyInfo -func (c *STS) GetAccessKeyInfo(input *GetAccessKeyInfoInput) (*GetAccessKeyInfoOutput, error) { - req, out := c.GetAccessKeyInfoRequest(input) - return out, req.Send() -} - -// GetAccessKeyInfoWithContext is the same as GetAccessKeyInfo with the addition of -// the ability to pass a context and additional request options. -// -// See GetAccessKeyInfo for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetAccessKeyInfoWithContext(ctx aws.Context, input *GetAccessKeyInfoInput, opts ...request.Option) (*GetAccessKeyInfoOutput, error) { - req, out := c.GetAccessKeyInfoRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetCallerIdentity = "GetCallerIdentity" - -// GetCallerIdentityRequest generates a "aws/request.Request" representing the -// client's request for the GetCallerIdentity operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetCallerIdentity for more information on using the GetCallerIdentity -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetCallerIdentityRequest method. -// req, resp := client.GetCallerIdentityRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity -func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *request.Request, output *GetCallerIdentityOutput) { - op := &request.Operation{ - Name: opGetCallerIdentity, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetCallerIdentityInput{} - } - - output = &GetCallerIdentityOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetCallerIdentity API operation for AWS Security Token Service. -// -// Returns details about the IAM user or role whose credentials are used to -// call the operation. -// -// No permissions are required to perform this operation. If an administrator -// attaches a policy to your identity that explicitly denies access to the sts:GetCallerIdentity -// action, you can still perform this operation. Permissions are not required -// because the same information is returned when access is denied. To view an -// example response, see I Am Not Authorized to Perform: iam:DeleteVirtualMFADevice -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_access-denied-delete-mfa) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetCallerIdentity for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity -func (c *STS) GetCallerIdentity(input *GetCallerIdentityInput) (*GetCallerIdentityOutput, error) { - req, out := c.GetCallerIdentityRequest(input) - return out, req.Send() -} - -// GetCallerIdentityWithContext is the same as GetCallerIdentity with the addition of -// the ability to pass a context and additional request options. -// -// See GetCallerIdentity for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetCallerIdentityWithContext(ctx aws.Context, input *GetCallerIdentityInput, opts ...request.Option) (*GetCallerIdentityOutput, error) { - req, out := c.GetCallerIdentityRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetFederationToken = "GetFederationToken" - -// GetFederationTokenRequest generates a "aws/request.Request" representing the -// client's request for the GetFederationToken operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetFederationToken for more information on using the GetFederationToken -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetFederationTokenRequest method. -// req, resp := client.GetFederationTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken -func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *request.Request, output *GetFederationTokenOutput) { - op := &request.Operation{ - Name: opGetFederationToken, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetFederationTokenInput{} - } - - output = &GetFederationTokenOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetFederationToken API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) for a user. A typical -// use is in a proxy application that gets temporary security credentials on -// behalf of distributed applications inside a corporate network. -// -// You must call the GetFederationToken operation using the long-term security -// credentials of an IAM user. As a result, this call is appropriate in contexts -// where those credentials can be safeguarded, usually in a server-based application. -// For a comparison of GetFederationToken with the other API operations that -// produce temporary credentials, see Requesting Temporary Security Credentials -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// Although it is possible to call GetFederationToken using the security credentials -// of an Amazon Web Services account root user rather than an IAM user that -// you create for the purpose of a proxy application, we do not recommend it. -// For more information, see Safeguard your root user credentials and don't -// use them for everyday tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) -// in the IAM User Guide. -// -// You can create a mobile-based or browser-based app that can authenticate -// users using a web identity provider like Login with Amazon, Facebook, Google, -// or an OpenID Connect-compatible identity provider. In this case, we recommend -// that you use Amazon Cognito (http://aws.amazon.com/cognito/) or AssumeRoleWithWebIdentity. -// For more information, see Federation Through a Web-based Identity Provider -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) -// in the IAM User Guide. -// -// # Session duration -// -// The temporary credentials are valid for the specified duration, from 900 -// seconds (15 minutes) up to a maximum of 129,600 seconds (36 hours). The default -// session duration is 43,200 seconds (12 hours). Temporary credentials obtained -// by using the root user credentials have a maximum duration of 3,600 seconds -// (1 hour). -// -// # Permissions -// -// You can use the temporary credentials created by GetFederationToken in any -// Amazon Web Services service with the following exceptions: -// -// - You cannot call any IAM operations using the CLI or the Amazon Web Services -// API. This limitation does not apply to console sessions. -// -// - You cannot call any STS operations except GetCallerIdentity. -// -// You can use temporary credentials for single sign-on (SSO) to the console. -// -// You must pass an inline or managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that -// you use for both inline and managed session policies can't exceed 2,048 characters. -// -// Though the session policy parameters are optional, if you do not pass a policy, -// then the resulting federated user session has no permissions. When you pass -// session policies, the session permissions are the intersection of the IAM -// user policies and the session policies that you pass. This gives you a way -// to further restrict the permissions for a federated user. You cannot use -// session policies to grant more permissions than those that are defined in -// the permissions policy of the IAM user. For more information, see Session -// Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. For information about using GetFederationToken to -// create temporary security credentials, see GetFederationToken—Federation -// Through a Custom Identity Broker (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken). -// -// You can use the credentials to access a resource that has a resource-based -// policy. If that policy specifically references the federated user session -// in the Principal element of the policy, the session has the permissions allowed -// by the policy. These permissions are granted in addition to the permissions -// granted by the session policies. -// -// # Tags -// -// (Optional) You can pass tag key-value pairs to your session. These are called -// session tags. For more information about session tags, see Passing Session -// Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -// -// You can create a mobile-based or browser-based app that can authenticate -// users using a web identity provider like Login with Amazon, Facebook, Google, -// or an OpenID Connect-compatible identity provider. In this case, we recommend -// that you use Amazon Cognito (http://aws.amazon.com/cognito/) or AssumeRoleWithWebIdentity. -// For more information, see Federation Through a Web-based Identity Provider -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) -// in the IAM User Guide. -// -// An administrator must grant you the permissions necessary to pass session -// tags. The administrator can also create granular permissions to allow you -// to pass only specific session tags. For more information, see Tutorial: Using -// Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. -// -// Tag key–value pairs are not case sensitive, but case is preserved. This -// means that you cannot have separate Department and department tag keys. Assume -// that the user that you are federating has the Department=Marketing tag and -// you pass the department=engineering session tag. Department and department -// are not saved as separate tags, and the session tag passed in the request -// takes precedence over the user tag. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetFederationToken for usage and error information. -// -// Returned Error Codes: -// -// - ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// - ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the total packed size of the session policies -// and session tags combined was too large. An Amazon Web Services conversion -// compresses the session policy document, session policy ARNs, and session -// tags into a packed binary format that has a separate limit. The error message -// indicates by percentage how close the policies and tags are to the upper -// size limit. For more information, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -// -// You could receive this error even though you meet other defined session policy -// and session tag limits. For more information, see IAM and STS Entity Character -// Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-limits-entity-length) -// in the IAM User Guide. -// -// - ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating Amazon Web Services STS in an Amazon Web Services Region -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken -func (c *STS) GetFederationToken(input *GetFederationTokenInput) (*GetFederationTokenOutput, error) { - req, out := c.GetFederationTokenRequest(input) - return out, req.Send() -} - -// GetFederationTokenWithContext is the same as GetFederationToken with the addition of -// the ability to pass a context and additional request options. -// -// See GetFederationToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetFederationTokenWithContext(ctx aws.Context, input *GetFederationTokenInput, opts ...request.Option) (*GetFederationTokenOutput, error) { - req, out := c.GetFederationTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetSessionToken = "GetSessionToken" - -// GetSessionTokenRequest generates a "aws/request.Request" representing the -// client's request for the GetSessionToken operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetSessionToken for more information on using the GetSessionToken -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// // Example sending a request using the GetSessionTokenRequest method. -// req, resp := client.GetSessionTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken -func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request.Request, output *GetSessionTokenOutput) { - op := &request.Operation{ - Name: opGetSessionToken, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetSessionTokenInput{} - } - - output = &GetSessionTokenOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetSessionToken API operation for AWS Security Token Service. -// -// Returns a set of temporary credentials for an Amazon Web Services account -// or IAM user. The credentials consist of an access key ID, a secret access -// key, and a security token. Typically, you use GetSessionToken if you want -// to use MFA to protect programmatic calls to specific Amazon Web Services -// API operations like Amazon EC2 StopInstances. -// -// MFA-enabled IAM users must call GetSessionToken and submit an MFA code that -// is associated with their MFA device. Using the temporary security credentials -// that the call returns, IAM users can then make programmatic calls to API -// operations that require MFA authentication. An incorrect MFA code causes -// the API to return an access denied error. For a comparison of GetSessionToken -// with the other API operations that produce temporary credentials, see Requesting -// Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// No permissions are required for users to perform this operation. The purpose -// of the sts:GetSessionToken operation is to authenticate the user using MFA. -// You cannot use policies to control authentication operations. For more information, -// see Permissions for GetSessionToken (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getsessiontoken.html) -// in the IAM User Guide. -// -// # Session Duration -// -// The GetSessionToken operation must be called by using the long-term Amazon -// Web Services security credentials of an IAM user. Credentials that are created -// by IAM users are valid for the duration that you specify. This duration can -// range from 900 seconds (15 minutes) up to a maximum of 129,600 seconds (36 -// hours), with a default of 43,200 seconds (12 hours). Credentials based on -// account credentials can range from 900 seconds (15 minutes) up to 3,600 seconds -// (1 hour), with a default of 1 hour. -// -// # Permissions -// -// The temporary security credentials created by GetSessionToken can be used -// to make API calls to any Amazon Web Services service with the following exceptions: -// -// - You cannot call any IAM API operations unless MFA authentication information -// is included in the request. -// -// - You cannot call any STS API except AssumeRole or GetCallerIdentity. -// -// The credentials that GetSessionToken returns are based on permissions associated -// with the IAM user whose credentials were used to call the operation. The -// temporary credentials have the same permissions as the IAM user. -// -// Although it is possible to call GetSessionToken using the security credentials -// of an Amazon Web Services account root user rather than an IAM user, we do -// not recommend it. If GetSessionToken is called using root user credentials, -// the temporary credentials have root user permissions. For more information, -// see Safeguard your root user credentials and don't use them for everyday -// tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) -// in the IAM User Guide -// -// For more information about using GetSessionToken to create temporary credentials, -// see Temporary Credentials for Users in Untrusted Environments (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetSessionToken for usage and error information. -// -// Returned Error Codes: -// - ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating Amazon Web Services STS in an Amazon Web Services Region -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken -func (c *STS) GetSessionToken(input *GetSessionTokenInput) (*GetSessionTokenOutput, error) { - req, out := c.GetSessionTokenRequest(input) - return out, req.Send() -} - -// GetSessionTokenWithContext is the same as GetSessionToken with the addition of -// the ability to pass a context and additional request options. -// -// See GetSessionToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetSessionTokenWithContext(ctx aws.Context, input *GetSessionTokenInput, opts ...request.Option) (*GetSessionTokenOutput, error) { - req, out := c.GetSessionTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type AssumeRoleInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. The value specified can range - // from 900 seconds (15 minutes) up to the maximum session duration set for - // the role. The maximum session duration setting can have a value from 1 hour - // to 12 hours. If you specify a value higher than this setting or the administrator - // setting (whichever is lower), the operation fails. For example, if you specify - // a session duration of 12 hours, but your administrator set the maximum session - // duration to 6 hours, your operation fails. - // - // Role chaining limits your Amazon Web Services CLI or Amazon Web Services - // API role session to a maximum of one hour. When you use the AssumeRole API - // operation to assume a role, you can specify the duration of your role session - // with the DurationSeconds parameter. You can specify a parameter value of - // up to 43200 seconds (12 hours), depending on the maximum session duration - // setting for your role. However, if you assume a role using role chaining - // and provide a DurationSeconds parameter value greater than one hour, the - // operation fails. To learn how to view the maximum value for your role, see - // View the Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. - // - // By default, the value is set to 3600 seconds. - // - // The DurationSeconds parameter is separate from the duration of a console - // session that you might request using the returned credentials. The request - // to the federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // A unique identifier that might be required when you assume a role in another - // account. If the administrator of the account to which the role belongs provided - // you with an external ID, then provide that value in the ExternalId parameter. - // This value can be any string, such as a passphrase or account number. A cross-account - // role is usually set up to trust everyone in an account. Therefore, the administrator - // of the trusting account might send an external ID to the administrator of - // the trusted account. That way, only someone with the ID can assume the role, - // rather than everyone in the account. For more information about the external - // ID, see How to Use an External ID When Granting Access to Your Amazon Web - // Services Resources to a Third Party (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html) - // in the IAM User Guide. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@:/- - ExternalId *string `min:"2" type:"string"` - - // An IAM policy in JSON format that you want to use as an inline session policy. - // - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use - // the role's temporary credentials in subsequent Amazon Web Services API calls - // to access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - // - // The plaintext that you use for both inline and managed session policies can't - // exceed 2,048 characters. The JSON policy characters can be any ASCII character - // from the space character to the end of the valid character list (\u0020 through - // \u00FF). It can also include the tab (\u0009), linefeed (\u000A), and carriage - // return (\u000D) characters. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - Policy *string `min:"1" type:"string"` - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want - // to use as managed session policies. The policies must exist in the same account - // as the role. - // - // This parameter is optional. You can provide up to 10 managed policy ARNs. - // However, the plaintext that you use for both inline and managed session policies - // can't exceed 2,048 characters. For more information about ARNs, see Amazon - // Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - // - // Passing policies to this operation returns new temporary credentials. The - // resulting session's permissions are the intersection of the role's identity-based - // policy and the session policies. You can use the role's temporary credentials - // in subsequent Amazon Web Services API calls to access resources in the account - // that owns the role. You cannot use session policies to grant more permissions - // than those allowed by the identity-based policy of the role that is being - // assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []*PolicyDescriptorType `type:"list"` - - // A list of previously acquired trusted context assertions in the format of - // a JSON array. The trusted context assertion is signed and encrypted by Amazon - // Web Services STS. - // - // The following is an example of a ProvidedContext value that includes a single - // trusted context assertion and the ARN of the context provider from which - // the trusted context assertion was generated. - // - // [{"ProviderArn":"arn:aws:iam::aws:contextProvider/IdentityCenter","ContextAssertion":"trusted-context-assertion"}] - ProvidedContexts []*ProvidedContext `type:"list"` - - // The Amazon Resource Name (ARN) of the role to assume. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // An identifier for the assumed role session. - // - // Use the role session name to uniquely identify a session when the same role - // is assumed by different principals or for different reasons. In cross-account - // scenarios, the role session name is visible to, and can be logged by the - // account that owns the role. The role session name is also used in the ARN - // of the assumed role principal. This means that subsequent cross-account API - // requests that use the temporary security credentials will expose the role - // session name to the external account in their CloudTrail logs. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // RoleSessionName is a required field - RoleSessionName *string `min:"2" type:"string" required:"true"` - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy - // of the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as GAHT12345678) - // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - SerialNumber *string `min:"9" type:"string"` - - // The source identity specified by the principal that is calling the AssumeRole - // operation. - // - // You can require users to specify a source identity when they assume a role. - // You do this by using the sts:SourceIdentity condition key in a role trust - // policy. You can use source identity information in CloudTrail logs to determine - // who took actions with a role. You can use the aws:SourceIdentity condition - // key to further control access to Amazon Web Services resources based on the - // value of source identity. For more information about using source identity, - // see Monitor and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@-. You cannot - // use a value that begins with the text aws:. This prefix is reserved for Amazon - // Web Services internal use. - SourceIdentity *string `min:"2" type:"string"` - - // A list of session tags that you want to pass. Each session tag consists of - // a key name and an associated value. For more information about session tags, - // see Tagging Amazon Web Services STS Sessions (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) - // in the IAM User Guide. - // - // This parameter is optional. You can pass up to 50 session tags. The plaintext - // session tag keys can’t exceed 128 characters, and the values can’t exceed - // 256 characters. For these and additional limits, see IAM and STS Character - // Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - // - // You can pass a session tag with the same key as a tag that is already attached - // to the role. When you do, session tags override a role tag with the same - // key. - // - // Tag key–value pairs are not case sensitive, but case is preserved. This - // means that you cannot have separate Department and department tag keys. Assume - // that the role has the Department=Marketing tag and you pass the department=engineering - // session tag. Department and department are not saved as separate tags, and - // the session tag passed in the request takes precedence over the role tag. - // - // Additionally, if you used temporary credentials to perform this operation, - // the new session inherits any transitive session tags from the calling session. - // If you pass a session tag with the same key as an inherited tag, the operation - // fails. To view the inherited tags for a session, see the CloudTrail logs. - // For more information, see Viewing Session Tags in CloudTrail (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_ctlogs) - // in the IAM User Guide. - Tags []*Tag `type:"list"` - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA. (In other words, if the policy includes a condition - // that tests for MFA). If the role being assumed requires MFA and if the TokenCode - // value is missing or expired, the AssumeRole call returns an "access denied" - // error. - // - // The format for this parameter, as described by its regex pattern, is a sequence - // of six numeric digits. - TokenCode *string `min:"6" type:"string"` - - // A list of keys for session tags that you want to set as transitive. If you - // set a tag key as transitive, the corresponding key and value passes to subsequent - // sessions in a role chain. For more information, see Chaining Roles with Session - // Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) - // in the IAM User Guide. - // - // This parameter is optional. When you set session tags as transitive, the - // session policy and session tags packed binary limit is not affected. - // - // If you choose not to specify a transitive tag key, then no tags are passed - // from this session to any subsequent sessions. - TransitiveTagKeys []*string `type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.ExternalId != nil && len(*s.ExternalId) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ExternalId", 2)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.RoleSessionName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleSessionName")) - } - if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2)) - } - if s.SerialNumber != nil && len(*s.SerialNumber) < 9 { - invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9)) - } - if s.SourceIdentity != nil && len(*s.SourceIdentity) < 2 { - invalidParams.Add(request.NewErrParamMinLen("SourceIdentity", 2)) - } - if s.TokenCode != nil && len(*s.TokenCode) < 6 { - invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6)) - } - if s.PolicyArns != nil { - for i, v := range s.PolicyArns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PolicyArns", i), err.(request.ErrInvalidParams)) - } - } - } - if s.ProvidedContexts != nil { - for i, v := range s.ProvidedContexts { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ProvidedContexts", i), err.(request.ErrInvalidParams)) - } - } - } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleInput) SetDurationSeconds(v int64) *AssumeRoleInput { - s.DurationSeconds = &v - return s -} - -// SetExternalId sets the ExternalId field's value. -func (s *AssumeRoleInput) SetExternalId(v string) *AssumeRoleInput { - s.ExternalId = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleInput) SetPolicy(v string) *AssumeRoleInput { - s.Policy = &v - return s -} - -// SetPolicyArns sets the PolicyArns field's value. -func (s *AssumeRoleInput) SetPolicyArns(v []*PolicyDescriptorType) *AssumeRoleInput { - s.PolicyArns = v - return s -} - -// SetProvidedContexts sets the ProvidedContexts field's value. -func (s *AssumeRoleInput) SetProvidedContexts(v []*ProvidedContext) *AssumeRoleInput { - s.ProvidedContexts = v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleInput) SetRoleArn(v string) *AssumeRoleInput { - s.RoleArn = &v - return s -} - -// SetRoleSessionName sets the RoleSessionName field's value. -func (s *AssumeRoleInput) SetRoleSessionName(v string) *AssumeRoleInput { - s.RoleSessionName = &v - return s -} - -// SetSerialNumber sets the SerialNumber field's value. -func (s *AssumeRoleInput) SetSerialNumber(v string) *AssumeRoleInput { - s.SerialNumber = &v - return s -} - -// SetSourceIdentity sets the SourceIdentity field's value. -func (s *AssumeRoleInput) SetSourceIdentity(v string) *AssumeRoleInput { - s.SourceIdentity = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *AssumeRoleInput) SetTags(v []*Tag) *AssumeRoleInput { - s.Tags = v - return s -} - -// SetTokenCode sets the TokenCode field's value. -func (s *AssumeRoleInput) SetTokenCode(v string) *AssumeRoleInput { - s.TokenCode = &v - return s -} - -// SetTransitiveTagKeys sets the TransitiveTagKeys field's value. -func (s *AssumeRoleInput) SetTransitiveTagKeys(v []*string) *AssumeRoleInput { - s.TransitiveTagKeys = v - return s -} - -// Contains the response to a successful AssumeRole request, including temporary -// Amazon Web Services credentials that can be used to make Amazon Web Services -// requests. -type AssumeRoleOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. - // For example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName - // that you specified when you called AssumeRole. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // The size of the security token that STS API operations return is not fixed. - // We strongly recommend that you make no assumptions about the maximum size. - Credentials *Credentials `type:"structure"` - - // A percentage value that indicates the packed size of the session policies - // and session tags combined passed in the request. The request fails if the - // packed size is greater than 100 percent, which means the policies and tags - // exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // The source identity specified by the principal that is calling the AssumeRole - // operation. - // - // You can require users to specify a source identity when they assume a role. - // You do this by using the sts:SourceIdentity condition key in a role trust - // policy. You can use source identity information in CloudTrail logs to determine - // who took actions with a role. You can use the aws:SourceIdentity condition - // key to further control access to Amazon Web Services resources based on the - // value of source identity. For more information about using source identity, - // see Monitor and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - SourceIdentity *string `min:"2" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleOutput { - s.AssumedRoleUser = v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleOutput) SetCredentials(v *Credentials) *AssumeRoleOutput { - s.Credentials = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleOutput) SetPackedPolicySize(v int64) *AssumeRoleOutput { - s.PackedPolicySize = &v - return s -} - -// SetSourceIdentity sets the SourceIdentity field's value. -func (s *AssumeRoleOutput) SetSourceIdentity(v string) *AssumeRoleOutput { - s.SourceIdentity = &v - return s -} - -type AssumeRoleWithSAMLInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. Your role session lasts for - // the duration that you specify for the DurationSeconds parameter, or until - // the time specified in the SAML authentication response's SessionNotOnOrAfter - // value, whichever is shorter. You can provide a DurationSeconds value from - // 900 seconds (15 minutes) up to the maximum session duration setting for the - // role. This setting can have a value from 1 hour to 12 hours. If you specify - // a value higher than this setting, the operation fails. For example, if you - // specify a session duration of 12 hours, but your administrator set the maximum - // session duration to 6 hours, your operation fails. To learn how to view the - // maximum value for your role, see View the Maximum Session Duration Setting - // for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. - // - // By default, the value is set to 3600 seconds. - // - // The DurationSeconds parameter is separate from the duration of a console - // session that you might request using the returned credentials. The request - // to the federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // An IAM policy in JSON format that you want to use as an inline session policy. - // - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use - // the role's temporary credentials in subsequent Amazon Web Services API calls - // to access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - // - // The plaintext that you use for both inline and managed session policies can't - // exceed 2,048 characters. The JSON policy characters can be any ASCII character - // from the space character to the end of the valid character list (\u0020 through - // \u00FF). It can also include the tab (\u0009), linefeed (\u000A), and carriage - // return (\u000D) characters. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - Policy *string `min:"1" type:"string"` - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want - // to use as managed session policies. The policies must exist in the same account - // as the role. - // - // This parameter is optional. You can provide up to 10 managed policy ARNs. - // However, the plaintext that you use for both inline and managed session policies - // can't exceed 2,048 characters. For more information about ARNs, see Amazon - // Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - // - // Passing policies to this operation returns new temporary credentials. The - // resulting session's permissions are the intersection of the role's identity-based - // policy and the session policies. You can use the role's temporary credentials - // in subsequent Amazon Web Services API calls to access resources in the account - // that owns the role. You cannot use session policies to grant more permissions - // than those allowed by the identity-based policy of the role that is being - // assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []*PolicyDescriptorType `type:"list"` - - // The Amazon Resource Name (ARN) of the SAML provider in IAM that describes - // the IdP. - // - // PrincipalArn is a required field - PrincipalArn *string `min:"20" type:"string" required:"true"` - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // The base64 encoded SAML authentication response provided by the IdP. - // - // For more information, see Configuring a Relying Party and Adding Claims (https://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html) - // in the IAM User Guide. - // - // SAMLAssertion is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by AssumeRoleWithSAMLInput's - // String and GoString methods. - // - // SAMLAssertion is a required field - SAMLAssertion *string `min:"4" type:"string" required:"true" sensitive:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleWithSAMLInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleWithSAMLInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleWithSAMLInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithSAMLInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.PrincipalArn == nil { - invalidParams.Add(request.NewErrParamRequired("PrincipalArn")) - } - if s.PrincipalArn != nil && len(*s.PrincipalArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("PrincipalArn", 20)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.SAMLAssertion == nil { - invalidParams.Add(request.NewErrParamRequired("SAMLAssertion")) - } - if s.SAMLAssertion != nil && len(*s.SAMLAssertion) < 4 { - invalidParams.Add(request.NewErrParamMinLen("SAMLAssertion", 4)) - } - if s.PolicyArns != nil { - for i, v := range s.PolicyArns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PolicyArns", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleWithSAMLInput) SetDurationSeconds(v int64) *AssumeRoleWithSAMLInput { - s.DurationSeconds = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleWithSAMLInput) SetPolicy(v string) *AssumeRoleWithSAMLInput { - s.Policy = &v - return s -} - -// SetPolicyArns sets the PolicyArns field's value. -func (s *AssumeRoleWithSAMLInput) SetPolicyArns(v []*PolicyDescriptorType) *AssumeRoleWithSAMLInput { - s.PolicyArns = v - return s -} - -// SetPrincipalArn sets the PrincipalArn field's value. -func (s *AssumeRoleWithSAMLInput) SetPrincipalArn(v string) *AssumeRoleWithSAMLInput { - s.PrincipalArn = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleWithSAMLInput) SetRoleArn(v string) *AssumeRoleWithSAMLInput { - s.RoleArn = &v - return s -} - -// SetSAMLAssertion sets the SAMLAssertion field's value. -func (s *AssumeRoleWithSAMLInput) SetSAMLAssertion(v string) *AssumeRoleWithSAMLInput { - s.SAMLAssertion = &v - return s -} - -// Contains the response to a successful AssumeRoleWithSAML request, including -// temporary Amazon Web Services credentials that can be used to make Amazon -// Web Services requests. -type AssumeRoleWithSAMLOutput struct { - _ struct{} `type:"structure"` - - // The identifiers for the temporary security credentials that the operation - // returns. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The value of the Recipient attribute of the SubjectConfirmationData element - // of the SAML assertion. - Audience *string `type:"string"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // The size of the security token that STS API operations return is not fixed. - // We strongly recommend that you make no assumptions about the maximum size. - Credentials *Credentials `type:"structure"` - - // The value of the Issuer element of the SAML assertion. - Issuer *string `type:"string"` - - // A hash value based on the concatenation of the following: - // - // * The Issuer response value. - // - // * The Amazon Web Services account ID. - // - // * The friendly name (the last part of the ARN) of the SAML provider in - // IAM. - // - // The combination of NameQualifier and Subject can be used to uniquely identify - // a user. - // - // The following pseudocode shows how the hash value is calculated: - // - // BASE64 ( SHA1 ( "https://example.com/saml" + "123456789012" + "/MySAMLIdP" - // ) ) - NameQualifier *string `type:"string"` - - // A percentage value that indicates the packed size of the session policies - // and session tags combined passed in the request. The request fails if the - // packed size is greater than 100 percent, which means the policies and tags - // exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // The value in the SourceIdentity attribute in the SAML assertion. - // - // You can require users to set a source identity value when they assume a role. - // You do this by using the sts:SourceIdentity condition key in a role trust - // policy. That way, actions that are taken with the role are associated with - // that user. After the source identity is set, the value cannot be changed. - // It is present in the request for all actions that are taken by the role and - // persists across chained role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts#iam-term-role-chaining) - // sessions. You can configure your SAML identity provider to use an attribute - // associated with your users, like user name or email, as the source identity - // when calling AssumeRoleWithSAML. You do this by adding an attribute to the - // SAML assertion. For more information about using source identity, see Monitor - // and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - SourceIdentity *string `min:"2" type:"string"` - - // The value of the NameID element in the Subject element of the SAML assertion. - Subject *string `type:"string"` - - // The format of the name ID, as defined by the Format attribute in the NameID - // element of the SAML assertion. Typical examples of the format are transient - // or persistent. - // - // If the format includes the prefix urn:oasis:names:tc:SAML:2.0:nameid-format, - // that prefix is removed. For example, urn:oasis:names:tc:SAML:2.0:nameid-format:transient - // is returned as transient. If the format includes any other prefix, the format - // is returned with no modifications. - SubjectType *string `type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleWithSAMLOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleWithSAMLOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleWithSAMLOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleWithSAMLOutput { - s.AssumedRoleUser = v - return s -} - -// SetAudience sets the Audience field's value. -func (s *AssumeRoleWithSAMLOutput) SetAudience(v string) *AssumeRoleWithSAMLOutput { - s.Audience = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleWithSAMLOutput) SetCredentials(v *Credentials) *AssumeRoleWithSAMLOutput { - s.Credentials = v - return s -} - -// SetIssuer sets the Issuer field's value. -func (s *AssumeRoleWithSAMLOutput) SetIssuer(v string) *AssumeRoleWithSAMLOutput { - s.Issuer = &v - return s -} - -// SetNameQualifier sets the NameQualifier field's value. -func (s *AssumeRoleWithSAMLOutput) SetNameQualifier(v string) *AssumeRoleWithSAMLOutput { - s.NameQualifier = &v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleWithSAMLOutput) SetPackedPolicySize(v int64) *AssumeRoleWithSAMLOutput { - s.PackedPolicySize = &v - return s -} - -// SetSourceIdentity sets the SourceIdentity field's value. -func (s *AssumeRoleWithSAMLOutput) SetSourceIdentity(v string) *AssumeRoleWithSAMLOutput { - s.SourceIdentity = &v - return s -} - -// SetSubject sets the Subject field's value. -func (s *AssumeRoleWithSAMLOutput) SetSubject(v string) *AssumeRoleWithSAMLOutput { - s.Subject = &v - return s -} - -// SetSubjectType sets the SubjectType field's value. -func (s *AssumeRoleWithSAMLOutput) SetSubjectType(v string) *AssumeRoleWithSAMLOutput { - s.SubjectType = &v - return s -} - -type AssumeRoleWithWebIdentityInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) up to the maximum session duration setting for the role. - // This setting can have a value from 1 hour to 12 hours. If you specify a value - // higher than this setting, the operation fails. For example, if you specify - // a session duration of 12 hours, but your administrator set the maximum session - // duration to 6 hours, your operation fails. To learn how to view the maximum - // value for your role, see View the Maximum Session Duration Setting for a - // Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. - // - // By default, the value is set to 3600 seconds. - // - // The DurationSeconds parameter is separate from the duration of a console - // session that you might request using the returned credentials. The request - // to the federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // An IAM policy in JSON format that you want to use as an inline session policy. - // - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use - // the role's temporary credentials in subsequent Amazon Web Services API calls - // to access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - // - // The plaintext that you use for both inline and managed session policies can't - // exceed 2,048 characters. The JSON policy characters can be any ASCII character - // from the space character to the end of the valid character list (\u0020 through - // \u00FF). It can also include the tab (\u0009), linefeed (\u000A), and carriage - // return (\u000D) characters. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - Policy *string `min:"1" type:"string"` - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want - // to use as managed session policies. The policies must exist in the same account - // as the role. - // - // This parameter is optional. You can provide up to 10 managed policy ARNs. - // However, the plaintext that you use for both inline and managed session policies - // can't exceed 2,048 characters. For more information about ARNs, see Amazon - // Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - // - // Passing policies to this operation returns new temporary credentials. The - // resulting session's permissions are the intersection of the role's identity-based - // policy and the session policies. You can use the role's temporary credentials - // in subsequent Amazon Web Services API calls to access resources in the account - // that owns the role. You cannot use session policies to grant more permissions - // than those allowed by the identity-based policy of the role that is being - // assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []*PolicyDescriptorType `type:"list"` - - // The fully qualified host component of the domain name of the OAuth 2.0 identity - // provider. Do not specify this value for an OpenID Connect identity provider. - // - // Currently www.amazon.com and graph.facebook.com are the only supported identity - // providers for OAuth 2.0 access tokens. Do not include URL schemes and port - // numbers. - // - // Do not specify this value for OpenID Connect ID tokens. - ProviderId *string `min:"4" type:"string"` - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // An identifier for the assumed role session. Typically, you pass the name - // or identifier that is associated with the user who is using your application. - // That way, the temporary security credentials that your application will use - // are associated with that user. This session name is included as part of the - // ARN and assumed role ID in the AssumedRoleUser response element. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // RoleSessionName is a required field - RoleSessionName *string `min:"2" type:"string" required:"true"` - - // The OAuth 2.0 access token or OpenID Connect ID token that is provided by - // the identity provider. Your application must get this token by authenticating - // the user who is using your application with a web identity provider before - // the application makes an AssumeRoleWithWebIdentity call. Only tokens with - // RSA algorithms (RS256) are supported. - // - // WebIdentityToken is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by AssumeRoleWithWebIdentityInput's - // String and GoString methods. - // - // WebIdentityToken is a required field - WebIdentityToken *string `min:"4" type:"string" required:"true" sensitive:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleWithWebIdentityInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleWithWebIdentityInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleWithWebIdentityInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithWebIdentityInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.ProviderId != nil && len(*s.ProviderId) < 4 { - invalidParams.Add(request.NewErrParamMinLen("ProviderId", 4)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.RoleSessionName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleSessionName")) - } - if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2)) - } - if s.WebIdentityToken == nil { - invalidParams.Add(request.NewErrParamRequired("WebIdentityToken")) - } - if s.WebIdentityToken != nil && len(*s.WebIdentityToken) < 4 { - invalidParams.Add(request.NewErrParamMinLen("WebIdentityToken", 4)) - } - if s.PolicyArns != nil { - for i, v := range s.PolicyArns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PolicyArns", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleWithWebIdentityInput) SetDurationSeconds(v int64) *AssumeRoleWithWebIdentityInput { - s.DurationSeconds = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleWithWebIdentityInput) SetPolicy(v string) *AssumeRoleWithWebIdentityInput { - s.Policy = &v - return s -} - -// SetPolicyArns sets the PolicyArns field's value. -func (s *AssumeRoleWithWebIdentityInput) SetPolicyArns(v []*PolicyDescriptorType) *AssumeRoleWithWebIdentityInput { - s.PolicyArns = v - return s -} - -// SetProviderId sets the ProviderId field's value. -func (s *AssumeRoleWithWebIdentityInput) SetProviderId(v string) *AssumeRoleWithWebIdentityInput { - s.ProviderId = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleWithWebIdentityInput) SetRoleArn(v string) *AssumeRoleWithWebIdentityInput { - s.RoleArn = &v - return s -} - -// SetRoleSessionName sets the RoleSessionName field's value. -func (s *AssumeRoleWithWebIdentityInput) SetRoleSessionName(v string) *AssumeRoleWithWebIdentityInput { - s.RoleSessionName = &v - return s -} - -// SetWebIdentityToken sets the WebIdentityToken field's value. -func (s *AssumeRoleWithWebIdentityInput) SetWebIdentityToken(v string) *AssumeRoleWithWebIdentityInput { - s.WebIdentityToken = &v - return s -} - -// Contains the response to a successful AssumeRoleWithWebIdentity request, -// including temporary Amazon Web Services credentials that can be used to make -// Amazon Web Services requests. -type AssumeRoleWithWebIdentityOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. - // For example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName - // that you specified when you called AssumeRole. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The intended audience (also known as client ID) of the web identity token. - // This is traditionally the client identifier issued to the application that - // requested the web identity token. - Audience *string `type:"string"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security token. - // - // The size of the security token that STS API operations return is not fixed. - // We strongly recommend that you make no assumptions about the maximum size. - Credentials *Credentials `type:"structure"` - - // A percentage value that indicates the packed size of the session policies - // and session tags combined passed in the request. The request fails if the - // packed size is greater than 100 percent, which means the policies and tags - // exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // The issuing authority of the web identity token presented. For OpenID Connect - // ID tokens, this contains the value of the iss field. For OAuth 2.0 access - // tokens, this contains the value of the ProviderId parameter that was passed - // in the AssumeRoleWithWebIdentity request. - Provider *string `type:"string"` - - // The value of the source identity that is returned in the JSON web token (JWT) - // from the identity provider. - // - // You can require users to set a source identity value when they assume a role. - // You do this by using the sts:SourceIdentity condition key in a role trust - // policy. That way, actions that are taken with the role are associated with - // that user. After the source identity is set, the value cannot be changed. - // It is present in the request for all actions that are taken by the role and - // persists across chained role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts#iam-term-role-chaining) - // sessions. You can configure your identity provider to use an attribute associated - // with your users, like user name or email, as the source identity when calling - // AssumeRoleWithWebIdentity. You do this by adding a claim to the JSON web - // token. To learn more about OIDC tokens and claims, see Using Tokens with - // User Pools (https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html) - // in the Amazon Cognito Developer Guide. For more information about using source - // identity, see Monitor and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - SourceIdentity *string `min:"2" type:"string"` - - // The unique user identifier that is returned by the identity provider. This - // identifier is associated with the WebIdentityToken that was submitted with - // the AssumeRoleWithWebIdentity call. The identifier is typically unique to - // the user and the application that acquired the WebIdentityToken (pairwise - // identifier). For OpenID Connect ID tokens, this field contains the value - // returned by the identity provider as the token's sub (Subject) claim. - SubjectFromWebIdentityToken *string `min:"6" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleWithWebIdentityOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumeRoleWithWebIdentityOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleWithWebIdentityOutput { - s.AssumedRoleUser = v - return s -} - -// SetAudience sets the Audience field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetAudience(v string) *AssumeRoleWithWebIdentityOutput { - s.Audience = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetCredentials(v *Credentials) *AssumeRoleWithWebIdentityOutput { - s.Credentials = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetPackedPolicySize(v int64) *AssumeRoleWithWebIdentityOutput { - s.PackedPolicySize = &v - return s -} - -// SetProvider sets the Provider field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetProvider(v string) *AssumeRoleWithWebIdentityOutput { - s.Provider = &v - return s -} - -// SetSourceIdentity sets the SourceIdentity field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetSourceIdentity(v string) *AssumeRoleWithWebIdentityOutput { - s.SourceIdentity = &v - return s -} - -// SetSubjectFromWebIdentityToken sets the SubjectFromWebIdentityToken field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetSubjectFromWebIdentityToken(v string) *AssumeRoleWithWebIdentityOutput { - s.SubjectFromWebIdentityToken = &v - return s -} - -// The identifiers for the temporary security credentials that the operation -// returns. -type AssumedRoleUser struct { - _ struct{} `type:"structure"` - - // The ARN of the temporary security credentials that are returned from the - // AssumeRole action. For more information about ARNs and how to use them in - // policies, see IAM Identifiers (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in the IAM User Guide. - // - // Arn is a required field - Arn *string `min:"20" type:"string" required:"true"` - - // A unique identifier that contains the role ID and the role session name of - // the role that is being assumed. The role ID is generated by Amazon Web Services - // when the role is created. - // - // AssumedRoleId is a required field - AssumedRoleId *string `min:"2" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumedRoleUser) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s AssumedRoleUser) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *AssumedRoleUser) SetArn(v string) *AssumedRoleUser { - s.Arn = &v - return s -} - -// SetAssumedRoleId sets the AssumedRoleId field's value. -func (s *AssumedRoleUser) SetAssumedRoleId(v string) *AssumedRoleUser { - s.AssumedRoleId = &v - return s -} - -// Amazon Web Services credentials for API authentication. -type Credentials struct { - _ struct{} `type:"structure"` - - // The access key ID that identifies the temporary security credentials. - // - // AccessKeyId is a required field - AccessKeyId *string `min:"16" type:"string" required:"true"` - - // The date on which the current credentials expire. - // - // Expiration is a required field - Expiration *time.Time `type:"timestamp" required:"true"` - - // The secret access key that can be used to sign requests. - // - // SecretAccessKey is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by Credentials's - // String and GoString methods. - // - // SecretAccessKey is a required field - SecretAccessKey *string `type:"string" required:"true" sensitive:"true"` - - // The token that users must pass to the service API to use the temporary credentials. - // - // SessionToken is a required field - SessionToken *string `type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Credentials) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Credentials) GoString() string { - return s.String() -} - -// SetAccessKeyId sets the AccessKeyId field's value. -func (s *Credentials) SetAccessKeyId(v string) *Credentials { - s.AccessKeyId = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *Credentials) SetExpiration(v time.Time) *Credentials { - s.Expiration = &v - return s -} - -// SetSecretAccessKey sets the SecretAccessKey field's value. -func (s *Credentials) SetSecretAccessKey(v string) *Credentials { - s.SecretAccessKey = &v - return s -} - -// SetSessionToken sets the SessionToken field's value. -func (s *Credentials) SetSessionToken(v string) *Credentials { - s.SessionToken = &v - return s -} - -type DecodeAuthorizationMessageInput struct { - _ struct{} `type:"structure"` - - // The encoded message that was returned with the response. - // - // EncodedMessage is a required field - EncodedMessage *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DecodeAuthorizationMessageInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DecodeAuthorizationMessageInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DecodeAuthorizationMessageInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DecodeAuthorizationMessageInput"} - if s.EncodedMessage == nil { - invalidParams.Add(request.NewErrParamRequired("EncodedMessage")) - } - if s.EncodedMessage != nil && len(*s.EncodedMessage) < 1 { - invalidParams.Add(request.NewErrParamMinLen("EncodedMessage", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEncodedMessage sets the EncodedMessage field's value. -func (s *DecodeAuthorizationMessageInput) SetEncodedMessage(v string) *DecodeAuthorizationMessageInput { - s.EncodedMessage = &v - return s -} - -// A document that contains additional information about the authorization status -// of a request from an encoded message that is returned in response to an Amazon -// Web Services request. -type DecodeAuthorizationMessageOutput struct { - _ struct{} `type:"structure"` - - // The API returns a response with the decoded message. - DecodedMessage *string `type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DecodeAuthorizationMessageOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s DecodeAuthorizationMessageOutput) GoString() string { - return s.String() -} - -// SetDecodedMessage sets the DecodedMessage field's value. -func (s *DecodeAuthorizationMessageOutput) SetDecodedMessage(v string) *DecodeAuthorizationMessageOutput { - s.DecodedMessage = &v - return s -} - -// Identifiers for the federated user that is associated with the credentials. -type FederatedUser struct { - _ struct{} `type:"structure"` - - // The ARN that specifies the federated user that is associated with the credentials. - // For more information about ARNs and how to use them in policies, see IAM - // Identifiers (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in the IAM User Guide. - // - // Arn is a required field - Arn *string `min:"20" type:"string" required:"true"` - - // The string that identifies the federated user associated with the credentials, - // similar to the unique ID of an IAM user. - // - // FederatedUserId is a required field - FederatedUserId *string `min:"2" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s FederatedUser) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s FederatedUser) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *FederatedUser) SetArn(v string) *FederatedUser { - s.Arn = &v - return s -} - -// SetFederatedUserId sets the FederatedUserId field's value. -func (s *FederatedUser) SetFederatedUserId(v string) *FederatedUser { - s.FederatedUserId = &v - return s -} - -type GetAccessKeyInfoInput struct { - _ struct{} `type:"structure"` - - // The identifier of an access key. - // - // This parameter allows (through its regex pattern) a string of characters - // that can consist of any upper- or lowercase letter or digit. - // - // AccessKeyId is a required field - AccessKeyId *string `min:"16" type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetAccessKeyInfoInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetAccessKeyInfoInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetAccessKeyInfoInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetAccessKeyInfoInput"} - if s.AccessKeyId == nil { - invalidParams.Add(request.NewErrParamRequired("AccessKeyId")) - } - if s.AccessKeyId != nil && len(*s.AccessKeyId) < 16 { - invalidParams.Add(request.NewErrParamMinLen("AccessKeyId", 16)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccessKeyId sets the AccessKeyId field's value. -func (s *GetAccessKeyInfoInput) SetAccessKeyId(v string) *GetAccessKeyInfoInput { - s.AccessKeyId = &v - return s -} - -type GetAccessKeyInfoOutput struct { - _ struct{} `type:"structure"` - - // The number used to identify the Amazon Web Services account. - Account *string `type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetAccessKeyInfoOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetAccessKeyInfoOutput) GoString() string { - return s.String() -} - -// SetAccount sets the Account field's value. -func (s *GetAccessKeyInfoOutput) SetAccount(v string) *GetAccessKeyInfoOutput { - s.Account = &v - return s -} - -type GetCallerIdentityInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetCallerIdentityInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetCallerIdentityInput) GoString() string { - return s.String() -} - -// Contains the response to a successful GetCallerIdentity request, including -// information about the entity making the request. -type GetCallerIdentityOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Web Services account ID number of the account that owns or contains - // the calling entity. - Account *string `type:"string"` - - // The Amazon Web Services ARN associated with the calling entity. - Arn *string `min:"20" type:"string"` - - // The unique identifier of the calling entity. The exact value depends on the - // type of entity that is making the call. The values returned are those listed - // in the aws:userid column in the Principal table (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#principaltable) - // found on the Policy Variables reference page in the IAM User Guide. - UserId *string `type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetCallerIdentityOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetCallerIdentityOutput) GoString() string { - return s.String() -} - -// SetAccount sets the Account field's value. -func (s *GetCallerIdentityOutput) SetAccount(v string) *GetCallerIdentityOutput { - s.Account = &v - return s -} - -// SetArn sets the Arn field's value. -func (s *GetCallerIdentityOutput) SetArn(v string) *GetCallerIdentityOutput { - s.Arn = &v - return s -} - -// SetUserId sets the UserId field's value. -func (s *GetCallerIdentityOutput) SetUserId(v string) *GetCallerIdentityOutput { - s.UserId = &v - return s -} - -type GetFederationTokenInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, that the session should last. Acceptable durations - // for federation sessions range from 900 seconds (15 minutes) to 129,600 seconds - // (36 hours), with 43,200 seconds (12 hours) as the default. Sessions obtained - // using root user credentials are restricted to a maximum of 3,600 seconds - // (one hour). If the specified duration is longer than one hour, the session - // obtained by using root user credentials defaults to one hour. - DurationSeconds *int64 `min:"900" type:"integer"` - - // The name of the federated user. The name is used as an identifier for the - // temporary security credentials (such as Bob). For example, you can reference - // the federated user name in a resource-based policy, such as in an Amazon - // S3 bucket policy. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // Name is a required field - Name *string `min:"2" type:"string" required:"true"` - - // An IAM policy in JSON format that you want to use as an inline session policy. - // - // You must pass an inline or managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // to this operation. You can pass a single JSON policy document to use as an - // inline session policy. You can also specify up to 10 managed policy Amazon - // Resource Names (ARNs) to use as managed session policies. - // - // This parameter is optional. However, if you do not pass any session policies, - // then the resulting federated user session has no permissions. - // - // When you pass session policies, the session permissions are the intersection - // of the IAM user policies and the session policies that you pass. This gives - // you a way to further restrict the permissions for a federated user. You cannot - // use session policies to grant more permissions than those that are defined - // in the permissions policy of the IAM user. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - // - // The resulting credentials can be used to access a resource that has a resource-based - // policy. If that policy specifically references the federated user session - // in the Principal element of the policy, the session has the permissions allowed - // by the policy. These permissions are granted in addition to the permissions - // that are granted by the session policies. - // - // The plaintext that you use for both inline and managed session policies can't - // exceed 2,048 characters. The JSON policy characters can be any ASCII character - // from the space character to the end of the valid character list (\u0020 through - // \u00FF). It can also include the tab (\u0009), linefeed (\u000A), and carriage - // return (\u000D) characters. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - Policy *string `min:"1" type:"string"` - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want - // to use as a managed session policy. The policies must exist in the same account - // as the IAM user that is requesting federated access. - // - // You must pass an inline or managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // to this operation. You can pass a single JSON policy document to use as an - // inline session policy. You can also specify up to 10 managed policy Amazon - // Resource Names (ARNs) to use as managed session policies. The plaintext that - // you use for both inline and managed session policies can't exceed 2,048 characters. - // You can provide up to 10 managed policy ARNs. For more information about - // ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces - // (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. - // - // This parameter is optional. However, if you do not pass any session policies, - // then the resulting federated user session has no permissions. - // - // When you pass session policies, the session permissions are the intersection - // of the IAM user policies and the session policies that you pass. This gives - // you a way to further restrict the permissions for a federated user. You cannot - // use session policies to grant more permissions than those that are defined - // in the permissions policy of the IAM user. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - // - // The resulting credentials can be used to access a resource that has a resource-based - // policy. If that policy specifically references the federated user session - // in the Principal element of the policy, the session has the permissions allowed - // by the policy. These permissions are granted in addition to the permissions - // that are granted by the session policies. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - PolicyArns []*PolicyDescriptorType `type:"list"` - - // A list of session tags. Each session tag consists of a key name and an associated - // value. For more information about session tags, see Passing Session Tags - // in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) - // in the IAM User Guide. - // - // This parameter is optional. You can pass up to 50 session tags. The plaintext - // session tag keys can’t exceed 128 characters and the values can’t exceed - // 256 characters. For these and additional limits, see IAM and STS Character - // Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - // - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has - // a separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the - // upper size limit. - // - // You can pass a session tag with the same key as a tag that is already attached - // to the user you are federating. When you do, session tags override a user - // tag with the same key. - // - // Tag key–value pairs are not case sensitive, but case is preserved. This - // means that you cannot have separate Department and department tag keys. Assume - // that the role has the Department=Marketing tag and you pass the department=engineering - // session tag. Department and department are not saved as separate tags, and - // the session tag passed in the request takes precedence over the role tag. - Tags []*Tag `type:"list"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetFederationTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetFederationTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetFederationTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetFederationTokenInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 2 { - invalidParams.Add(request.NewErrParamMinLen("Name", 2)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.PolicyArns != nil { - for i, v := range s.PolicyArns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PolicyArns", i), err.(request.ErrInvalidParams)) - } - } - } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *GetFederationTokenInput) SetDurationSeconds(v int64) *GetFederationTokenInput { - s.DurationSeconds = &v - return s -} - -// SetName sets the Name field's value. -func (s *GetFederationTokenInput) SetName(v string) *GetFederationTokenInput { - s.Name = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *GetFederationTokenInput) SetPolicy(v string) *GetFederationTokenInput { - s.Policy = &v - return s -} - -// SetPolicyArns sets the PolicyArns field's value. -func (s *GetFederationTokenInput) SetPolicyArns(v []*PolicyDescriptorType) *GetFederationTokenInput { - s.PolicyArns = v - return s -} - -// SetTags sets the Tags field's value. -func (s *GetFederationTokenInput) SetTags(v []*Tag) *GetFederationTokenInput { - s.Tags = v - return s -} - -// Contains the response to a successful GetFederationToken request, including -// temporary Amazon Web Services credentials that can be used to make Amazon -// Web Services requests. -type GetFederationTokenOutput struct { - _ struct{} `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // The size of the security token that STS API operations return is not fixed. - // We strongly recommend that you make no assumptions about the maximum size. - Credentials *Credentials `type:"structure"` - - // Identifiers for the federated user associated with the credentials (such - // as arn:aws:sts::123456789012:federated-user/Bob or 123456789012:Bob). You - // can use the federated user's ARN in your resource-based policies, such as - // an Amazon S3 bucket policy. - FederatedUser *FederatedUser `type:"structure"` - - // A percentage value that indicates the packed size of the session policies - // and session tags combined passed in the request. The request fails if the - // packed size is greater than 100 percent, which means the policies and tags - // exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetFederationTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetFederationTokenOutput) GoString() string { - return s.String() -} - -// SetCredentials sets the Credentials field's value. -func (s *GetFederationTokenOutput) SetCredentials(v *Credentials) *GetFederationTokenOutput { - s.Credentials = v - return s -} - -// SetFederatedUser sets the FederatedUser field's value. -func (s *GetFederationTokenOutput) SetFederatedUser(v *FederatedUser) *GetFederationTokenOutput { - s.FederatedUser = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *GetFederationTokenOutput) SetPackedPolicySize(v int64) *GetFederationTokenOutput { - s.PackedPolicySize = &v - return s -} - -type GetSessionTokenInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, that the credentials should remain valid. Acceptable - // durations for IAM user sessions range from 900 seconds (15 minutes) to 129,600 - // seconds (36 hours), with 43,200 seconds (12 hours) as the default. Sessions - // for Amazon Web Services account owners are restricted to a maximum of 3,600 - // seconds (one hour). If the duration is longer than one hour, the session - // for Amazon Web Services account owners defaults to one hour. - DurationSeconds *int64 `min:"900" type:"integer"` - - // The identification number of the MFA device that is associated with the IAM - // user who is making the GetSessionToken call. Specify this value if the IAM - // user has a policy that requires MFA authentication. The value is either the - // serial number for a hardware device (such as GAHT12345678) or an Amazon Resource - // Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - // You can find the device for an IAM user by going to the Amazon Web Services - // Management Console and viewing the user's security credentials. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@:/- - SerialNumber *string `min:"9" type:"string"` - - // The value provided by the MFA device, if MFA is required. If any policy requires - // the IAM user to submit an MFA code, specify this value. If MFA authentication - // is required, the user must provide a code when requesting a set of temporary - // security credentials. A user who fails to provide the code receives an "access - // denied" response when requesting resources that require MFA authentication. - // - // The format for this parameter, as described by its regex pattern, is a sequence - // of six numeric digits. - TokenCode *string `min:"6" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetSessionTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetSessionTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetSessionTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetSessionTokenInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.SerialNumber != nil && len(*s.SerialNumber) < 9 { - invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9)) - } - if s.TokenCode != nil && len(*s.TokenCode) < 6 { - invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *GetSessionTokenInput) SetDurationSeconds(v int64) *GetSessionTokenInput { - s.DurationSeconds = &v - return s -} - -// SetSerialNumber sets the SerialNumber field's value. -func (s *GetSessionTokenInput) SetSerialNumber(v string) *GetSessionTokenInput { - s.SerialNumber = &v - return s -} - -// SetTokenCode sets the TokenCode field's value. -func (s *GetSessionTokenInput) SetTokenCode(v string) *GetSessionTokenInput { - s.TokenCode = &v - return s -} - -// Contains the response to a successful GetSessionToken request, including -// temporary Amazon Web Services credentials that can be used to make Amazon -// Web Services requests. -type GetSessionTokenOutput struct { - _ struct{} `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // The size of the security token that STS API operations return is not fixed. - // We strongly recommend that you make no assumptions about the maximum size. - Credentials *Credentials `type:"structure"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetSessionTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s GetSessionTokenOutput) GoString() string { - return s.String() -} - -// SetCredentials sets the Credentials field's value. -func (s *GetSessionTokenOutput) SetCredentials(v *Credentials) *GetSessionTokenOutput { - s.Credentials = v - return s -} - -// A reference to the IAM managed policy that is passed as a session policy -// for a role session or a federated user session. -type PolicyDescriptorType struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the IAM managed policy to use as a session - // policy for the role. For more information about ARNs, see Amazon Resource - // Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. - Arn *string `locationName:"arn" min:"20" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PolicyDescriptorType) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s PolicyDescriptorType) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PolicyDescriptorType) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PolicyDescriptorType"} - if s.Arn != nil && len(*s.Arn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("Arn", 20)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetArn sets the Arn field's value. -func (s *PolicyDescriptorType) SetArn(v string) *PolicyDescriptorType { - s.Arn = &v - return s -} - -// Contains information about the provided context. This includes the signed -// and encrypted trusted context assertion and the context provider ARN from -// which the trusted context assertion was generated. -type ProvidedContext struct { - _ struct{} `type:"structure"` - - // The signed and encrypted trusted context assertion generated by the context - // provider. The trusted context assertion is signed and encrypted by Amazon - // Web Services STS. - ContextAssertion *string `min:"4" type:"string"` - - // The context provider ARN from which the trusted context assertion was generated. - ProviderArn *string `min:"20" type:"string"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ProvidedContext) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s ProvidedContext) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ProvidedContext) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ProvidedContext"} - if s.ContextAssertion != nil && len(*s.ContextAssertion) < 4 { - invalidParams.Add(request.NewErrParamMinLen("ContextAssertion", 4)) - } - if s.ProviderArn != nil && len(*s.ProviderArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("ProviderArn", 20)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetContextAssertion sets the ContextAssertion field's value. -func (s *ProvidedContext) SetContextAssertion(v string) *ProvidedContext { - s.ContextAssertion = &v - return s -} - -// SetProviderArn sets the ProviderArn field's value. -func (s *ProvidedContext) SetProviderArn(v string) *ProvidedContext { - s.ProviderArn = &v - return s -} - -// You can pass custom key-value pair attributes when you assume a role or federate -// a user. These are called session tags. You can then use the session tags -// to control access to resources. For more information, see Tagging Amazon -// Web Services STS Sessions (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -type Tag struct { - _ struct{} `type:"structure"` - - // The key for a session tag. - // - // You can pass up to 50 session tags. The plain text session tag keys can’t - // exceed 128 characters. For these and additional limits, see IAM and STS Character - // Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - // - // Key is a required field - Key *string `min:"1" type:"string" required:"true"` - - // The value for a session tag. - // - // You can pass up to 50 session tags. The plain text session tag values can’t - // exceed 256 characters. For these and additional limits, see IAM and STS Character - // Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - // - // Value is a required field - Value *string `type:"string" required:"true"` -} - -// String returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Tag) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation. -// -// API parameter values that are decorated as "sensitive" in the API will not -// be included in the string output. The member name will be present, but the -// value will be replaced with "sensitive". -func (s Tag) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Tag) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Tag"} - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.Value == nil { - invalidParams.Add(request.NewErrParamRequired("Value")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKey sets the Key field's value. -func (s *Tag) SetKey(v string) *Tag { - s.Key = &v - return s -} - -// SetValue sets the Value field's value. -func (s *Tag) SetValue(v string) *Tag { - s.Value = &v - return s -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go deleted file mode 100644 index d5307fcaa..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go +++ /dev/null @@ -1,11 +0,0 @@ -package sts - -import "github.com/aws/aws-sdk-go/aws/request" - -func init() { - initRequest = customizeRequest -} - -func customizeRequest(r *request.Request) { - r.RetryErrorCodes = append(r.RetryErrorCodes, ErrCodeIDPCommunicationErrorException) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go deleted file mode 100644 index ea1d9eb0c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package sts provides the client and types for making API -// requests to AWS Security Token Service. -// -// Security Token Service (STS) enables you to request temporary, limited-privilege -// credentials for users. This guide provides descriptions of the STS API. For -// more information about using this service, see Temporary Security Credentials -// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). -// -// See https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15 for more information on this service. -// -// See sts package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/ -// -// # Using the Client -// -// To contact AWS Security Token Service with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the AWS Security Token Service client STS for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#New -package sts diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go deleted file mode 100644 index b680bbd5d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go +++ /dev/null @@ -1,84 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -const ( - - // ErrCodeExpiredTokenException for service response error code - // "ExpiredTokenException". - // - // The web identity token that was passed is expired or is not valid. Get a - // new identity token from the identity provider and then retry the request. - ErrCodeExpiredTokenException = "ExpiredTokenException" - - // ErrCodeIDPCommunicationErrorException for service response error code - // "IDPCommunicationError". - // - // The request could not be fulfilled because the identity provider (IDP) that - // was asked to verify the incoming identity token could not be reached. This - // is often a transient error caused by network conditions. Retry the request - // a limited number of times so that you don't exceed the request rate. If the - // error persists, the identity provider might be down or not responding. - ErrCodeIDPCommunicationErrorException = "IDPCommunicationError" - - // ErrCodeIDPRejectedClaimException for service response error code - // "IDPRejectedClaim". - // - // The identity provider (IdP) reported that authentication failed. This might - // be because the claim is invalid. - // - // If this error is returned for the AssumeRoleWithWebIdentity operation, it - // can also mean that the claim has expired or has been explicitly revoked. - ErrCodeIDPRejectedClaimException = "IDPRejectedClaim" - - // ErrCodeInvalidAuthorizationMessageException for service response error code - // "InvalidAuthorizationMessageException". - // - // The error returned if the message passed to DecodeAuthorizationMessage was - // invalid. This can happen if the token contains invalid characters, such as - // linebreaks. - ErrCodeInvalidAuthorizationMessageException = "InvalidAuthorizationMessageException" - - // ErrCodeInvalidIdentityTokenException for service response error code - // "InvalidIdentityToken". - // - // The web identity token that was passed could not be validated by Amazon Web - // Services. Get a new identity token from the identity provider and then retry - // the request. - ErrCodeInvalidIdentityTokenException = "InvalidIdentityToken" - - // ErrCodeMalformedPolicyDocumentException for service response error code - // "MalformedPolicyDocument". - // - // The request was rejected because the policy document was malformed. The error - // message describes the specific error. - ErrCodeMalformedPolicyDocumentException = "MalformedPolicyDocument" - - // ErrCodePackedPolicyTooLargeException for service response error code - // "PackedPolicyTooLarge". - // - // The request was rejected because the total packed size of the session policies - // and session tags combined was too large. An Amazon Web Services conversion - // compresses the session policy document, session policy ARNs, and session - // tags into a packed binary format that has a separate limit. The error message - // indicates by percentage how close the policies and tags are to the upper - // size limit. For more information, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) - // in the IAM User Guide. - // - // You could receive this error even though you meet other defined session policy - // and session tag limits. For more information, see IAM and STS Entity Character - // Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - ErrCodePackedPolicyTooLargeException = "PackedPolicyTooLarge" - - // ErrCodeRegionDisabledException for service response error code - // "RegionDisabledException". - // - // STS is not activated in the requested region for the account that is being - // asked to generate credentials. The account administrator must use the IAM - // console to activate STS in that region. For more information, see Activating - // and Deactivating Amazon Web Services STS in an Amazon Web Services Region - // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) - // in the IAM User Guide. - ErrCodeRegionDisabledException = "RegionDisabledException" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go deleted file mode 100644 index 12327d053..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/query" -) - -// STS provides the API operation methods for making requests to -// AWS Security Token Service. See this package's package overview docs -// for details on the service. -// -// STS methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type STS struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "sts" // Name of service. - EndpointsID = ServiceName // ID to lookup a service endpoint with. - ServiceID = "STS" // ServiceID is a unique identifier of a specific service. -) - -// New creates a new instance of the STS client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// -// mySession := session.Must(session.NewSession()) -// -// // Create a STS client from just a session. -// svc := sts.New(mySession) -// -// // Create a STS client with additional configuration -// svc := sts.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *STS { - c := p.ClientConfig(EndpointsID, cfgs...) - if c.SigningNameDerived || len(c.SigningName) == 0 { - c.SigningName = EndpointsID - // No Fallback - } - return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName, c.ResolvedRegion) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *STS { - svc := &STS{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - ServiceID: ServiceID, - SigningName: signingName, - SigningRegion: signingRegion, - PartitionID: partitionID, - Endpoint: endpoint, - APIVersion: "2011-06-15", - ResolvedRegion: resolvedRegion, - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a STS operation and runs any -// custom request initialization. -func (c *STS) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/stsiface/interface.go b/vendor/github.com/aws/aws-sdk-go/service/sts/stsiface/interface.go deleted file mode 100644 index bf06b2e7d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/stsiface/interface.go +++ /dev/null @@ -1,96 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package stsiface provides an interface to enable mocking the AWS Security Token Service service client -// for testing your code. -// -// It is important to note that this interface will have breaking changes -// when the service model is updated and adds new API operations, paginators, -// and waiters. -package stsiface - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/service/sts" -) - -// STSAPI provides an interface to enable mocking the -// sts.STS service client's API operation, -// paginators, and waiters. This make unit testing your code that calls out -// to the SDK's service client's calls easier. -// -// The best way to use this interface is so the SDK's service client's calls -// can be stubbed out for unit testing your code with the SDK without needing -// to inject custom request handlers into the SDK's request pipeline. -// -// // myFunc uses an SDK service client to make a request to -// // AWS Security Token Service. -// func myFunc(svc stsiface.STSAPI) bool { -// // Make svc.AssumeRole request -// } -// -// func main() { -// sess := session.New() -// svc := sts.New(sess) -// -// myFunc(svc) -// } -// -// In your _test.go file: -// -// // Define a mock struct to be used in your unit tests of myFunc. -// type mockSTSClient struct { -// stsiface.STSAPI -// } -// func (m *mockSTSClient) AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) { -// // mock response/functionality -// } -// -// func TestMyFunc(t *testing.T) { -// // Setup Test -// mockSvc := &mockSTSClient{} -// -// myfunc(mockSvc) -// -// // Verify myFunc's functionality -// } -// -// It is important to note that this interface will have breaking changes -// when the service model is updated and adds new API operations, paginators, -// and waiters. Its suggested to use the pattern above for testing, or using -// tooling to generate mocks to satisfy the interfaces. -type STSAPI interface { - AssumeRole(*sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) - AssumeRoleWithContext(aws.Context, *sts.AssumeRoleInput, ...request.Option) (*sts.AssumeRoleOutput, error) - AssumeRoleRequest(*sts.AssumeRoleInput) (*request.Request, *sts.AssumeRoleOutput) - - AssumeRoleWithSAML(*sts.AssumeRoleWithSAMLInput) (*sts.AssumeRoleWithSAMLOutput, error) - AssumeRoleWithSAMLWithContext(aws.Context, *sts.AssumeRoleWithSAMLInput, ...request.Option) (*sts.AssumeRoleWithSAMLOutput, error) - AssumeRoleWithSAMLRequest(*sts.AssumeRoleWithSAMLInput) (*request.Request, *sts.AssumeRoleWithSAMLOutput) - - AssumeRoleWithWebIdentity(*sts.AssumeRoleWithWebIdentityInput) (*sts.AssumeRoleWithWebIdentityOutput, error) - AssumeRoleWithWebIdentityWithContext(aws.Context, *sts.AssumeRoleWithWebIdentityInput, ...request.Option) (*sts.AssumeRoleWithWebIdentityOutput, error) - AssumeRoleWithWebIdentityRequest(*sts.AssumeRoleWithWebIdentityInput) (*request.Request, *sts.AssumeRoleWithWebIdentityOutput) - - DecodeAuthorizationMessage(*sts.DecodeAuthorizationMessageInput) (*sts.DecodeAuthorizationMessageOutput, error) - DecodeAuthorizationMessageWithContext(aws.Context, *sts.DecodeAuthorizationMessageInput, ...request.Option) (*sts.DecodeAuthorizationMessageOutput, error) - DecodeAuthorizationMessageRequest(*sts.DecodeAuthorizationMessageInput) (*request.Request, *sts.DecodeAuthorizationMessageOutput) - - GetAccessKeyInfo(*sts.GetAccessKeyInfoInput) (*sts.GetAccessKeyInfoOutput, error) - GetAccessKeyInfoWithContext(aws.Context, *sts.GetAccessKeyInfoInput, ...request.Option) (*sts.GetAccessKeyInfoOutput, error) - GetAccessKeyInfoRequest(*sts.GetAccessKeyInfoInput) (*request.Request, *sts.GetAccessKeyInfoOutput) - - GetCallerIdentity(*sts.GetCallerIdentityInput) (*sts.GetCallerIdentityOutput, error) - GetCallerIdentityWithContext(aws.Context, *sts.GetCallerIdentityInput, ...request.Option) (*sts.GetCallerIdentityOutput, error) - GetCallerIdentityRequest(*sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) - - GetFederationToken(*sts.GetFederationTokenInput) (*sts.GetFederationTokenOutput, error) - GetFederationTokenWithContext(aws.Context, *sts.GetFederationTokenInput, ...request.Option) (*sts.GetFederationTokenOutput, error) - GetFederationTokenRequest(*sts.GetFederationTokenInput) (*request.Request, *sts.GetFederationTokenOutput) - - GetSessionToken(*sts.GetSessionTokenInput) (*sts.GetSessionTokenOutput, error) - GetSessionTokenWithContext(aws.Context, *sts.GetSessionTokenInput, ...request.Option) (*sts.GetSessionTokenOutput, error) - GetSessionTokenRequest(*sts.GetSessionTokenInput) (*request.Request, *sts.GetSessionTokenOutput) -} - -var _ STSAPI = (*sts.STS)(nil) diff --git a/vendor/github.com/beorn7/perks/LICENSE b/vendor/github.com/beorn7/perks/LICENSE deleted file mode 100644 index 339177be6..000000000 --- a/vendor/github.com/beorn7/perks/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (C) 2013 Blake Mizerany - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/beorn7/perks/quantile/exampledata.txt b/vendor/github.com/beorn7/perks/quantile/exampledata.txt deleted file mode 100644 index 1602287d7..000000000 --- a/vendor/github.com/beorn7/perks/quantile/exampledata.txt +++ /dev/null @@ -1,2388 +0,0 @@ -8 -5 -26 -12 -5 -235 -13 -6 -28 -30 -3 -3 -3 -3 -5 -2 -33 -7 -2 -4 -7 -12 -14 -5 -8 -3 -10 -4 -5 -3 -6 -6 -209 -20 -3 -10 -14 -3 -4 -6 -8 -5 -11 -7 -3 -2 -3 -3 -212 -5 -222 -4 -10 -10 -5 -6 -3 -8 -3 -10 -254 -220 -2 -3 -5 -24 -5 -4 -222 -7 -3 -3 -223 -8 -15 -12 -14 -14 -3 -2 -2 -3 -13 -3 -11 -4 -4 -6 -5 -7 -13 -5 -3 -5 -2 -5 -3 -5 -2 -7 -15 -17 -14 -3 -6 -6 -3 -17 -5 -4 -7 -6 -4 -4 -8 -6 -8 -3 -9 -3 -6 -3 -4 -5 -3 -3 -660 -4 -6 -10 -3 -6 -3 -2 -5 -13 -2 -4 -4 -10 -4 -8 -4 -3 -7 -9 -9 -3 -10 -37 -3 -13 -4 -12 -3 -6 -10 -8 -5 -21 -2 -3 -8 -3 -2 -3 -3 -4 -12 -2 -4 -8 -8 -4 -3 -2 -20 -1 -6 -32 -2 -11 -6 -18 -3 -8 -11 -3 -212 -3 -4 -2 -6 -7 -12 -11 -3 -2 -16 -10 -6 -4 -6 -3 -2 -7 -3 -2 -2 -2 -2 -5 -6 -4 -3 -10 -3 -4 -6 -5 -3 -4 -4 -5 -6 -4 -3 -4 -4 -5 -7 -5 -5 -3 -2 -7 -2 -4 -12 -4 -5 -6 -2 -4 -4 -8 -4 -15 -13 -7 -16 -5 -3 -23 -5 -5 -7 -3 -2 -9 -8 -7 -5 -8 -11 -4 -10 -76 -4 -47 -4 -3 -2 -7 -4 -2 -3 -37 -10 -4 -2 -20 -5 -4 -4 -10 -10 -4 -3 -7 -23 -240 -7 -13 -5 -5 -3 -3 -2 -5 -4 -2 -8 -7 -19 -2 -23 -8 -7 -2 -5 -3 -8 -3 -8 -13 -5 -5 -5 -2 -3 -23 -4 -9 -8 -4 -3 -3 -5 -220 -2 -3 -4 -6 -14 -3 -53 -6 -2 -5 -18 -6 -3 -219 -6 -5 -2 -5 -3 -6 -5 -15 -4 -3 -17 -3 -2 -4 -7 -2 -3 -3 -4 -4 -3 -2 -664 -6 -3 -23 -5 -5 -16 -5 -8 -2 -4 -2 -24 -12 -3 -2 -3 -5 -8 -3 -5 -4 -3 -14 -3 -5 -8 -2 -3 -7 -9 -4 -2 -3 -6 -8 -4 -3 -4 -6 -5 -3 -3 -6 -3 -19 -4 -4 -6 -3 -6 -3 -5 -22 -5 -4 -4 -3 -8 -11 -4 -9 -7 -6 -13 -4 -4 -4 -6 -17 -9 -3 -3 -3 -4 -3 -221 -5 -11 -3 -4 -2 -12 -6 -3 -5 -7 -5 -7 -4 -9 -7 -14 -37 -19 -217 -16 -3 -5 -2 -2 -7 -19 -7 -6 -7 -4 -24 -5 -11 -4 -7 -7 -9 -13 -3 -4 -3 -6 -28 -4 -4 -5 -5 -2 -5 -6 -4 -4 -6 -10 -5 -4 -3 -2 -3 -3 -6 -5 -5 -4 -3 -2 -3 -7 -4 -6 -18 -16 -8 -16 -4 -5 -8 -6 -9 -13 -1545 -6 -215 -6 -5 -6 -3 -45 -31 -5 -2 -2 -4 -3 -3 -2 -5 -4 -3 -5 -7 -7 -4 -5 -8 -5 -4 -749 -2 -31 -9 -11 -2 -11 -5 -4 -4 -7 -9 -11 -4 -5 -4 -7 -3 -4 -6 -2 -15 -3 -4 -3 -4 -3 -5 -2 -13 -5 -5 -3 -3 -23 -4 -4 -5 -7 -4 -13 -2 -4 -3 -4 -2 -6 -2 -7 -3 -5 -5 -3 -29 -5 -4 -4 -3 -10 -2 -3 -79 -16 -6 -6 -7 -7 -3 -5 -5 -7 -4 -3 -7 -9 -5 -6 -5 -9 -6 -3 -6 -4 -17 -2 -10 -9 -3 -6 -2 -3 -21 -22 -5 -11 -4 -2 -17 -2 -224 -2 -14 -3 -4 -4 -2 -4 -4 -4 -4 -5 -3 -4 -4 -10 -2 -6 -3 -3 -5 -7 -2 -7 -5 -6 -3 -218 -2 -2 -5 -2 -6 -3 -5 -222 -14 -6 -33 -3 -2 -5 -3 -3 -3 -9 -5 -3 -3 -2 -7 -4 -3 -4 -3 -5 -6 -5 -26 -4 -13 -9 -7 -3 -221 -3 -3 -4 -4 -4 -4 -2 -18 -5 -3 -7 -9 -6 -8 -3 -10 -3 -11 -9 -5 -4 -17 -5 -5 -6 -6 -3 -2 -4 -12 -17 -6 -7 -218 -4 -2 -4 -10 -3 -5 -15 -3 -9 -4 -3 -3 -6 -29 -3 -3 -4 -5 -5 -3 -8 -5 -6 -6 -7 -5 -3 -5 -3 -29 -2 -31 -5 -15 -24 -16 -5 -207 -4 -3 -3 -2 -15 -4 -4 -13 -5 -5 -4 -6 -10 -2 -7 -8 -4 -6 -20 -5 -3 -4 -3 -12 -12 -5 -17 -7 -3 -3 -3 -6 -10 -3 -5 -25 -80 -4 -9 -3 -2 -11 -3 -3 -2 -3 -8 -7 -5 -5 -19 -5 -3 -3 -12 -11 -2 -6 -5 -5 -5 -3 -3 -3 -4 -209 -14 -3 -2 -5 -19 -4 -4 -3 -4 -14 -5 -6 -4 -13 -9 -7 -4 -7 -10 -2 -9 -5 -7 -2 -8 -4 -6 -5 -5 -222 -8 -7 -12 -5 -216 -3 -4 -4 -6 -3 -14 -8 -7 -13 -4 -3 -3 -3 -3 -17 -5 -4 -3 -33 -6 -6 -33 -7 -5 -3 -8 -7 -5 -2 -9 -4 -2 -233 -24 -7 -4 -8 -10 -3 -4 -15 -2 -16 -3 -3 -13 -12 -7 -5 -4 -207 -4 -2 -4 -27 -15 -2 -5 -2 -25 -6 -5 -5 -6 -13 -6 -18 -6 -4 -12 -225 -10 -7 -5 -2 -2 -11 -4 -14 -21 -8 -10 -3 -5 -4 -232 -2 -5 -5 -3 -7 -17 -11 -6 -6 -23 -4 -6 -3 -5 -4 -2 -17 -3 -6 -5 -8 -3 -2 -2 -14 -9 -4 -4 -2 -5 -5 -3 -7 -6 -12 -6 -10 -3 -6 -2 -2 -19 -5 -4 -4 -9 -2 -4 -13 -3 -5 -6 -3 -6 -5 -4 -9 -6 -3 -5 -7 -3 -6 -6 -4 -3 -10 -6 -3 -221 -3 -5 -3 -6 -4 -8 -5 -3 -6 -4 -4 -2 -54 -5 -6 -11 -3 -3 -4 -4 -4 -3 -7 -3 -11 -11 -7 -10 -6 -13 -223 -213 -15 -231 -7 -3 -7 -228 -2 -3 -4 -4 -5 -6 -7 -4 -13 -3 -4 -5 -3 -6 -4 -6 -7 -2 -4 -3 -4 -3 -3 -6 -3 -7 -3 -5 -18 -5 -6 -8 -10 -3 -3 -3 -2 -4 -2 -4 -4 -5 -6 -6 -4 -10 -13 -3 -12 -5 -12 -16 -8 -4 -19 -11 -2 -4 -5 -6 -8 -5 -6 -4 -18 -10 -4 -2 -216 -6 -6 -6 -2 -4 -12 -8 -3 -11 -5 -6 -14 -5 -3 -13 -4 -5 -4 -5 -3 -28 -6 -3 -7 -219 -3 -9 -7 -3 -10 -6 -3 -4 -19 -5 -7 -11 -6 -15 -19 -4 -13 -11 -3 -7 -5 -10 -2 -8 -11 -2 -6 -4 -6 -24 -6 -3 -3 -3 -3 -6 -18 -4 -11 -4 -2 -5 -10 -8 -3 -9 -5 -3 -4 -5 -6 -2 -5 -7 -4 -4 -14 -6 -4 -4 -5 -5 -7 -2 -4 -3 -7 -3 -3 -6 -4 -5 -4 -4 -4 -3 -3 -3 -3 -8 -14 -2 -3 -5 -3 -2 -4 -5 -3 -7 -3 -3 -18 -3 -4 -4 -5 -7 -3 -3 -3 -13 -5 -4 -8 -211 -5 -5 -3 -5 -2 -5 -4 -2 -655 -6 -3 -5 -11 -2 -5 -3 -12 -9 -15 -11 -5 -12 -217 -2 -6 -17 -3 -3 -207 -5 -5 -4 -5 -9 -3 -2 -8 -5 -4 -3 -2 -5 -12 -4 -14 -5 -4 -2 -13 -5 -8 -4 -225 -4 -3 -4 -5 -4 -3 -3 -6 -23 -9 -2 -6 -7 -233 -4 -4 -6 -18 -3 -4 -6 -3 -4 -4 -2 -3 -7 -4 -13 -227 -4 -3 -5 -4 -2 -12 -9 -17 -3 -7 -14 -6 -4 -5 -21 -4 -8 -9 -2 -9 -25 -16 -3 -6 -4 -7 -8 -5 -2 -3 -5 -4 -3 -3 -5 -3 -3 -3 -2 -3 -19 -2 -4 -3 -4 -2 -3 -4 -4 -2 -4 -3 -3 -3 -2 -6 -3 -17 -5 -6 -4 -3 -13 -5 -3 -3 -3 -4 -9 -4 -2 -14 -12 -4 -5 -24 -4 -3 -37 -12 -11 -21 -3 -4 -3 -13 -4 -2 -3 -15 -4 -11 -4 -4 -3 -8 -3 -4 -4 -12 -8 -5 -3 -3 -4 -2 -220 -3 -5 -223 -3 -3 -3 -10 -3 -15 -4 -241 -9 -7 -3 -6 -6 -23 -4 -13 -7 -3 -4 -7 -4 -9 -3 -3 -4 -10 -5 -5 -1 -5 -24 -2 -4 -5 -5 -6 -14 -3 -8 -2 -3 -5 -13 -13 -3 -5 -2 -3 -15 -3 -4 -2 -10 -4 -4 -4 -5 -5 -3 -5 -3 -4 -7 -4 -27 -3 -6 -4 -15 -3 -5 -6 -6 -5 -4 -8 -3 -9 -2 -6 -3 -4 -3 -7 -4 -18 -3 -11 -3 -3 -8 -9 -7 -24 -3 -219 -7 -10 -4 -5 -9 -12 -2 -5 -4 -4 -4 -3 -3 -19 -5 -8 -16 -8 -6 -22 -3 -23 -3 -242 -9 -4 -3 -3 -5 -7 -3 -3 -5 -8 -3 -7 -5 -14 -8 -10 -3 -4 -3 -7 -4 -6 -7 -4 -10 -4 -3 -11 -3 -7 -10 -3 -13 -6 -8 -12 -10 -5 -7 -9 -3 -4 -7 -7 -10 -8 -30 -9 -19 -4 -3 -19 -15 -4 -13 -3 -215 -223 -4 -7 -4 -8 -17 -16 -3 -7 -6 -5 -5 -4 -12 -3 -7 -4 -4 -13 -4 -5 -2 -5 -6 -5 -6 -6 -7 -10 -18 -23 -9 -3 -3 -6 -5 -2 -4 -2 -7 -3 -3 -2 -5 -5 -14 -10 -224 -6 -3 -4 -3 -7 -5 -9 -3 -6 -4 -2 -5 -11 -4 -3 -3 -2 -8 -4 -7 -4 -10 -7 -3 -3 -18 -18 -17 -3 -3 -3 -4 -5 -3 -3 -4 -12 -7 -3 -11 -13 -5 -4 -7 -13 -5 -4 -11 -3 -12 -3 -6 -4 -4 -21 -4 -6 -9 -5 -3 -10 -8 -4 -6 -4 -4 -6 -5 -4 -8 -6 -4 -6 -4 -4 -5 -9 -6 -3 -4 -2 -9 -3 -18 -2 -4 -3 -13 -3 -6 -6 -8 -7 -9 -3 -2 -16 -3 -4 -6 -3 -2 -33 -22 -14 -4 -9 -12 -4 -5 -6 -3 -23 -9 -4 -3 -5 -5 -3 -4 -5 -3 -5 -3 -10 -4 -5 -5 -8 -4 -4 -6 -8 -5 -4 -3 -4 -6 -3 -3 -3 -5 -9 -12 -6 -5 -9 -3 -5 -3 -2 -2 -2 -18 -3 -2 -21 -2 -5 -4 -6 -4 -5 -10 -3 -9 -3 -2 -10 -7 -3 -6 -6 -4 -4 -8 -12 -7 -3 -7 -3 -3 -9 -3 -4 -5 -4 -4 -5 -5 -10 -15 -4 -4 -14 -6 -227 -3 -14 -5 -216 -22 -5 -4 -2 -2 -6 -3 -4 -2 -9 -9 -4 -3 -28 -13 -11 -4 -5 -3 -3 -2 -3 -3 -5 -3 -4 -3 -5 -23 -26 -3 -4 -5 -6 -4 -6 -3 -5 -5 -3 -4 -3 -2 -2 -2 -7 -14 -3 -6 -7 -17 -2 -2 -15 -14 -16 -4 -6 -7 -13 -6 -4 -5 -6 -16 -3 -3 -28 -3 -6 -15 -3 -9 -2 -4 -6 -3 -3 -22 -4 -12 -6 -7 -2 -5 -4 -10 -3 -16 -6 -9 -2 -5 -12 -7 -5 -5 -5 -5 -2 -11 -9 -17 -4 -3 -11 -7 -3 -5 -15 -4 -3 -4 -211 -8 -7 -5 -4 -7 -6 -7 -6 -3 -6 -5 -6 -5 -3 -4 -4 -26 -4 -6 -10 -4 -4 -3 -2 -3 -3 -4 -5 -9 -3 -9 -4 -4 -5 -5 -8 -2 -4 -2 -3 -8 -4 -11 -19 -5 -8 -6 -3 -5 -6 -12 -3 -2 -4 -16 -12 -3 -4 -4 -8 -6 -5 -6 -6 -219 -8 -222 -6 -16 -3 -13 -19 -5 -4 -3 -11 -6 -10 -4 -7 -7 -12 -5 -3 -3 -5 -6 -10 -3 -8 -2 -5 -4 -7 -2 -4 -4 -2 -12 -9 -6 -4 -2 -40 -2 -4 -10 -4 -223 -4 -2 -20 -6 -7 -24 -5 -4 -5 -2 -20 -16 -6 -5 -13 -2 -3 -3 -19 -3 -2 -4 -5 -6 -7 -11 -12 -5 -6 -7 -7 -3 -5 -3 -5 -3 -14 -3 -4 -4 -2 -11 -1 -7 -3 -9 -6 -11 -12 -5 -8 -6 -221 -4 -2 -12 -4 -3 -15 -4 -5 -226 -7 -218 -7 -5 -4 -5 -18 -4 -5 -9 -4 -4 -2 -9 -18 -18 -9 -5 -6 -6 -3 -3 -7 -3 -5 -4 -4 -4 -12 -3 -6 -31 -5 -4 -7 -3 -6 -5 -6 -5 -11 -2 -2 -11 -11 -6 -7 -5 -8 -7 -10 -5 -23 -7 -4 -3 -5 -34 -2 -5 -23 -7 -3 -6 -8 -4 -4 -4 -2 -5 -3 -8 -5 -4 -8 -25 -2 -3 -17 -8 -3 -4 -8 -7 -3 -15 -6 -5 -7 -21 -9 -5 -6 -6 -5 -3 -2 -3 -10 -3 -6 -3 -14 -7 -4 -4 -8 -7 -8 -2 -6 -12 -4 -213 -6 -5 -21 -8 -2 -5 -23 -3 -11 -2 -3 -6 -25 -2 -3 -6 -7 -6 -6 -4 -4 -6 -3 -17 -9 -7 -6 -4 -3 -10 -7 -2 -3 -3 -3 -11 -8 -3 -7 -6 -4 -14 -36 -3 -4 -3 -3 -22 -13 -21 -4 -2 -7 -4 -4 -17 -15 -3 -7 -11 -2 -4 -7 -6 -209 -6 -3 -2 -2 -24 -4 -9 -4 -3 -3 -3 -29 -2 -2 -4 -3 -3 -5 -4 -6 -3 -3 -2 -4 diff --git a/vendor/github.com/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go deleted file mode 100644 index d7d14f8eb..000000000 --- a/vendor/github.com/beorn7/perks/quantile/stream.go +++ /dev/null @@ -1,316 +0,0 @@ -// Package quantile computes approximate quantiles over an unbounded data -// stream within low memory and CPU bounds. -// -// A small amount of accuracy is traded to achieve the above properties. -// -// Multiple streams can be merged before calling Query to generate a single set -// of results. This is meaningful when the streams represent the same type of -// data. See Merge and Samples. -// -// For more detailed information about the algorithm used, see: -// -// Effective Computation of Biased Quantiles over Data Streams -// -// http://www.cs.rutgers.edu/~muthu/bquant.pdf -package quantile - -import ( - "math" - "sort" -) - -// Sample holds an observed value and meta information for compression. JSON -// tags have been added for convenience. -type Sample struct { - Value float64 `json:",string"` - Width float64 `json:",string"` - Delta float64 `json:",string"` -} - -// Samples represents a slice of samples. It implements sort.Interface. -type Samples []Sample - -func (a Samples) Len() int { return len(a) } -func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value } -func (a Samples) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -type invariant func(s *stream, r float64) float64 - -// NewLowBiased returns an initialized Stream for low-biased quantiles -// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but -// error guarantees can still be given even for the lower ranks of the data -// distribution. -// -// The provided epsilon is a relative error, i.e. the true quantile of a value -// returned by a query is guaranteed to be within (1±Epsilon)*Quantile. -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error -// properties. -func NewLowBiased(epsilon float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - return 2 * epsilon * r - } - return newStream(ƒ) -} - -// NewHighBiased returns an initialized Stream for high-biased quantiles -// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but -// error guarantees can still be given even for the higher ranks of the data -// distribution. -// -// The provided epsilon is a relative error, i.e. the true quantile of a value -// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile). -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error -// properties. -func NewHighBiased(epsilon float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - return 2 * epsilon * (s.n - r) - } - return newStream(ƒ) -} - -// NewTargeted returns an initialized Stream concerned with a particular set of -// quantile values that are supplied a priori. Knowing these a priori reduces -// space and computation time. The targets map maps the desired quantiles to -// their absolute errors, i.e. the true quantile of a value returned by a query -// is guaranteed to be within (Quantile±Epsilon). -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties. -func NewTargeted(targetMap map[float64]float64) *Stream { - // Convert map to slice to avoid slow iterations on a map. - // ƒ is called on the hot path, so converting the map to a slice - // beforehand results in significant CPU savings. - targets := targetMapToSlice(targetMap) - - ƒ := func(s *stream, r float64) float64 { - var m = math.MaxFloat64 - var f float64 - for _, t := range targets { - if t.quantile*s.n <= r { - f = (2 * t.epsilon * r) / t.quantile - } else { - f = (2 * t.epsilon * (s.n - r)) / (1 - t.quantile) - } - if f < m { - m = f - } - } - return m - } - return newStream(ƒ) -} - -type target struct { - quantile float64 - epsilon float64 -} - -func targetMapToSlice(targetMap map[float64]float64) []target { - targets := make([]target, 0, len(targetMap)) - - for quantile, epsilon := range targetMap { - t := target{ - quantile: quantile, - epsilon: epsilon, - } - targets = append(targets, t) - } - - return targets -} - -// Stream computes quantiles for a stream of float64s. It is not thread-safe by -// design. Take care when using across multiple goroutines. -type Stream struct { - *stream - b Samples - sorted bool -} - -func newStream(ƒ invariant) *Stream { - x := &stream{ƒ: ƒ} - return &Stream{x, make(Samples, 0, 500), true} -} - -// Insert inserts v into the stream. -func (s *Stream) Insert(v float64) { - s.insert(Sample{Value: v, Width: 1}) -} - -func (s *Stream) insert(sample Sample) { - s.b = append(s.b, sample) - s.sorted = false - if len(s.b) == cap(s.b) { - s.flush() - } -} - -// Query returns the computed qth percentiles value. If s was created with -// NewTargeted, and q is not in the set of quantiles provided a priori, Query -// will return an unspecified result. -func (s *Stream) Query(q float64) float64 { - if !s.flushed() { - // Fast path when there hasn't been enough data for a flush; - // this also yields better accuracy for small sets of data. - l := len(s.b) - if l == 0 { - return 0 - } - i := int(math.Ceil(float64(l) * q)) - if i > 0 { - i -= 1 - } - s.maybeSort() - return s.b[i].Value - } - s.flush() - return s.stream.query(q) -} - -// Merge merges samples into the underlying streams samples. This is handy when -// merging multiple streams from separate threads, database shards, etc. -// -// ATTENTION: This method is broken and does not yield correct results. The -// underlying algorithm is not capable of merging streams correctly. -func (s *Stream) Merge(samples Samples) { - sort.Sort(samples) - s.stream.merge(samples) -} - -// Reset reinitializes and clears the list reusing the samples buffer memory. -func (s *Stream) Reset() { - s.stream.reset() - s.b = s.b[:0] -} - -// Samples returns stream samples held by s. -func (s *Stream) Samples() Samples { - if !s.flushed() { - return s.b - } - s.flush() - return s.stream.samples() -} - -// Count returns the total number of samples observed in the stream -// since initialization. -func (s *Stream) Count() int { - return len(s.b) + s.stream.count() -} - -func (s *Stream) flush() { - s.maybeSort() - s.stream.merge(s.b) - s.b = s.b[:0] -} - -func (s *Stream) maybeSort() { - if !s.sorted { - s.sorted = true - sort.Sort(s.b) - } -} - -func (s *Stream) flushed() bool { - return len(s.stream.l) > 0 -} - -type stream struct { - n float64 - l []Sample - ƒ invariant -} - -func (s *stream) reset() { - s.l = s.l[:0] - s.n = 0 -} - -func (s *stream) insert(v float64) { - s.merge(Samples{{v, 1, 0}}) -} - -func (s *stream) merge(samples Samples) { - // TODO(beorn7): This tries to merge not only individual samples, but - // whole summaries. The paper doesn't mention merging summaries at - // all. Unittests show that the merging is inaccurate. Find out how to - // do merges properly. - var r float64 - i := 0 - for _, sample := range samples { - for ; i < len(s.l); i++ { - c := s.l[i] - if c.Value > sample.Value { - // Insert at position i. - s.l = append(s.l, Sample{}) - copy(s.l[i+1:], s.l[i:]) - s.l[i] = Sample{ - sample.Value, - sample.Width, - math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1), - // TODO(beorn7): How to calculate delta correctly? - } - i++ - goto inserted - } - r += c.Width - } - s.l = append(s.l, Sample{sample.Value, sample.Width, 0}) - i++ - inserted: - s.n += sample.Width - r += sample.Width - } - s.compress() -} - -func (s *stream) count() int { - return int(s.n) -} - -func (s *stream) query(q float64) float64 { - t := math.Ceil(q * s.n) - t += math.Ceil(s.ƒ(s, t) / 2) - p := s.l[0] - var r float64 - for _, c := range s.l[1:] { - r += p.Width - if r+c.Width+c.Delta > t { - return p.Value - } - p = c - } - return p.Value -} - -func (s *stream) compress() { - if len(s.l) < 2 { - return - } - x := s.l[len(s.l)-1] - xi := len(s.l) - 1 - r := s.n - 1 - x.Width - - for i := len(s.l) - 2; i >= 0; i-- { - c := s.l[i] - if c.Width+x.Width+x.Delta <= s.ƒ(s, r) { - x.Width += c.Width - s.l[xi] = x - // Remove element at i. - copy(s.l[i:], s.l[i+1:]) - s.l = s.l[:len(s.l)-1] - xi -= 1 - } else { - x = c - xi = i - } - r -= c.Width - } -} - -func (s *stream) samples() Samples { - samples := make(Samples, len(s.l)) - copy(samples, s.l) - return samples -} diff --git a/vendor/github.com/cespare/xxhash/v2/LICENSE.txt b/vendor/github.com/cespare/xxhash/v2/LICENSE.txt deleted file mode 100644 index 24b53065f..000000000 --- a/vendor/github.com/cespare/xxhash/v2/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2016 Caleb Spare - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/cespare/xxhash/v2/README.md b/vendor/github.com/cespare/xxhash/v2/README.md deleted file mode 100644 index 33c88305c..000000000 --- a/vendor/github.com/cespare/xxhash/v2/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# xxhash - -[![Go Reference](https://pkg.go.dev/badge/github.com/cespare/xxhash/v2.svg)](https://pkg.go.dev/github.com/cespare/xxhash/v2) -[![Test](https://github.com/cespare/xxhash/actions/workflows/test.yml/badge.svg)](https://github.com/cespare/xxhash/actions/workflows/test.yml) - -xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a -high-quality hashing algorithm that is much faster than anything in the Go -standard library. - -This package provides a straightforward API: - -``` -func Sum64(b []byte) uint64 -func Sum64String(s string) uint64 -type Digest struct{ ... } - func New() *Digest -``` - -The `Digest` type implements hash.Hash64. Its key methods are: - -``` -func (*Digest) Write([]byte) (int, error) -func (*Digest) WriteString(string) (int, error) -func (*Digest) Sum64() uint64 -``` - -The package is written with optimized pure Go and also contains even faster -assembly implementations for amd64 and arm64. If desired, the `purego` build tag -opts into using the Go code even on those architectures. - -[xxHash]: http://cyan4973.github.io/xxHash/ - -## Compatibility - -This package is in a module and the latest code is in version 2 of the module. -You need a version of Go with at least "minimal module compatibility" to use -github.com/cespare/xxhash/v2: - -* 1.9.7+ for Go 1.9 -* 1.10.3+ for Go 1.10 -* Go 1.11 or later - -I recommend using the latest release of Go. - -## Benchmarks - -Here are some quick benchmarks comparing the pure-Go and assembly -implementations of Sum64. - -| input size | purego | asm | -| ---------- | --------- | --------- | -| 4 B | 1.3 GB/s | 1.2 GB/s | -| 16 B | 2.9 GB/s | 3.5 GB/s | -| 100 B | 6.9 GB/s | 8.1 GB/s | -| 4 KB | 11.7 GB/s | 16.7 GB/s | -| 10 MB | 12.0 GB/s | 17.3 GB/s | - -These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C -CPU using the following commands under Go 1.19.2: - -``` -benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') -benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') -``` - -## Projects using this package - -- [InfluxDB](https://github.com/influxdata/influxdb) -- [Prometheus](https://github.com/prometheus/prometheus) -- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics) -- [FreeCache](https://github.com/coocood/freecache) -- [FastCache](https://github.com/VictoriaMetrics/fastcache) -- [Ristretto](https://github.com/dgraph-io/ristretto) -- [Badger](https://github.com/dgraph-io/badger) diff --git a/vendor/github.com/cespare/xxhash/v2/testall.sh b/vendor/github.com/cespare/xxhash/v2/testall.sh deleted file mode 100644 index 94b9c4439..000000000 --- a/vendor/github.com/cespare/xxhash/v2/testall.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -set -eu -o pipefail - -# Small convenience script for running the tests with various combinations of -# arch/tags. This assumes we're running on amd64 and have qemu available. - -go test ./... -go test -tags purego ./... -GOARCH=arm64 go test -GOARCH=arm64 go test -tags purego diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash.go b/vendor/github.com/cespare/xxhash/v2/xxhash.go deleted file mode 100644 index 78bddf1ce..000000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash.go +++ /dev/null @@ -1,243 +0,0 @@ -// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described -// at http://cyan4973.github.io/xxHash/. -package xxhash - -import ( - "encoding/binary" - "errors" - "math/bits" -) - -const ( - prime1 uint64 = 11400714785074694791 - prime2 uint64 = 14029467366897019727 - prime3 uint64 = 1609587929392839161 - prime4 uint64 = 9650029242287828579 - prime5 uint64 = 2870177450012600261 -) - -// Store the primes in an array as well. -// -// The consts are used when possible in Go code to avoid MOVs but we need a -// contiguous array for the assembly code. -var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5} - -// Digest implements hash.Hash64. -// -// Note that a zero-valued Digest is not ready to receive writes. -// Call Reset or create a Digest using New before calling other methods. -type Digest struct { - v1 uint64 - v2 uint64 - v3 uint64 - v4 uint64 - total uint64 - mem [32]byte - n int // how much of mem is used -} - -// New creates a new Digest with a zero seed. -func New() *Digest { - return NewWithSeed(0) -} - -// NewWithSeed creates a new Digest with the given seed. -func NewWithSeed(seed uint64) *Digest { - var d Digest - d.ResetWithSeed(seed) - return &d -} - -// Reset clears the Digest's state so that it can be reused. -// It uses a seed value of zero. -func (d *Digest) Reset() { - d.ResetWithSeed(0) -} - -// ResetWithSeed clears the Digest's state so that it can be reused. -// It uses the given seed to initialize the state. -func (d *Digest) ResetWithSeed(seed uint64) { - d.v1 = seed + prime1 + prime2 - d.v2 = seed + prime2 - d.v3 = seed - d.v4 = seed - prime1 - d.total = 0 - d.n = 0 -} - -// Size always returns 8 bytes. -func (d *Digest) Size() int { return 8 } - -// BlockSize always returns 32 bytes. -func (d *Digest) BlockSize() int { return 32 } - -// Write adds more data to d. It always returns len(b), nil. -func (d *Digest) Write(b []byte) (n int, err error) { - n = len(b) - d.total += uint64(n) - - memleft := d.mem[d.n&(len(d.mem)-1):] - - if d.n+n < 32 { - // This new data doesn't even fill the current block. - copy(memleft, b) - d.n += n - return - } - - if d.n > 0 { - // Finish off the partial block. - c := copy(memleft, b) - d.v1 = round(d.v1, u64(d.mem[0:8])) - d.v2 = round(d.v2, u64(d.mem[8:16])) - d.v3 = round(d.v3, u64(d.mem[16:24])) - d.v4 = round(d.v4, u64(d.mem[24:32])) - b = b[c:] - d.n = 0 - } - - if len(b) >= 32 { - // One or more full blocks left. - nw := writeBlocks(d, b) - b = b[nw:] - } - - // Store any remaining partial block. - copy(d.mem[:], b) - d.n = len(b) - - return -} - -// Sum appends the current hash to b and returns the resulting slice. -func (d *Digest) Sum(b []byte) []byte { - s := d.Sum64() - return append( - b, - byte(s>>56), - byte(s>>48), - byte(s>>40), - byte(s>>32), - byte(s>>24), - byte(s>>16), - byte(s>>8), - byte(s), - ) -} - -// Sum64 returns the current hash. -func (d *Digest) Sum64() uint64 { - var h uint64 - - if d.total >= 32 { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = d.v3 + prime5 - } - - h += d.total - - b := d.mem[:d.n&(len(d.mem)-1)] - for ; len(b) >= 8; b = b[8:] { - k1 := round(0, u64(b[:8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if len(b) >= 4 { - h ^= uint64(u32(b[:4])) * prime1 - h = rol23(h)*prime2 + prime3 - b = b[4:] - } - for ; len(b) > 0; b = b[1:] { - h ^= uint64(b[0]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -const ( - magic = "xxh\x06" - marshaledSize = len(magic) + 8*5 + 32 -) - -// MarshalBinary implements the encoding.BinaryMarshaler interface. -func (d *Digest) MarshalBinary() ([]byte, error) { - b := make([]byte, 0, marshaledSize) - b = append(b, magic...) - b = appendUint64(b, d.v1) - b = appendUint64(b, d.v2) - b = appendUint64(b, d.v3) - b = appendUint64(b, d.v4) - b = appendUint64(b, d.total) - b = append(b, d.mem[:d.n]...) - b = b[:len(b)+len(d.mem)-d.n] - return b, nil -} - -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. -func (d *Digest) UnmarshalBinary(b []byte) error { - if len(b) < len(magic) || string(b[:len(magic)]) != magic { - return errors.New("xxhash: invalid hash state identifier") - } - if len(b) != marshaledSize { - return errors.New("xxhash: invalid hash state size") - } - b = b[len(magic):] - b, d.v1 = consumeUint64(b) - b, d.v2 = consumeUint64(b) - b, d.v3 = consumeUint64(b) - b, d.v4 = consumeUint64(b) - b, d.total = consumeUint64(b) - copy(d.mem[:], b) - d.n = int(d.total % uint64(len(d.mem))) - return nil -} - -func appendUint64(b []byte, x uint64) []byte { - var a [8]byte - binary.LittleEndian.PutUint64(a[:], x) - return append(b, a[:]...) -} - -func consumeUint64(b []byte) ([]byte, uint64) { - x := u64(b) - return b[8:], x -} - -func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } -func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } - -func round(acc, input uint64) uint64 { - acc += input * prime2 - acc = rol31(acc) - acc *= prime1 - return acc -} - -func mergeRound(acc, val uint64) uint64 { - val = round(0, val) - acc ^= val - acc = acc*prime1 + prime4 - return acc -} - -func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } -func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } -func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) } -func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) } -func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) } -func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) } -func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) } -func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) } diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s b/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s deleted file mode 100644 index 3e8b13257..000000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s +++ /dev/null @@ -1,209 +0,0 @@ -//go:build !appengine && gc && !purego -// +build !appengine -// +build gc -// +build !purego - -#include "textflag.h" - -// Registers: -#define h AX -#define d AX -#define p SI // pointer to advance through b -#define n DX -#define end BX // loop end -#define v1 R8 -#define v2 R9 -#define v3 R10 -#define v4 R11 -#define x R12 -#define prime1 R13 -#define prime2 R14 -#define prime4 DI - -#define round(acc, x) \ - IMULQ prime2, x \ - ADDQ x, acc \ - ROLQ $31, acc \ - IMULQ prime1, acc - -// round0 performs the operation x = round(0, x). -#define round0(x) \ - IMULQ prime2, x \ - ROLQ $31, x \ - IMULQ prime1, x - -// mergeRound applies a merge round on the two registers acc and x. -// It assumes that prime1, prime2, and prime4 have been loaded. -#define mergeRound(acc, x) \ - round0(x) \ - XORQ x, acc \ - IMULQ prime1, acc \ - ADDQ prime4, acc - -// blockLoop processes as many 32-byte blocks as possible, -// updating v1, v2, v3, and v4. It assumes that there is at least one block -// to process. -#define blockLoop() \ -loop: \ - MOVQ +0(p), x \ - round(v1, x) \ - MOVQ +8(p), x \ - round(v2, x) \ - MOVQ +16(p), x \ - round(v3, x) \ - MOVQ +24(p), x \ - round(v4, x) \ - ADDQ $32, p \ - CMPQ p, end \ - JLE loop - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 - // Load fixed primes. - MOVQ ·primes+0(SB), prime1 - MOVQ ·primes+8(SB), prime2 - MOVQ ·primes+24(SB), prime4 - - // Load slice. - MOVQ b_base+0(FP), p - MOVQ b_len+8(FP), n - LEAQ (p)(n*1), end - - // The first loop limit will be len(b)-32. - SUBQ $32, end - - // Check whether we have at least one block. - CMPQ n, $32 - JLT noBlocks - - // Set up initial state (v1, v2, v3, v4). - MOVQ prime1, v1 - ADDQ prime2, v1 - MOVQ prime2, v2 - XORQ v3, v3 - XORQ v4, v4 - SUBQ prime1, v4 - - blockLoop() - - MOVQ v1, h - ROLQ $1, h - MOVQ v2, x - ROLQ $7, x - ADDQ x, h - MOVQ v3, x - ROLQ $12, x - ADDQ x, h - MOVQ v4, x - ROLQ $18, x - ADDQ x, h - - mergeRound(h, v1) - mergeRound(h, v2) - mergeRound(h, v3) - mergeRound(h, v4) - - JMP afterBlocks - -noBlocks: - MOVQ ·primes+32(SB), h - -afterBlocks: - ADDQ n, h - - ADDQ $24, end - CMPQ p, end - JG try4 - -loop8: - MOVQ (p), x - ADDQ $8, p - round0(x) - XORQ x, h - ROLQ $27, h - IMULQ prime1, h - ADDQ prime4, h - - CMPQ p, end - JLE loop8 - -try4: - ADDQ $4, end - CMPQ p, end - JG try1 - - MOVL (p), x - ADDQ $4, p - IMULQ prime1, x - XORQ x, h - - ROLQ $23, h - IMULQ prime2, h - ADDQ ·primes+16(SB), h - -try1: - ADDQ $4, end - CMPQ p, end - JGE finalize - -loop1: - MOVBQZX (p), x - ADDQ $1, p - IMULQ ·primes+32(SB), x - XORQ x, h - ROLQ $11, h - IMULQ prime1, h - - CMPQ p, end - JL loop1 - -finalize: - MOVQ h, x - SHRQ $33, x - XORQ x, h - IMULQ prime2, h - MOVQ h, x - SHRQ $29, x - XORQ x, h - IMULQ ·primes+16(SB), h - MOVQ h, x - SHRQ $32, x - XORQ x, h - - MOVQ h, ret+24(FP) - RET - -// func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 - // Load fixed primes needed for round. - MOVQ ·primes+0(SB), prime1 - MOVQ ·primes+8(SB), prime2 - - // Load slice. - MOVQ b_base+8(FP), p - MOVQ b_len+16(FP), n - LEAQ (p)(n*1), end - SUBQ $32, end - - // Load vN from d. - MOVQ s+0(FP), d - MOVQ 0(d), v1 - MOVQ 8(d), v2 - MOVQ 16(d), v3 - MOVQ 24(d), v4 - - // We don't need to check the loop condition here; this function is - // always called with at least one block of data to process. - blockLoop() - - // Copy vN back to d. - MOVQ v1, 0(d) - MOVQ v2, 8(d) - MOVQ v3, 16(d) - MOVQ v4, 24(d) - - // The number of bytes written is p minus the old base pointer. - SUBQ b_base+8(FP), p - MOVQ p, ret+32(FP) - - RET diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s b/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s deleted file mode 100644 index 7e3145a22..000000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s +++ /dev/null @@ -1,183 +0,0 @@ -//go:build !appengine && gc && !purego -// +build !appengine -// +build gc -// +build !purego - -#include "textflag.h" - -// Registers: -#define digest R1 -#define h R2 // return value -#define p R3 // input pointer -#define n R4 // input length -#define nblocks R5 // n / 32 -#define prime1 R7 -#define prime2 R8 -#define prime3 R9 -#define prime4 R10 -#define prime5 R11 -#define v1 R12 -#define v2 R13 -#define v3 R14 -#define v4 R15 -#define x1 R20 -#define x2 R21 -#define x3 R22 -#define x4 R23 - -#define round(acc, x) \ - MADD prime2, acc, x, acc \ - ROR $64-31, acc \ - MUL prime1, acc - -// round0 performs the operation x = round(0, x). -#define round0(x) \ - MUL prime2, x \ - ROR $64-31, x \ - MUL prime1, x - -#define mergeRound(acc, x) \ - round0(x) \ - EOR x, acc \ - MADD acc, prime4, prime1, acc - -// blockLoop processes as many 32-byte blocks as possible, -// updating v1, v2, v3, and v4. It assumes that n >= 32. -#define blockLoop() \ - LSR $5, n, nblocks \ - PCALIGN $16 \ - loop: \ - LDP.P 16(p), (x1, x2) \ - LDP.P 16(p), (x3, x4) \ - round(v1, x1) \ - round(v2, x2) \ - round(v3, x3) \ - round(v4, x4) \ - SUB $1, nblocks \ - CBNZ nblocks, loop - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 - LDP b_base+0(FP), (p, n) - - LDP ·primes+0(SB), (prime1, prime2) - LDP ·primes+16(SB), (prime3, prime4) - MOVD ·primes+32(SB), prime5 - - CMP $32, n - CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 } - BLT afterLoop - - ADD prime1, prime2, v1 - MOVD prime2, v2 - MOVD $0, v3 - NEG prime1, v4 - - blockLoop() - - ROR $64-1, v1, x1 - ROR $64-7, v2, x2 - ADD x1, x2 - ROR $64-12, v3, x3 - ROR $64-18, v4, x4 - ADD x3, x4 - ADD x2, x4, h - - mergeRound(h, v1) - mergeRound(h, v2) - mergeRound(h, v3) - mergeRound(h, v4) - -afterLoop: - ADD n, h - - TBZ $4, n, try8 - LDP.P 16(p), (x1, x2) - - round0(x1) - - // NOTE: here and below, sequencing the EOR after the ROR (using a - // rotated register) is worth a small but measurable speedup for small - // inputs. - ROR $64-27, h - EOR x1 @> 64-27, h, h - MADD h, prime4, prime1, h - - round0(x2) - ROR $64-27, h - EOR x2 @> 64-27, h, h - MADD h, prime4, prime1, h - -try8: - TBZ $3, n, try4 - MOVD.P 8(p), x1 - - round0(x1) - ROR $64-27, h - EOR x1 @> 64-27, h, h - MADD h, prime4, prime1, h - -try4: - TBZ $2, n, try2 - MOVWU.P 4(p), x2 - - MUL prime1, x2 - ROR $64-23, h - EOR x2 @> 64-23, h, h - MADD h, prime3, prime2, h - -try2: - TBZ $1, n, try1 - MOVHU.P 2(p), x3 - AND $255, x3, x1 - LSR $8, x3, x2 - - MUL prime5, x1 - ROR $64-11, h - EOR x1 @> 64-11, h, h - MUL prime1, h - - MUL prime5, x2 - ROR $64-11, h - EOR x2 @> 64-11, h, h - MUL prime1, h - -try1: - TBZ $0, n, finalize - MOVBU (p), x4 - - MUL prime5, x4 - ROR $64-11, h - EOR x4 @> 64-11, h, h - MUL prime1, h - -finalize: - EOR h >> 33, h - MUL prime2, h - EOR h >> 29, h - MUL prime3, h - EOR h >> 32, h - - MOVD h, ret+24(FP) - RET - -// func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 - LDP ·primes+0(SB), (prime1, prime2) - - // Load state. Assume v[1-4] are stored contiguously. - MOVD d+0(FP), digest - LDP 0(digest), (v1, v2) - LDP 16(digest), (v3, v4) - - LDP b_base+8(FP), (p, n) - - blockLoop() - - // Store updated state. - STP (v1, v2), 0(digest) - STP (v3, v4), 16(digest) - - BIC $31, n - MOVD n, ret+32(FP) - RET diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go b/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go deleted file mode 100644 index 78f95f256..000000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build (amd64 || arm64) && !appengine && gc && !purego -// +build amd64 arm64 -// +build !appengine -// +build gc -// +build !purego - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b with a zero seed. -// -//go:noescape -func Sum64(b []byte) uint64 - -//go:noescape -func writeBlocks(d *Digest, b []byte) int diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_other.go b/vendor/github.com/cespare/xxhash/v2/xxhash_other.go deleted file mode 100644 index 118e49e81..000000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_other.go +++ /dev/null @@ -1,76 +0,0 @@ -//go:build (!amd64 && !arm64) || appengine || !gc || purego -// +build !amd64,!arm64 appengine !gc purego - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b with a zero seed. -func Sum64(b []byte) uint64 { - // A simpler version would be - // d := New() - // d.Write(b) - // return d.Sum64() - // but this is faster, particularly for small inputs. - - n := len(b) - var h uint64 - - if n >= 32 { - v1 := primes[0] + prime2 - v2 := prime2 - v3 := uint64(0) - v4 := -primes[0] - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = prime5 - } - - h += uint64(n) - - for ; len(b) >= 8; b = b[8:] { - k1 := round(0, u64(b[:8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if len(b) >= 4 { - h ^= uint64(u32(b[:4])) * prime1 - h = rol23(h)*prime2 + prime3 - b = b[4:] - } - for ; len(b) > 0; b = b[1:] { - h ^= uint64(b[0]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -func writeBlocks(d *Digest, b []byte) int { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - n := len(b) - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4 - return n - len(b) -} diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go b/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go deleted file mode 100644 index 05f5e7dfe..000000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build appengine -// +build appengine - -// This file contains the safe implementations of otherwise unsafe-using code. - -package xxhash - -// Sum64String computes the 64-bit xxHash digest of s with a zero seed. -func Sum64String(s string) uint64 { - return Sum64([]byte(s)) -} - -// WriteString adds more data to d. It always returns len(s), nil. -func (d *Digest) WriteString(s string) (n int, err error) { - return d.Write([]byte(s)) -} diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go b/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go deleted file mode 100644 index cf9d42aed..000000000 --- a/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go +++ /dev/null @@ -1,58 +0,0 @@ -//go:build !appengine -// +build !appengine - -// This file encapsulates usage of unsafe. -// xxhash_safe.go contains the safe implementations. - -package xxhash - -import ( - "unsafe" -) - -// In the future it's possible that compiler optimizations will make these -// XxxString functions unnecessary by realizing that calls such as -// Sum64([]byte(s)) don't need to copy s. See https://go.dev/issue/2205. -// If that happens, even if we keep these functions they can be replaced with -// the trivial safe code. - -// NOTE: The usual way of doing an unsafe string-to-[]byte conversion is: -// -// var b []byte -// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) -// bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data -// bh.Len = len(s) -// bh.Cap = len(s) -// -// Unfortunately, as of Go 1.15.3 the inliner's cost model assigns a high enough -// weight to this sequence of expressions that any function that uses it will -// not be inlined. Instead, the functions below use a different unsafe -// conversion designed to minimize the inliner weight and allow both to be -// inlined. There is also a test (TestInlining) which verifies that these are -// inlined. -// -// See https://github.com/golang/go/issues/42739 for discussion. - -// Sum64String computes the 64-bit xxHash digest of s with a zero seed. -// It may be faster than Sum64([]byte(s)) by avoiding a copy. -func Sum64String(s string) uint64 { - b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)})) - return Sum64(b) -} - -// WriteString adds more data to d. It always returns len(s), nil. -// It may be faster than Write([]byte(s)) by avoiding a copy. -func (d *Digest) WriteString(s string) (n int, err error) { - d.Write(*(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))) - // d.Write always returns len(s), nil. - // Ignoring the return output and returning these fixed values buys a - // savings of 6 in the inliner's cost model. - return len(s), nil -} - -// sliceHeader is similar to reflect.SliceHeader, but it assumes that the layout -// of the first two words is the same as the layout of a string. -type sliceHeader struct { - s string - cap int -} diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE deleted file mode 100644 index bc52e96f2..000000000 --- a/vendor/github.com/davecgh/go-spew/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -ISC License - -Copyright (c) 2012-2016 Dave Collins - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go deleted file mode 100644 index 792994785..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) 2015-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// Go versions prior to 1.4 are disabled because they use a different layout -// for interfaces which make the implementation of unsafeReflectValue more complex. -// +build !js,!appengine,!safe,!disableunsafe,go1.4 - -package spew - -import ( - "reflect" - "unsafe" -) - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = false - - // ptrSize is the size of a pointer on the current arch. - ptrSize = unsafe.Sizeof((*byte)(nil)) -) - -type flag uintptr - -var ( - // flagRO indicates whether the value field of a reflect.Value - // is read-only. - flagRO flag - - // flagAddr indicates whether the address of the reflect.Value's - // value may be taken. - flagAddr flag -) - -// flagKindMask holds the bits that make up the kind -// part of the flags field. In all the supported versions, -// it is in the lower 5 bits. -const flagKindMask = flag(0x1f) - -// Different versions of Go have used different -// bit layouts for the flags type. This table -// records the known combinations. -var okFlags = []struct { - ro, addr flag -}{{ - // From Go 1.4 to 1.5 - ro: 1 << 5, - addr: 1 << 7, -}, { - // Up to Go tip. - ro: 1<<5 | 1<<6, - addr: 1 << 8, -}} - -var flagValOffset = func() uintptr { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - return field.Offset -}() - -// flagField returns a pointer to the flag field of a reflect.Value. -func flagField(v *reflect.Value) *flag { - return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) -} - -// unsafeReflectValue converts the passed reflect.Value into a one that bypasses -// the typical safety restrictions preventing access to unaddressable and -// unexported data. It works by digging the raw pointer to the underlying -// value out of the protected value and generating a new unprotected (unsafe) -// reflect.Value to it. -// -// This allows us to check for implementations of the Stringer and error -// interfaces to be used for pretty printing ordinarily unaddressable and -// inaccessible values such as unexported struct fields. -func unsafeReflectValue(v reflect.Value) reflect.Value { - if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { - return v - } - flagFieldPtr := flagField(&v) - *flagFieldPtr &^= flagRO - *flagFieldPtr |= flagAddr - return v -} - -// Sanity checks against future reflect package changes -// to the type or semantics of the Value.flag field. -func init() { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { - panic("reflect.Value flag field has changed kind") - } - type t0 int - var t struct { - A t0 - // t0 will have flagEmbedRO set. - t0 - // a will have flagStickyRO set - a t0 - } - vA := reflect.ValueOf(t).FieldByName("A") - va := reflect.ValueOf(t).FieldByName("a") - vt0 := reflect.ValueOf(t).FieldByName("t0") - - // Infer flagRO from the difference between the flags - // for the (otherwise identical) fields in t. - flagPublic := *flagField(&vA) - flagWithRO := *flagField(&va) | *flagField(&vt0) - flagRO = flagPublic ^ flagWithRO - - // Infer flagAddr from the difference between a value - // taken from a pointer and not. - vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") - flagNoPtr := *flagField(&vA) - flagPtr := *flagField(&vPtrA) - flagAddr = flagNoPtr ^ flagPtr - - // Check that the inferred flags tally with one of the known versions. - for _, f := range okFlags { - if flagRO == f.ro && flagAddr == f.addr { - return - } - } - panic("reflect.Value read-only flag has changed semantics") -} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go deleted file mode 100644 index 205c28d68..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2015-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is running on Google App Engine, compiled by GopherJS, or -// "-tags safe" is added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build js appengine safe disableunsafe !go1.4 - -package spew - -import "reflect" - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = true -) - -// unsafeReflectValue typically converts the passed reflect.Value into a one -// that bypasses the typical safety restrictions preventing access to -// unaddressable and unexported data. However, doing this relies on access to -// the unsafe package. This is a stub version which simply returns the passed -// reflect.Value when the unsafe package is not available. -func unsafeReflectValue(v reflect.Value) reflect.Value { - return v -} diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go deleted file mode 100644 index 1be8ce945..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/common.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "io" - "reflect" - "sort" - "strconv" -) - -// Some constants in the form of bytes to avoid string overhead. This mirrors -// the technique used in the fmt package. -var ( - panicBytes = []byte("(PANIC=") - plusBytes = []byte("+") - iBytes = []byte("i") - trueBytes = []byte("true") - falseBytes = []byte("false") - interfaceBytes = []byte("(interface {})") - commaNewlineBytes = []byte(",\n") - newlineBytes = []byte("\n") - openBraceBytes = []byte("{") - openBraceNewlineBytes = []byte("{\n") - closeBraceBytes = []byte("}") - asteriskBytes = []byte("*") - colonBytes = []byte(":") - colonSpaceBytes = []byte(": ") - openParenBytes = []byte("(") - closeParenBytes = []byte(")") - spaceBytes = []byte(" ") - pointerChainBytes = []byte("->") - nilAngleBytes = []byte("") - maxNewlineBytes = []byte("\n") - maxShortBytes = []byte("") - circularBytes = []byte("") - circularShortBytes = []byte("") - invalidAngleBytes = []byte("") - openBracketBytes = []byte("[") - closeBracketBytes = []byte("]") - percentBytes = []byte("%") - precisionBytes = []byte(".") - openAngleBytes = []byte("<") - closeAngleBytes = []byte(">") - openMapBytes = []byte("map[") - closeMapBytes = []byte("]") - lenEqualsBytes = []byte("len=") - capEqualsBytes = []byte("cap=") -) - -// hexDigits is used to map a decimal value to a hex digit. -var hexDigits = "0123456789abcdef" - -// catchPanic handles any panics that might occur during the handleMethods -// calls. -func catchPanic(w io.Writer, v reflect.Value) { - if err := recover(); err != nil { - w.Write(panicBytes) - fmt.Fprintf(w, "%v", err) - w.Write(closeParenBytes) - } -} - -// handleMethods attempts to call the Error and String methods on the underlying -// type the passed reflect.Value represents and outputes the result to Writer w. -// -// It handles panics in any called methods by catching and displaying the error -// as the formatted value. -func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { - // We need an interface to check if the type implements the error or - // Stringer interface. However, the reflect package won't give us an - // interface on certain things like unexported struct fields in order - // to enforce visibility rules. We use unsafe, when it's available, - // to bypass these restrictions since this package does not mutate the - // values. - if !v.CanInterface() { - if UnsafeDisabled { - return false - } - - v = unsafeReflectValue(v) - } - - // Choose whether or not to do error and Stringer interface lookups against - // the base type or a pointer to the base type depending on settings. - // Technically calling one of these methods with a pointer receiver can - // mutate the value, however, types which choose to satisify an error or - // Stringer interface with a pointer receiver should not be mutating their - // state inside these interface methods. - if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { - v = unsafeReflectValue(v) - } - if v.CanAddr() { - v = v.Addr() - } - - // Is it an error or Stringer? - switch iface := v.Interface().(type) { - case error: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.Error())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - - w.Write([]byte(iface.Error())) - return true - - case fmt.Stringer: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.String())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - w.Write([]byte(iface.String())) - return true - } - return false -} - -// printBool outputs a boolean value as true or false to Writer w. -func printBool(w io.Writer, val bool) { - if val { - w.Write(trueBytes) - } else { - w.Write(falseBytes) - } -} - -// printInt outputs a signed integer value to Writer w. -func printInt(w io.Writer, val int64, base int) { - w.Write([]byte(strconv.FormatInt(val, base))) -} - -// printUint outputs an unsigned integer value to Writer w. -func printUint(w io.Writer, val uint64, base int) { - w.Write([]byte(strconv.FormatUint(val, base))) -} - -// printFloat outputs a floating point value using the specified precision, -// which is expected to be 32 or 64bit, to Writer w. -func printFloat(w io.Writer, val float64, precision int) { - w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) -} - -// printComplex outputs a complex value using the specified float precision -// for the real and imaginary parts to Writer w. -func printComplex(w io.Writer, c complex128, floatPrecision int) { - r := real(c) - w.Write(openParenBytes) - w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) - i := imag(c) - if i >= 0 { - w.Write(plusBytes) - } - w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) - w.Write(iBytes) - w.Write(closeParenBytes) -} - -// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' -// prefix to Writer w. -func printHexPtr(w io.Writer, p uintptr) { - // Null pointer. - num := uint64(p) - if num == 0 { - w.Write(nilAngleBytes) - return - } - - // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix - buf := make([]byte, 18) - - // It's simpler to construct the hex string right to left. - base := uint64(16) - i := len(buf) - 1 - for num >= base { - buf[i] = hexDigits[num%base] - num /= base - i-- - } - buf[i] = hexDigits[num] - - // Add '0x' prefix. - i-- - buf[i] = 'x' - i-- - buf[i] = '0' - - // Strip unused leading bytes. - buf = buf[i:] - w.Write(buf) -} - -// valuesSorter implements sort.Interface to allow a slice of reflect.Value -// elements to be sorted. -type valuesSorter struct { - values []reflect.Value - strings []string // either nil or same len and values - cs *ConfigState -} - -// newValuesSorter initializes a valuesSorter instance, which holds a set of -// surrogate keys on which the data should be sorted. It uses flags in -// ConfigState to decide if and how to populate those surrogate keys. -func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { - vs := &valuesSorter{values: values, cs: cs} - if canSortSimply(vs.values[0].Kind()) { - return vs - } - if !cs.DisableMethods { - vs.strings = make([]string, len(values)) - for i := range vs.values { - b := bytes.Buffer{} - if !handleMethods(cs, &b, vs.values[i]) { - vs.strings = nil - break - } - vs.strings[i] = b.String() - } - } - if vs.strings == nil && cs.SpewKeys { - vs.strings = make([]string, len(values)) - for i := range vs.values { - vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) - } - } - return vs -} - -// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted -// directly, or whether it should be considered for sorting by surrogate keys -// (if the ConfigState allows it). -func canSortSimply(kind reflect.Kind) bool { - // This switch parallels valueSortLess, except for the default case. - switch kind { - case reflect.Bool: - return true - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return true - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return true - case reflect.Float32, reflect.Float64: - return true - case reflect.String: - return true - case reflect.Uintptr: - return true - case reflect.Array: - return true - } - return false -} - -// Len returns the number of values in the slice. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Len() int { - return len(s.values) -} - -// Swap swaps the values at the passed indices. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Swap(i, j int) { - s.values[i], s.values[j] = s.values[j], s.values[i] - if s.strings != nil { - s.strings[i], s.strings[j] = s.strings[j], s.strings[i] - } -} - -// valueSortLess returns whether the first value should sort before the second -// value. It is used by valueSorter.Less as part of the sort.Interface -// implementation. -func valueSortLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Bool: - return !a.Bool() && b.Bool() - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return a.Int() < b.Int() - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return a.Uint() < b.Uint() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.String: - return a.String() < b.String() - case reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Array: - // Compare the contents of both arrays. - l := a.Len() - for i := 0; i < l; i++ { - av := a.Index(i) - bv := b.Index(i) - if av.Interface() == bv.Interface() { - continue - } - return valueSortLess(av, bv) - } - } - return a.String() < b.String() -} - -// Less returns whether the value at index i should sort before the -// value at index j. It is part of the sort.Interface implementation. -func (s *valuesSorter) Less(i, j int) bool { - if s.strings == nil { - return valueSortLess(s.values[i], s.values[j]) - } - return s.strings[i] < s.strings[j] -} - -// sortValues is a sort function that handles both native types and any type that -// can be converted to error or Stringer. Other inputs are sorted according to -// their Value.String() value to ensure display stability. -func sortValues(values []reflect.Value, cs *ConfigState) { - if len(values) == 0 { - return - } - sort.Sort(newValuesSorter(values, cs)) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go deleted file mode 100644 index 2e3d22f31..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/config.go +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "io" - "os" -) - -// ConfigState houses the configuration options used by spew to format and -// display values. There is a global instance, Config, that is used to control -// all top-level Formatter and Dump functionality. Each ConfigState instance -// provides methods equivalent to the top-level functions. -// -// The zero value for ConfigState provides no indentation. You would typically -// want to set it to a space or a tab. -// -// Alternatively, you can use NewDefaultConfig to get a ConfigState instance -// with default settings. See the documentation of NewDefaultConfig for default -// values. -type ConfigState struct { - // Indent specifies the string to use for each indentation level. The - // global config instance that all top-level functions use set this to a - // single space by default. If you would like more indentation, you might - // set this to a tab with "\t" or perhaps two spaces with " ". - Indent string - - // MaxDepth controls the maximum number of levels to descend into nested - // data structures. The default, 0, means there is no limit. - // - // NOTE: Circular data structures are properly detected, so it is not - // necessary to set this value unless you specifically want to limit deeply - // nested data structures. - MaxDepth int - - // DisableMethods specifies whether or not error and Stringer interfaces are - // invoked for types that implement them. - DisableMethods bool - - // DisablePointerMethods specifies whether or not to check for and invoke - // error and Stringer interfaces on types which only accept a pointer - // receiver when the current type is not a pointer. - // - // NOTE: This might be an unsafe action since calling one of these methods - // with a pointer receiver could technically mutate the value, however, - // in practice, types which choose to satisify an error or Stringer - // interface with a pointer receiver should not be mutating their state - // inside these interface methods. As a result, this option relies on - // access to the unsafe package, so it will not have any effect when - // running in environments without access to the unsafe package such as - // Google App Engine or with the "safe" build tag specified. - DisablePointerMethods bool - - // DisablePointerAddresses specifies whether to disable the printing of - // pointer addresses. This is useful when diffing data structures in tests. - DisablePointerAddresses bool - - // DisableCapacities specifies whether to disable the printing of capacities - // for arrays, slices, maps and channels. This is useful when diffing - // data structures in tests. - DisableCapacities bool - - // ContinueOnMethod specifies whether or not recursion should continue once - // a custom error or Stringer interface is invoked. The default, false, - // means it will print the results of invoking the custom error or Stringer - // interface and return immediately instead of continuing to recurse into - // the internals of the data type. - // - // NOTE: This flag does not have any effect if method invocation is disabled - // via the DisableMethods or DisablePointerMethods options. - ContinueOnMethod bool - - // SortKeys specifies map keys should be sorted before being printed. Use - // this to have a more deterministic, diffable output. Note that only - // native types (bool, int, uint, floats, uintptr and string) and types - // that support the error or Stringer interfaces (if methods are - // enabled) are supported, with other types sorted according to the - // reflect.Value.String() output which guarantees display stability. - SortKeys bool - - // SpewKeys specifies that, as a last resort attempt, map keys should - // be spewed to strings and sorted by those strings. This is only - // considered if SortKeys is true. - SpewKeys bool -} - -// Config is the active configuration of the top-level functions. -// The configuration can be changed by modifying the contents of spew.Config. -var Config = ConfigState{Indent: " "} - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the formatted string as a value that satisfies error. See NewFormatter -// for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, c.convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, c.convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, c.convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a Formatter interface returned by c.NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, c.convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Print(a ...interface{}) (n int, err error) { - return fmt.Print(c.convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, c.convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Println(a ...interface{}) (n int, err error) { - return fmt.Println(c.convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprint(a ...interface{}) string { - return fmt.Sprint(c.convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, c.convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a Formatter interface returned by c.NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintln(a ...interface{}) string { - return fmt.Sprintln(c.convertArgs(a)...) -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -c.Printf, c.Println, or c.Printf. -*/ -func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(c, v) -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { - fdump(c, w, a...) -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by modifying the public members -of c. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func (c *ConfigState) Dump(a ...interface{}) { - fdump(c, os.Stdout, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func (c *ConfigState) Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(c, &buf, a...) - return buf.String() -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a spew Formatter interface using -// the ConfigState associated with s. -func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = newFormatter(c, arg) - } - return formatters -} - -// NewDefaultConfig returns a ConfigState with the following default settings. -// -// Indent: " " -// MaxDepth: 0 -// DisableMethods: false -// DisablePointerMethods: false -// ContinueOnMethod: false -// SortKeys: false -func NewDefaultConfig() *ConfigState { - return &ConfigState{Indent: " "} -} diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go deleted file mode 100644 index aacaac6f1..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/doc.go +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Package spew implements a deep pretty printer for Go data structures to aid in -debugging. - -A quick overview of the additional features spew provides over the built-in -printing facilities for Go data types are as follows: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output (only when using - Dump style) - -There are two different approaches spew allows for dumping Go data structures: - - * Dump style which prints with newlines, customizable indentation, - and additional debug information such as types and all pointer addresses - used to indirect to the final value - * A custom Formatter interface that integrates cleanly with the standard fmt - package and replaces %v, %+v, %#v, and %#+v to provide inline printing - similar to the default %v while providing the additional functionality - outlined above and passing unsupported format verbs such as %x and %q - along to fmt - -Quick Start - -This section demonstrates how to quickly get started with spew. See the -sections below for further details on formatting and configuration options. - -To dump a variable with full newlines, indentation, type, and pointer -information use Dump, Fdump, or Sdump: - spew.Dump(myVar1, myVar2, ...) - spew.Fdump(someWriter, myVar1, myVar2, ...) - str := spew.Sdump(myVar1, myVar2, ...) - -Alternatively, if you would prefer to use format strings with a compacted inline -printing style, use the convenience wrappers Printf, Fprintf, etc with -%v (most compact), %+v (adds pointer addresses), %#v (adds types), or -%#+v (adds types and pointer addresses): - spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - -Configuration Options - -Configuration of spew is handled by fields in the ConfigState type. For -convenience, all of the top-level functions use a global state available -via the spew.Config global. - -It is also possible to create a ConfigState instance that provides methods -equivalent to the top-level functions. This allows concurrent configuration -options. See the ConfigState documentation for more details. - -The following configuration options are available: - * Indent - String to use for each indentation level for Dump functions. - It is a single space by default. A popular alternative is "\t". - - * MaxDepth - Maximum number of levels to descend into nested data structures. - There is no limit by default. - - * DisableMethods - Disables invocation of error and Stringer interface methods. - Method invocation is enabled by default. - - * DisablePointerMethods - Disables invocation of error and Stringer interface methods on types - which only accept pointer receivers from non-pointer variables. - Pointer method invocation is enabled by default. - - * DisablePointerAddresses - DisablePointerAddresses specifies whether to disable the printing of - pointer addresses. This is useful when diffing data structures in tests. - - * DisableCapacities - DisableCapacities specifies whether to disable the printing of - capacities for arrays, slices, maps and channels. This is useful when - diffing data structures in tests. - - * ContinueOnMethod - Enables recursion into types after invoking error and Stringer interface - methods. Recursion after method invocation is disabled by default. - - * SortKeys - Specifies map keys should be sorted before being printed. Use - this to have a more deterministic, diffable output. Note that - only native types (bool, int, uint, floats, uintptr and string) - and types which implement error or Stringer interfaces are - supported with other types sorted according to the - reflect.Value.String() output which guarantees display - stability. Natural map order is used by default. - - * SpewKeys - Specifies that, as a last resort attempt, map keys should be - spewed to strings and sorted by those strings. This is only - considered if SortKeys is true. - -Dump Usage - -Simply call spew.Dump with a list of variables you want to dump: - - spew.Dump(myVar1, myVar2, ...) - -You may also call spew.Fdump if you would prefer to output to an arbitrary -io.Writer. For example, to dump to standard error: - - spew.Fdump(os.Stderr, myVar1, myVar2, ...) - -A third option is to call spew.Sdump to get the formatted output as a string: - - str := spew.Sdump(myVar1, myVar2, ...) - -Sample Dump Output - -See the Dump example for details on the setup of the types and variables being -shown here. - - (main.Foo) { - unexportedField: (*main.Bar)(0xf84002e210)({ - flag: (main.Flag) flagTwo, - data: (uintptr) - }), - ExportedField: (map[interface {}]interface {}) (len=1) { - (string) (len=3) "one": (bool) true - } - } - -Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C -command as shown. - ([]uint8) (len=32 cap=32) { - 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - 00000020 31 32 |12| - } - -Custom Formatter - -Spew provides a custom formatter that implements the fmt.Formatter interface -so that it integrates cleanly with standard fmt package printing functions. The -formatter is useful for inline printing of smaller data types similar to the -standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Custom Formatter Usage - -The simplest way to make use of the spew custom formatter is to call one of the -convenience functions such as spew.Printf, spew.Println, or spew.Printf. The -functions have syntax you are most likely already familiar with: - - spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - spew.Println(myVar, myVar2) - spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - -See the Index for the full list convenience functions. - -Sample Formatter Output - -Double pointer to a uint8: - %v: <**>5 - %+v: <**>(0xf8400420d0->0xf8400420c8)5 - %#v: (**uint8)5 - %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 - -Pointer to circular struct with a uint8 field and a pointer to itself: - %v: <*>{1 <*>} - %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} - %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} - %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} - -See the Printf example for details on the setup of variables being shown -here. - -Errors - -Since it is possible for custom Stringer/error interfaces to panic, spew -detects them and handles them internally by printing the panic information -inline with the output. Since spew is intended to provide deep pretty printing -capabilities on structures, it intentionally does not return any errors. -*/ -package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go deleted file mode 100644 index f78d89fc1..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dump.go +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "encoding/hex" - "fmt" - "io" - "os" - "reflect" - "regexp" - "strconv" - "strings" -) - -var ( - // uint8Type is a reflect.Type representing a uint8. It is used to - // convert cgo types to uint8 slices for hexdumping. - uint8Type = reflect.TypeOf(uint8(0)) - - // cCharRE is a regular expression that matches a cgo char. - // It is used to detect character arrays to hexdump them. - cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) - - // cUnsignedCharRE is a regular expression that matches a cgo unsigned - // char. It is used to detect unsigned character arrays to hexdump - // them. - cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) - - // cUint8tCharRE is a regular expression that matches a cgo uint8_t. - // It is used to detect uint8_t arrays to hexdump them. - cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) -) - -// dumpState contains information about the state of a dump operation. -type dumpState struct { - w io.Writer - depth int - pointers map[uintptr]int - ignoreNextType bool - ignoreNextIndent bool - cs *ConfigState -} - -// indent performs indentation according to the depth level and cs.Indent -// option. -func (d *dumpState) indent() { - if d.ignoreNextIndent { - d.ignoreNextIndent = false - return - } - d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) -} - -// unpackValue returns values inside of non-nil interfaces when possible. -// This is useful for data types like structs, arrays, slices, and maps which -// can contain varying types packed inside an interface. -func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { - if v.Kind() == reflect.Interface && !v.IsNil() { - v = v.Elem() - } - return v -} - -// dumpPtr handles formatting of pointers by indirecting them as necessary. -func (d *dumpState) dumpPtr(v reflect.Value) { - // Remove pointers at or below the current depth from map used to detect - // circular refs. - for k, depth := range d.pointers { - if depth >= d.depth { - delete(d.pointers, k) - } - } - - // Keep list of all dereferenced pointers to show later. - pointerChain := make([]uintptr, 0) - - // Figure out how many levels of indirection there are by dereferencing - // pointers and unpacking interfaces down the chain while detecting circular - // references. - nilFound := false - cycleFound := false - indirects := 0 - ve := v - for ve.Kind() == reflect.Ptr { - if ve.IsNil() { - nilFound = true - break - } - indirects++ - addr := ve.Pointer() - pointerChain = append(pointerChain, addr) - if pd, ok := d.pointers[addr]; ok && pd < d.depth { - cycleFound = true - indirects-- - break - } - d.pointers[addr] = d.depth - - ve = ve.Elem() - if ve.Kind() == reflect.Interface { - if ve.IsNil() { - nilFound = true - break - } - ve = ve.Elem() - } - } - - // Display type information. - d.w.Write(openParenBytes) - d.w.Write(bytes.Repeat(asteriskBytes, indirects)) - d.w.Write([]byte(ve.Type().String())) - d.w.Write(closeParenBytes) - - // Display pointer information. - if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { - d.w.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - d.w.Write(pointerChainBytes) - } - printHexPtr(d.w, addr) - } - d.w.Write(closeParenBytes) - } - - // Display dereferenced value. - d.w.Write(openParenBytes) - switch { - case nilFound: - d.w.Write(nilAngleBytes) - - case cycleFound: - d.w.Write(circularBytes) - - default: - d.ignoreNextType = true - d.dump(ve) - } - d.w.Write(closeParenBytes) -} - -// dumpSlice handles formatting of arrays and slices. Byte (uint8 under -// reflection) arrays and slices are dumped in hexdump -C fashion. -func (d *dumpState) dumpSlice(v reflect.Value) { - // Determine whether this type should be hex dumped or not. Also, - // for types which should be hexdumped, try to use the underlying data - // first, then fall back to trying to convert them to a uint8 slice. - var buf []uint8 - doConvert := false - doHexDump := false - numEntries := v.Len() - if numEntries > 0 { - vt := v.Index(0).Type() - vts := vt.String() - switch { - // C types that need to be converted. - case cCharRE.MatchString(vts): - fallthrough - case cUnsignedCharRE.MatchString(vts): - fallthrough - case cUint8tCharRE.MatchString(vts): - doConvert = true - - // Try to use existing uint8 slices and fall back to converting - // and copying if that fails. - case vt.Kind() == reflect.Uint8: - // We need an addressable interface to convert the type - // to a byte slice. However, the reflect package won't - // give us an interface on certain things like - // unexported struct fields in order to enforce - // visibility rules. We use unsafe, when available, to - // bypass these restrictions since this package does not - // mutate the values. - vs := v - if !vs.CanInterface() || !vs.CanAddr() { - vs = unsafeReflectValue(vs) - } - if !UnsafeDisabled { - vs = vs.Slice(0, numEntries) - - // Use the existing uint8 slice if it can be - // type asserted. - iface := vs.Interface() - if slice, ok := iface.([]uint8); ok { - buf = slice - doHexDump = true - break - } - } - - // The underlying data needs to be converted if it can't - // be type asserted to a uint8 slice. - doConvert = true - } - - // Copy and convert the underlying type if needed. - if doConvert && vt.ConvertibleTo(uint8Type) { - // Convert and copy each element into a uint8 byte - // slice. - buf = make([]uint8, numEntries) - for i := 0; i < numEntries; i++ { - vv := v.Index(i) - buf[i] = uint8(vv.Convert(uint8Type).Uint()) - } - doHexDump = true - } - } - - // Hexdump the entire slice as needed. - if doHexDump { - indent := strings.Repeat(d.cs.Indent, d.depth) - str := indent + hex.Dump(buf) - str = strings.Replace(str, "\n", "\n"+indent, -1) - str = strings.TrimRight(str, d.cs.Indent) - d.w.Write([]byte(str)) - return - } - - // Recursively call dump for each item. - for i := 0; i < numEntries; i++ { - d.dump(d.unpackValue(v.Index(i))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } -} - -// dump is the main workhorse for dumping a value. It uses the passed reflect -// value to figure out what kind of object we are dealing with and formats it -// appropriately. It is a recursive function, however circular data structures -// are detected and handled properly. -func (d *dumpState) dump(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - d.w.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - d.indent() - d.dumpPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !d.ignoreNextType { - d.indent() - d.w.Write(openParenBytes) - d.w.Write([]byte(v.Type().String())) - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - d.ignoreNextType = false - - // Display length and capacity if the built-in len and cap functions - // work with the value's kind and the len/cap itself is non-zero. - valueLen, valueCap := 0, 0 - switch v.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - valueLen, valueCap = v.Len(), v.Cap() - case reflect.Map, reflect.String: - valueLen = v.Len() - } - if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { - d.w.Write(openParenBytes) - if valueLen != 0 { - d.w.Write(lenEqualsBytes) - printInt(d.w, int64(valueLen), 10) - } - if !d.cs.DisableCapacities && valueCap != 0 { - if valueLen != 0 { - d.w.Write(spaceBytes) - } - d.w.Write(capEqualsBytes) - printInt(d.w, int64(valueCap), 10) - } - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - - // Call Stringer/error interfaces if they exist and the handle methods flag - // is enabled - if !d.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(d.cs, d.w, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(d.w, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(d.w, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(d.w, v.Uint(), 10) - - case reflect.Float32: - printFloat(d.w, v.Float(), 32) - - case reflect.Float64: - printFloat(d.w, v.Float(), 64) - - case reflect.Complex64: - printComplex(d.w, v.Complex(), 32) - - case reflect.Complex128: - printComplex(d.w, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - d.dumpSlice(v) - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.String: - d.w.Write([]byte(strconv.Quote(v.String()))) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - d.w.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - numEntries := v.Len() - keys := v.MapKeys() - if d.cs.SortKeys { - sortValues(keys, d.cs) - } - for i, key := range keys { - d.dump(d.unpackValue(key)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.MapIndex(key))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Struct: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - vt := v.Type() - numFields := v.NumField() - for i := 0; i < numFields; i++ { - d.indent() - vtf := vt.Field(i) - d.w.Write([]byte(vtf.Name)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.Field(i))) - if i < (numFields - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(d.w, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(d.w, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it in case any new - // types are added. - default: - if v.CanInterface() { - fmt.Fprintf(d.w, "%v", v.Interface()) - } else { - fmt.Fprintf(d.w, "%v", v.String()) - } - } -} - -// fdump is a helper function to consolidate the logic from the various public -// methods which take varying writers and config states. -func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { - for _, arg := range a { - if arg == nil { - w.Write(interfaceBytes) - w.Write(spaceBytes) - w.Write(nilAngleBytes) - w.Write(newlineBytes) - continue - } - - d := dumpState{w: w, cs: cs} - d.pointers = make(map[uintptr]int) - d.dump(reflect.ValueOf(arg)) - d.w.Write(newlineBytes) - } -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func Fdump(w io.Writer, a ...interface{}) { - fdump(&Config, w, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(&Config, &buf, a...) - return buf.String() -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by an exported package global, -spew.Config. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func Dump(a ...interface{}) { - fdump(&Config, os.Stdout, a...) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go deleted file mode 100644 index b04edb7d7..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/format.go +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "reflect" - "strconv" - "strings" -) - -// supportedFlags is a list of all the character flags supported by fmt package. -const supportedFlags = "0-+# " - -// formatState implements the fmt.Formatter interface and contains information -// about the state of a formatting operation. The NewFormatter function can -// be used to get a new Formatter which can be used directly as arguments -// in standard fmt package printing calls. -type formatState struct { - value interface{} - fs fmt.State - depth int - pointers map[uintptr]int - ignoreNextType bool - cs *ConfigState -} - -// buildDefaultFormat recreates the original format string without precision -// and width information to pass in to fmt.Sprintf in the case of an -// unrecognized type. Unless new types are added to the language, this -// function won't ever be called. -func (f *formatState) buildDefaultFormat() (format string) { - buf := bytes.NewBuffer(percentBytes) - - for _, flag := range supportedFlags { - if f.fs.Flag(int(flag)) { - buf.WriteRune(flag) - } - } - - buf.WriteRune('v') - - format = buf.String() - return format -} - -// constructOrigFormat recreates the original format string including precision -// and width information to pass along to the standard fmt package. This allows -// automatic deferral of all format strings this package doesn't support. -func (f *formatState) constructOrigFormat(verb rune) (format string) { - buf := bytes.NewBuffer(percentBytes) - - for _, flag := range supportedFlags { - if f.fs.Flag(int(flag)) { - buf.WriteRune(flag) - } - } - - if width, ok := f.fs.Width(); ok { - buf.WriteString(strconv.Itoa(width)) - } - - if precision, ok := f.fs.Precision(); ok { - buf.Write(precisionBytes) - buf.WriteString(strconv.Itoa(precision)) - } - - buf.WriteRune(verb) - - format = buf.String() - return format -} - -// unpackValue returns values inside of non-nil interfaces when possible and -// ensures that types for values which have been unpacked from an interface -// are displayed when the show types flag is also set. -// This is useful for data types like structs, arrays, slices, and maps which -// can contain varying types packed inside an interface. -func (f *formatState) unpackValue(v reflect.Value) reflect.Value { - if v.Kind() == reflect.Interface { - f.ignoreNextType = false - if !v.IsNil() { - v = v.Elem() - } - } - return v -} - -// formatPtr handles formatting of pointers by indirecting them as necessary. -func (f *formatState) formatPtr(v reflect.Value) { - // Display nil if top level pointer is nil. - showTypes := f.fs.Flag('#') - if v.IsNil() && (!showTypes || f.ignoreNextType) { - f.fs.Write(nilAngleBytes) - return - } - - // Remove pointers at or below the current depth from map used to detect - // circular refs. - for k, depth := range f.pointers { - if depth >= f.depth { - delete(f.pointers, k) - } - } - - // Keep list of all dereferenced pointers to possibly show later. - pointerChain := make([]uintptr, 0) - - // Figure out how many levels of indirection there are by derferencing - // pointers and unpacking interfaces down the chain while detecting circular - // references. - nilFound := false - cycleFound := false - indirects := 0 - ve := v - for ve.Kind() == reflect.Ptr { - if ve.IsNil() { - nilFound = true - break - } - indirects++ - addr := ve.Pointer() - pointerChain = append(pointerChain, addr) - if pd, ok := f.pointers[addr]; ok && pd < f.depth { - cycleFound = true - indirects-- - break - } - f.pointers[addr] = f.depth - - ve = ve.Elem() - if ve.Kind() == reflect.Interface { - if ve.IsNil() { - nilFound = true - break - } - ve = ve.Elem() - } - } - - // Display type or indirection level depending on flags. - if showTypes && !f.ignoreNextType { - f.fs.Write(openParenBytes) - f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) - f.fs.Write([]byte(ve.Type().String())) - f.fs.Write(closeParenBytes) - } else { - if nilFound || cycleFound { - indirects += strings.Count(ve.Type().String(), "*") - } - f.fs.Write(openAngleBytes) - f.fs.Write([]byte(strings.Repeat("*", indirects))) - f.fs.Write(closeAngleBytes) - } - - // Display pointer information depending on flags. - if f.fs.Flag('+') && (len(pointerChain) > 0) { - f.fs.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - f.fs.Write(pointerChainBytes) - } - printHexPtr(f.fs, addr) - } - f.fs.Write(closeParenBytes) - } - - // Display dereferenced value. - switch { - case nilFound: - f.fs.Write(nilAngleBytes) - - case cycleFound: - f.fs.Write(circularShortBytes) - - default: - f.ignoreNextType = true - f.format(ve) - } -} - -// format is the main workhorse for providing the Formatter interface. It -// uses the passed reflect value to figure out what kind of object we are -// dealing with and formats it appropriately. It is a recursive function, -// however circular data structures are detected and handled properly. -func (f *formatState) format(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - f.fs.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - f.formatPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !f.ignoreNextType && f.fs.Flag('#') { - f.fs.Write(openParenBytes) - f.fs.Write([]byte(v.Type().String())) - f.fs.Write(closeParenBytes) - } - f.ignoreNextType = false - - // Call Stringer/error interfaces if they exist and the handle methods - // flag is enabled. - if !f.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(f.cs, f.fs, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(f.fs, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(f.fs, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(f.fs, v.Uint(), 10) - - case reflect.Float32: - printFloat(f.fs, v.Float(), 32) - - case reflect.Float64: - printFloat(f.fs, v.Float(), 64) - - case reflect.Complex64: - printComplex(f.fs, v.Complex(), 32) - - case reflect.Complex128: - printComplex(f.fs, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - f.fs.Write(openBracketBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - numEntries := v.Len() - for i := 0; i < numEntries; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(v.Index(i))) - } - } - f.depth-- - f.fs.Write(closeBracketBytes) - - case reflect.String: - f.fs.Write([]byte(v.String())) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - f.fs.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - - f.fs.Write(openMapBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - keys := v.MapKeys() - if f.cs.SortKeys { - sortValues(keys, f.cs) - } - for i, key := range keys { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(key)) - f.fs.Write(colonBytes) - f.ignoreNextType = true - f.format(f.unpackValue(v.MapIndex(key))) - } - } - f.depth-- - f.fs.Write(closeMapBytes) - - case reflect.Struct: - numFields := v.NumField() - f.fs.Write(openBraceBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - vt := v.Type() - for i := 0; i < numFields; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - vtf := vt.Field(i) - if f.fs.Flag('+') || f.fs.Flag('#') { - f.fs.Write([]byte(vtf.Name)) - f.fs.Write(colonBytes) - } - f.format(f.unpackValue(v.Field(i))) - } - } - f.depth-- - f.fs.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(f.fs, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(f.fs, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it if any get added. - default: - format := f.buildDefaultFormat() - if v.CanInterface() { - fmt.Fprintf(f.fs, format, v.Interface()) - } else { - fmt.Fprintf(f.fs, format, v.String()) - } - } -} - -// Format satisfies the fmt.Formatter interface. See NewFormatter for usage -// details. -func (f *formatState) Format(fs fmt.State, verb rune) { - f.fs = fs - - // Use standard formatting for verbs that are not v. - if verb != 'v' { - format := f.constructOrigFormat(verb) - fmt.Fprintf(fs, format, f.value) - return - } - - if f.value == nil { - if fs.Flag('#') { - fs.Write(interfaceBytes) - } - fs.Write(nilAngleBytes) - return - } - - f.format(reflect.ValueOf(f.value)) -} - -// newFormatter is a helper function to consolidate the logic from the various -// public methods which take varying config states. -func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { - fs := &formatState{value: v, cs: cs} - fs.pointers = make(map[uintptr]int) - return fs -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -Printf, Println, or Fprintf. -*/ -func NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(&Config, v) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go deleted file mode 100644 index 32c0e3388..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/spew.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "fmt" - "io" -) - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the formatted string as a value that satisfies error. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a default Formatter interface returned by NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) -func Print(a ...interface{}) (n int, err error) { - return fmt.Print(convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) -func Println(a ...interface{}) (n int, err error) { - return fmt.Println(convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprint(a ...interface{}) string { - return fmt.Sprint(convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintln(a ...interface{}) string { - return fmt.Sprintln(convertArgs(a)...) -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a default spew Formatter interface. -func convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = NewFormatter(arg) - } - return formatters -} diff --git a/vendor/github.com/getkin/kin-openapi/LICENSE b/vendor/github.com/getkin/kin-openapi/LICENSE deleted file mode 100644 index 992b9831e..000000000 --- a/vendor/github.com/getkin/kin-openapi/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017-2018 the project authors. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/callback.go b/vendor/github.com/getkin/kin-openapi/openapi3/callback.go deleted file mode 100644 index 34a6bea35..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/callback.go +++ /dev/null @@ -1,54 +0,0 @@ -package openapi3 - -import ( - "context" - "sort" -) - -// Callback is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callback-object -type Callback struct { - Extensions map[string]any `json:"-" yaml:"-"` - - m map[string]*PathItem -} - -// NewCallback builds a Callback object with path items in insertion order. -func NewCallback(opts ...NewCallbackOption) *Callback { - Callback := NewCallbackWithCapacity(len(opts)) - for _, opt := range opts { - opt(Callback) - } - return Callback -} - -// NewCallbackOption describes options to NewCallback func -type NewCallbackOption func(*Callback) - -// WithCallback adds Callback as an option to NewCallback -func WithCallback(cb string, pathItem *PathItem) NewCallbackOption { - return func(callback *Callback) { - if p := pathItem; p != nil && cb != "" { - callback.Set(cb, p) - } - } -} - -// Validate returns an error if Callback does not comply with the OpenAPI spec. -func (callback *Callback) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - keys := make([]string, 0, callback.Len()) - for key := range callback.Map() { - keys = append(keys, key) - } - sort.Strings(keys) - for _, key := range keys { - v := callback.Value(key) - if err := v.Validate(ctx); err != nil { - return err - } - } - - return validateExtensions(ctx, callback.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/components.go b/vendor/github.com/getkin/kin-openapi/openapi3/components.go deleted file mode 100644 index 98c4b96c1..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/components.go +++ /dev/null @@ -1,370 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "fmt" - "sort" - - "github.com/go-openapi/jsonpointer" -) - -type ( - Callbacks map[string]*CallbackRef - Examples map[string]*ExampleRef - Headers map[string]*HeaderRef - Links map[string]*LinkRef - ParametersMap map[string]*ParameterRef - RequestBodies map[string]*RequestBodyRef - ResponseBodies map[string]*ResponseRef - Schemas map[string]*SchemaRef - SecuritySchemes map[string]*SecuritySchemeRef -) - -// Components is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#components-object -type Components struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Schemas Schemas `json:"schemas,omitempty" yaml:"schemas,omitempty"` - Parameters ParametersMap `json:"parameters,omitempty" yaml:"parameters,omitempty"` - Headers Headers `json:"headers,omitempty" yaml:"headers,omitempty"` - RequestBodies RequestBodies `json:"requestBodies,omitempty" yaml:"requestBodies,omitempty"` - Responses ResponseBodies `json:"responses,omitempty" yaml:"responses,omitempty"` - SecuritySchemes SecuritySchemes `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty"` - Examples Examples `json:"examples,omitempty" yaml:"examples,omitempty"` - Links Links `json:"links,omitempty" yaml:"links,omitempty"` - Callbacks Callbacks `json:"callbacks,omitempty" yaml:"callbacks,omitempty"` -} - -func NewComponents() Components { - return Components{} -} - -// MarshalJSON returns the JSON encoding of Components. -func (components Components) MarshalJSON() ([]byte, error) { - x, err := components.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Components. -func (components Components) MarshalYAML() (any, error) { - m := make(map[string]any, 9+len(components.Extensions)) - for k, v := range components.Extensions { - m[k] = v - } - if x := components.Schemas; len(x) != 0 { - m["schemas"] = x - } - if x := components.Parameters; len(x) != 0 { - m["parameters"] = x - } - if x := components.Headers; len(x) != 0 { - m["headers"] = x - } - if x := components.RequestBodies; len(x) != 0 { - m["requestBodies"] = x - } - if x := components.Responses; len(x) != 0 { - m["responses"] = x - } - if x := components.SecuritySchemes; len(x) != 0 { - m["securitySchemes"] = x - } - if x := components.Examples; len(x) != 0 { - m["examples"] = x - } - if x := components.Links; len(x) != 0 { - m["links"] = x - } - if x := components.Callbacks; len(x) != 0 { - m["callbacks"] = x - } - return m, nil -} - -// UnmarshalJSON sets Components to a copy of data. -func (components *Components) UnmarshalJSON(data []byte) error { - type ComponentsBis Components - var x ComponentsBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "schemas") - delete(x.Extensions, "parameters") - delete(x.Extensions, "headers") - delete(x.Extensions, "requestBodies") - delete(x.Extensions, "responses") - delete(x.Extensions, "securitySchemes") - delete(x.Extensions, "examples") - delete(x.Extensions, "links") - delete(x.Extensions, "callbacks") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *components = Components(x) - return nil -} - -// Validate returns an error if Components does not comply with the OpenAPI spec. -func (components *Components) Validate(ctx context.Context, opts ...ValidationOption) (err error) { - ctx = WithValidationOptions(ctx, opts...) - - schemas := make([]string, 0, len(components.Schemas)) - for name := range components.Schemas { - schemas = append(schemas, name) - } - sort.Strings(schemas) - for _, k := range schemas { - v := components.Schemas[k] - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("schema %q: %w", k, err) - } - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("schema %q: %w", k, err) - } - } - - parameters := make([]string, 0, len(components.Parameters)) - for name := range components.Parameters { - parameters = append(parameters, name) - } - sort.Strings(parameters) - for _, k := range parameters { - v := components.Parameters[k] - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("parameter %q: %w", k, err) - } - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("parameter %q: %w", k, err) - } - } - - requestBodies := make([]string, 0, len(components.RequestBodies)) - for name := range components.RequestBodies { - requestBodies = append(requestBodies, name) - } - sort.Strings(requestBodies) - for _, k := range requestBodies { - v := components.RequestBodies[k] - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("request body %q: %w", k, err) - } - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("request body %q: %w", k, err) - } - } - - responses := make([]string, 0, len(components.Responses)) - for name := range components.Responses { - responses = append(responses, name) - } - sort.Strings(responses) - for _, k := range responses { - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("response %q: %w", k, err) - } - v := components.Responses[k] - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("response %q: %w", k, err) - } - } - - headers := make([]string, 0, len(components.Headers)) - for name := range components.Headers { - headers = append(headers, name) - } - sort.Strings(headers) - for _, k := range headers { - v := components.Headers[k] - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("header %q: %w", k, err) - } - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("header %q: %w", k, err) - } - } - - securitySchemes := make([]string, 0, len(components.SecuritySchemes)) - for name := range components.SecuritySchemes { - securitySchemes = append(securitySchemes, name) - } - sort.Strings(securitySchemes) - for _, k := range securitySchemes { - v := components.SecuritySchemes[k] - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("security scheme %q: %w", k, err) - } - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("security scheme %q: %w", k, err) - } - } - - examples := make([]string, 0, len(components.Examples)) - for name := range components.Examples { - examples = append(examples, name) - } - sort.Strings(examples) - for _, k := range examples { - v := components.Examples[k] - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("example %q: %w", k, err) - } - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("example %q: %w", k, err) - } - } - - links := make([]string, 0, len(components.Links)) - for name := range components.Links { - links = append(links, name) - } - sort.Strings(links) - for _, k := range links { - v := components.Links[k] - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("link %q: %w", k, err) - } - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("link %q: %w", k, err) - } - } - - callbacks := make([]string, 0, len(components.Callbacks)) - for name := range components.Callbacks { - callbacks = append(callbacks, name) - } - sort.Strings(callbacks) - for _, k := range callbacks { - v := components.Callbacks[k] - if err = ValidateIdentifier(k); err != nil { - return fmt.Errorf("callback %q: %w", k, err) - } - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("callback %q: %w", k, err) - } - } - - return validateExtensions(ctx, components.Extensions) -} - -var _ jsonpointer.JSONPointable = (*Schemas)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m Schemas) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no schema %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} - -var _ jsonpointer.JSONPointable = (*ParametersMap)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m ParametersMap) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no parameter %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} - -var _ jsonpointer.JSONPointable = (*Headers)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m Headers) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no header %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} - -var _ jsonpointer.JSONPointable = (*RequestBodyRef)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m RequestBodies) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no request body %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} - -var _ jsonpointer.JSONPointable = (*ResponseRef)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m ResponseBodies) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no response body %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} - -var _ jsonpointer.JSONPointable = (*SecuritySchemes)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m SecuritySchemes) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no security scheme body %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} - -var _ jsonpointer.JSONPointable = (*Examples)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m Examples) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no example body %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} - -var _ jsonpointer.JSONPointable = (*Links)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m Links) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no link body %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} - -var _ jsonpointer.JSONPointable = (*Callbacks)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (m Callbacks) JSONLookup(token string) (any, error) { - if v, ok := m[token]; !ok || v == nil { - return nil, fmt.Errorf("no callback body %q", token) - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - return v.Value, nil - } -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/contact.go b/vendor/github.com/getkin/kin-openapi/openapi3/contact.go deleted file mode 100644 index 6c76a6fb6..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/contact.go +++ /dev/null @@ -1,68 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" -) - -// Contact is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#contact-object -type Contact struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Name string `json:"name,omitempty" yaml:"name,omitempty"` - URL string `json:"url,omitempty" yaml:"url,omitempty"` - Email string `json:"email,omitempty" yaml:"email,omitempty"` -} - -// MarshalJSON returns the JSON encoding of Contact. -func (contact Contact) MarshalJSON() ([]byte, error) { - x, err := contact.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Contact. -func (contact Contact) MarshalYAML() (any, error) { - m := make(map[string]any, 3+len(contact.Extensions)) - for k, v := range contact.Extensions { - m[k] = v - } - if x := contact.Name; x != "" { - m["name"] = x - } - if x := contact.URL; x != "" { - m["url"] = x - } - if x := contact.Email; x != "" { - m["email"] = x - } - return m, nil -} - -// UnmarshalJSON sets Contact to a copy of data. -func (contact *Contact) UnmarshalJSON(data []byte) error { - type ContactBis Contact - var x ContactBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "name") - delete(x.Extensions, "url") - delete(x.Extensions, "email") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *contact = Contact(x) - return nil -} - -// Validate returns an error if Contact does not comply with the OpenAPI spec. -func (contact *Contact) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - return validateExtensions(ctx, contact.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/content.go b/vendor/github.com/getkin/kin-openapi/openapi3/content.go deleted file mode 100644 index 81b070eec..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/content.go +++ /dev/null @@ -1,124 +0,0 @@ -package openapi3 - -import ( - "context" - "sort" - "strings" -) - -// Content is specified by OpenAPI/Swagger 3.0 standard. -type Content map[string]*MediaType - -func NewContent() Content { - return make(map[string]*MediaType) -} - -func NewContentWithSchema(schema *Schema, consumes []string) Content { - if len(consumes) == 0 { - return Content{ - "*/*": NewMediaType().WithSchema(schema), - } - } - content := make(map[string]*MediaType, len(consumes)) - for _, mediaType := range consumes { - content[mediaType] = NewMediaType().WithSchema(schema) - } - return content -} - -func NewContentWithSchemaRef(schema *SchemaRef, consumes []string) Content { - if len(consumes) == 0 { - return Content{ - "*/*": NewMediaType().WithSchemaRef(schema), - } - } - content := make(map[string]*MediaType, len(consumes)) - for _, mediaType := range consumes { - content[mediaType] = NewMediaType().WithSchemaRef(schema) - } - return content -} - -func NewContentWithJSONSchema(schema *Schema) Content { - return Content{ - "application/json": NewMediaType().WithSchema(schema), - } -} -func NewContentWithJSONSchemaRef(schema *SchemaRef) Content { - return Content{ - "application/json": NewMediaType().WithSchemaRef(schema), - } -} - -func NewContentWithFormDataSchema(schema *Schema) Content { - return Content{ - "multipart/form-data": NewMediaType().WithSchema(schema), - } -} - -func NewContentWithFormDataSchemaRef(schema *SchemaRef) Content { - return Content{ - "multipart/form-data": NewMediaType().WithSchemaRef(schema), - } -} - -func (content Content) Get(mime string) *MediaType { - // If the mime is empty then short-circuit to the wildcard. - // We do this here so that we catch only the specific case of - // and empty mime rather than a present, but invalid, mime type. - if mime == "" { - return content["*/*"] - } - // Start by making the most specific match possible - // by using the mime type in full. - if v := content[mime]; v != nil { - return v - } - // If an exact match is not found then we strip all - // metadata from the mime type and only use the x/y - // portion. - i := strings.IndexByte(mime, ';') - if i < 0 { - // If there is no metadata then preserve the full mime type - // string for later wildcard searches. - i = len(mime) - } - mime = mime[:i] - if v := content[mime]; v != nil { - return v - } - // If the x/y pattern has no specific match then we - // try the x/* pattern. - i = strings.IndexByte(mime, '/') - if i < 0 { - // In the case that the given mime type is not valid because it is - // missing the subtype we return nil so that this does not accidentally - // resolve with the wildcard. - return nil - } - mime = mime[:i] + "/*" - if v := content[mime]; v != nil { - return v - } - // Finally, the most generic match of */* is returned - // as a catch-all. - return content["*/*"] -} - -// Validate returns an error if Content does not comply with the OpenAPI spec. -func (content Content) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - keys := make([]string, 0, len(content)) - for key := range content { - keys = append(keys, key) - } - sort.Strings(keys) - for _, k := range keys { - v := content[k] - if err := v.Validate(ctx); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/discriminator.go b/vendor/github.com/getkin/kin-openapi/openapi3/discriminator.go deleted file mode 100644 index e8193bd90..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/discriminator.go +++ /dev/null @@ -1,61 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" -) - -// Discriminator is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#discriminator-object -type Discriminator struct { - Extensions map[string]any `json:"-" yaml:"-"` - - PropertyName string `json:"propertyName" yaml:"propertyName"` // required - Mapping map[string]string `json:"mapping,omitempty" yaml:"mapping,omitempty"` -} - -// MarshalJSON returns the JSON encoding of Discriminator. -func (discriminator Discriminator) MarshalJSON() ([]byte, error) { - x, err := discriminator.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Discriminator. -func (discriminator Discriminator) MarshalYAML() (any, error) { - m := make(map[string]any, 2+len(discriminator.Extensions)) - for k, v := range discriminator.Extensions { - m[k] = v - } - m["propertyName"] = discriminator.PropertyName - if x := discriminator.Mapping; len(x) != 0 { - m["mapping"] = x - } - return m, nil -} - -// UnmarshalJSON sets Discriminator to a copy of data. -func (discriminator *Discriminator) UnmarshalJSON(data []byte) error { - type DiscriminatorBis Discriminator - var x DiscriminatorBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "propertyName") - delete(x.Extensions, "mapping") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *discriminator = Discriminator(x) - return nil -} - -// Validate returns an error if Discriminator does not comply with the OpenAPI spec. -func (discriminator *Discriminator) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - return validateExtensions(ctx, discriminator.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/doc.go b/vendor/github.com/getkin/kin-openapi/openapi3/doc.go deleted file mode 100644 index 41c9965c6..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package openapi3 parses and writes OpenAPI 3 specification documents. -// -// See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md -package openapi3 diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/encoding.go b/vendor/github.com/getkin/kin-openapi/openapi3/encoding.go deleted file mode 100644 index 1bcdaea5e..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/encoding.go +++ /dev/null @@ -1,148 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "fmt" - "sort" -) - -// Encoding is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#encoding-object -type Encoding struct { - Extensions map[string]any `json:"-" yaml:"-"` - - ContentType string `json:"contentType,omitempty" yaml:"contentType,omitempty"` - Headers Headers `json:"headers,omitempty" yaml:"headers,omitempty"` - Style string `json:"style,omitempty" yaml:"style,omitempty"` - Explode *bool `json:"explode,omitempty" yaml:"explode,omitempty"` - AllowReserved bool `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"` -} - -func NewEncoding() *Encoding { - return &Encoding{} -} - -func (encoding *Encoding) WithHeader(name string, header *Header) *Encoding { - return encoding.WithHeaderRef(name, &HeaderRef{ - Value: header, - }) -} - -func (encoding *Encoding) WithHeaderRef(name string, ref *HeaderRef) *Encoding { - headers := encoding.Headers - if headers == nil { - headers = make(map[string]*HeaderRef) - encoding.Headers = headers - } - headers[name] = ref - return encoding -} - -// MarshalJSON returns the JSON encoding of Encoding. -func (encoding Encoding) MarshalJSON() ([]byte, error) { - x, err := encoding.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Encoding. -func (encoding Encoding) MarshalYAML() (any, error) { - m := make(map[string]any, 5+len(encoding.Extensions)) - for k, v := range encoding.Extensions { - m[k] = v - } - if x := encoding.ContentType; x != "" { - m["contentType"] = x - } - if x := encoding.Headers; len(x) != 0 { - m["headers"] = x - } - if x := encoding.Style; x != "" { - m["style"] = x - } - if x := encoding.Explode; x != nil { - m["explode"] = x - } - if x := encoding.AllowReserved; x { - m["allowReserved"] = x - } - return m, nil -} - -// UnmarshalJSON sets Encoding to a copy of data. -func (encoding *Encoding) UnmarshalJSON(data []byte) error { - type EncodingBis Encoding - var x EncodingBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "contentType") - delete(x.Extensions, "headers") - delete(x.Extensions, "style") - delete(x.Extensions, "explode") - delete(x.Extensions, "allowReserved") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *encoding = Encoding(x) - return nil -} - -// SerializationMethod returns a serialization method of request body. -// When serialization method is not defined the method returns the default serialization method. -func (encoding *Encoding) SerializationMethod() *SerializationMethod { - sm := &SerializationMethod{Style: SerializationForm, Explode: true} - if encoding != nil { - if encoding.Style != "" { - sm.Style = encoding.Style - } - if encoding.Explode != nil { - sm.Explode = *encoding.Explode - } - } - return sm -} - -// Validate returns an error if Encoding does not comply with the OpenAPI spec. -func (encoding *Encoding) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if encoding == nil { - return nil - } - - headers := make([]string, 0, len(encoding.Headers)) - for k := range encoding.Headers { - headers = append(headers, k) - } - sort.Strings(headers) - for _, k := range headers { - v := encoding.Headers[k] - if err := ValidateIdentifier(k); err != nil { - return nil - } - if err := v.Validate(ctx); err != nil { - return nil - } - } - - // Validate a media types's serialization method. - sm := encoding.SerializationMethod() - switch { - case sm.Style == SerializationForm && sm.Explode, - sm.Style == SerializationForm && !sm.Explode, - sm.Style == SerializationSpaceDelimited && sm.Explode, - sm.Style == SerializationSpaceDelimited && !sm.Explode, - sm.Style == SerializationPipeDelimited && sm.Explode, - sm.Style == SerializationPipeDelimited && !sm.Explode, - sm.Style == SerializationDeepObject && sm.Explode: - default: - return fmt.Errorf("serialization method with style=%q and explode=%v is not supported by media type", sm.Style, sm.Explode) - } - - return validateExtensions(ctx, encoding.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/errors.go b/vendor/github.com/getkin/kin-openapi/openapi3/errors.go deleted file mode 100644 index 010dc889a..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/errors.go +++ /dev/null @@ -1,59 +0,0 @@ -package openapi3 - -import ( - "bytes" - "errors" -) - -// MultiError is a collection of errors, intended for when -// multiple issues need to be reported upstream -type MultiError []error - -func (me MultiError) Error() string { - return spliceErr(" | ", me) -} - -func spliceErr(sep string, errs []error) string { - buff := &bytes.Buffer{} - for i, e := range errs { - buff.WriteString(e.Error()) - if i != len(errs)-1 { - buff.WriteString(sep) - } - } - return buff.String() -} - -// Is allows you to determine if a generic error is in fact a MultiError using `errors.Is()` -// It will also return true if any of the contained errors match target -func (me MultiError) Is(target error) bool { - if _, ok := target.(MultiError); ok { - return true - } - for _, e := range me { - if errors.Is(e, target) { - return true - } - } - return false -} - -// As allows you to use `errors.As()` to set target to the first error within the multi error that matches the target type -func (me MultiError) As(target any) bool { - for _, e := range me { - if errors.As(e, target) { - return true - } - } - return false -} - -type multiErrorForOneOf MultiError - -func (meo multiErrorForOneOf) Error() string { - return spliceErr(" Or ", meo) -} - -func (meo multiErrorForOneOf) Unwrap() error { - return MultiError(meo) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/example.go b/vendor/github.com/getkin/kin-openapi/openapi3/example.go deleted file mode 100644 index f9a7a6b07..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/example.go +++ /dev/null @@ -1,85 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" -) - -// Example is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#example-object -type Example struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Value any `json:"value,omitempty" yaml:"value,omitempty"` - ExternalValue string `json:"externalValue,omitempty" yaml:"externalValue,omitempty"` -} - -func NewExample(value any) *Example { - return &Example{Value: value} -} - -// MarshalJSON returns the JSON encoding of Example. -func (example Example) MarshalJSON() ([]byte, error) { - x, err := example.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Example. -func (example Example) MarshalYAML() (any, error) { - m := make(map[string]any, 4+len(example.Extensions)) - for k, v := range example.Extensions { - m[k] = v - } - if x := example.Summary; x != "" { - m["summary"] = x - } - if x := example.Description; x != "" { - m["description"] = x - } - if x := example.Value; x != nil { - m["value"] = x - } - if x := example.ExternalValue; x != "" { - m["externalValue"] = x - } - return m, nil -} - -// UnmarshalJSON sets Example to a copy of data. -func (example *Example) UnmarshalJSON(data []byte) error { - type ExampleBis Example - var x ExampleBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "summary") - delete(x.Extensions, "description") - delete(x.Extensions, "value") - delete(x.Extensions, "externalValue") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *example = Example(x) - return nil -} - -// Validate returns an error if Example does not comply with the OpenAPI spec. -func (example *Example) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if example.Value != nil && example.ExternalValue != "" { - return errors.New("value and externalValue are mutually exclusive") - } - if example.Value == nil && example.ExternalValue == "" { - return errors.New("no value or externalValue field") - } - - return validateExtensions(ctx, example.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/example_validation.go b/vendor/github.com/getkin/kin-openapi/openapi3/example_validation.go deleted file mode 100644 index 0d105c92d..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/example_validation.go +++ /dev/null @@ -1,16 +0,0 @@ -package openapi3 - -import "context" - -func validateExampleValue(ctx context.Context, input any, schema *Schema) error { - opts := make([]SchemaValidationOption, 0, 2) - - if vo := getValidationOptions(ctx); vo.examplesValidationAsReq { - opts = append(opts, VisitAsRequest()) - } else if vo.examplesValidationAsRes { - opts = append(opts, VisitAsResponse()) - } - opts = append(opts, MultiErrors()) - - return schema.VisitJSON(input, opts...) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/extension.go b/vendor/github.com/getkin/kin-openapi/openapi3/extension.go deleted file mode 100644 index ca86078f2..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/extension.go +++ /dev/null @@ -1,32 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - "sort" - "strings" -) - -func validateExtensions(ctx context.Context, extensions map[string]any) error { // FIXME: newtype + Validate(...) - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - - var unknowns []string - for k := range extensions { - if strings.HasPrefix(k, "x-") { - continue - } - if allowed != nil { - if _, ok := allowed[k]; ok { - continue - } - } - unknowns = append(unknowns, k) - } - - if len(unknowns) != 0 { - sort.Strings(unknowns) - return fmt.Errorf("extra sibling fields: %+v", unknowns) - } - - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/external_docs.go b/vendor/github.com/getkin/kin-openapi/openapi3/external_docs.go deleted file mode 100644 index bd99511a5..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/external_docs.go +++ /dev/null @@ -1,73 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/url" -) - -// ExternalDocs is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#external-documentation-object -type ExternalDocs struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Description string `json:"description,omitempty" yaml:"description,omitempty"` - URL string `json:"url,omitempty" yaml:"url,omitempty"` -} - -// MarshalJSON returns the JSON encoding of ExternalDocs. -func (e ExternalDocs) MarshalJSON() ([]byte, error) { - x, err := e.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of ExternalDocs. -func (e ExternalDocs) MarshalYAML() (any, error) { - m := make(map[string]any, 2+len(e.Extensions)) - for k, v := range e.Extensions { - m[k] = v - } - if x := e.Description; x != "" { - m["description"] = x - } - if x := e.URL; x != "" { - m["url"] = x - } - return m, nil -} - -// UnmarshalJSON sets ExternalDocs to a copy of data. -func (e *ExternalDocs) UnmarshalJSON(data []byte) error { - type ExternalDocsBis ExternalDocs - var x ExternalDocsBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "description") - delete(x.Extensions, "url") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *e = ExternalDocs(x) - return nil -} - -// Validate returns an error if ExternalDocs does not comply with the OpenAPI spec. -func (e *ExternalDocs) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if e.URL == "" { - return errors.New("url is required") - } - if _, err := url.Parse(e.URL); err != nil { - return fmt.Errorf("url is incorrect: %w", err) - } - - return validateExtensions(ctx, e.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/header.go b/vendor/github.com/getkin/kin-openapi/openapi3/header.go deleted file mode 100644 index dc542874d..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/header.go +++ /dev/null @@ -1,96 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - - "github.com/go-openapi/jsonpointer" -) - -// Header is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#header-object -type Header struct { - Parameter -} - -var _ jsonpointer.JSONPointable = (*Header)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (header Header) JSONLookup(token string) (any, error) { - return header.Parameter.JSONLookup(token) -} - -// MarshalJSON returns the JSON encoding of Header. -func (header Header) MarshalJSON() ([]byte, error) { - return header.Parameter.MarshalJSON() -} - -// UnmarshalJSON sets Header to a copy of data. -func (header *Header) UnmarshalJSON(data []byte) error { - return header.Parameter.UnmarshalJSON(data) -} - -// MarshalYAML returns the JSON encoding of Header. -func (header Header) MarshalYAML() (any, error) { - return header.Parameter, nil -} - -// SerializationMethod returns a header's serialization method. -func (header *Header) SerializationMethod() (*SerializationMethod, error) { - style := header.Style - if style == "" { - style = SerializationSimple - } - explode := false - if header.Explode != nil { - explode = *header.Explode - } - return &SerializationMethod{Style: style, Explode: explode}, nil -} - -// Validate returns an error if Header does not comply with the OpenAPI spec. -func (header *Header) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if header.Name != "" { - return errors.New("header 'name' MUST NOT be specified, it is given in the corresponding headers map") - } - if header.In != "" { - return errors.New("header 'in' MUST NOT be specified, it is implicitly in header") - } - - // Validate a parameter's serialization method. - sm, err := header.SerializationMethod() - if err != nil { - return err - } - if smSupported := false || - sm.Style == SerializationSimple && !sm.Explode || - sm.Style == SerializationSimple && sm.Explode; !smSupported { - e := fmt.Errorf("serialization method with style=%q and explode=%v is not supported by a header parameter", sm.Style, sm.Explode) - return fmt.Errorf("header schema is invalid: %w", e) - } - - if (header.Schema == nil) == (len(header.Content) == 0) { - e := fmt.Errorf("parameter must contain exactly one of content and schema: %v", header) - return fmt.Errorf("header schema is invalid: %w", e) - } - if schema := header.Schema; schema != nil { - if err := schema.Validate(ctx); err != nil { - return fmt.Errorf("header schema is invalid: %w", err) - } - } - - if content := header.Content; content != nil { - e := errors.New("parameter content must only contain one entry") - if len(content) > 1 { - return fmt.Errorf("header content is invalid: %w", e) - } - - if err := content.Validate(ctx); err != nil { - return fmt.Errorf("header content is invalid: %w", err) - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/helpers.go b/vendor/github.com/getkin/kin-openapi/openapi3/helpers.go deleted file mode 100644 index d50b3d847..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/helpers.go +++ /dev/null @@ -1,261 +0,0 @@ -package openapi3 - -import ( - "fmt" - "net/url" - "path" - "reflect" - "regexp" - "sort" - "strings" - - "github.com/go-openapi/jsonpointer" -) - -const identifierChars = `a-zA-Z0-9._-` - -// IdentifierRegExp verifies whether Component object key matches contains just 'identifierChars', according to OpenAPI v3.x. -// InvalidIdentifierCharRegExp matches all characters not contained in 'identifierChars'. -// However, to be able supporting legacy OpenAPI v2.x, there is a need to customize above pattern in order not to fail -// converted v2-v3 validation -var ( - IdentifierRegExp = regexp.MustCompile(`^[` + identifierChars + `]+$`) - InvalidIdentifierCharRegExp = regexp.MustCompile(`[^` + identifierChars + `]`) -) - -// ValidateIdentifier returns an error if the given component name does not match [IdentifierRegExp]. -func ValidateIdentifier(value string) error { - if IdentifierRegExp.MatchString(value) { - return nil - } - return fmt.Errorf("identifier %q is not supported by OpenAPIv3 standard (charset: [%q])", value, identifierChars) -} - -// Float64Ptr is a helper for defining OpenAPI schemas. -func Float64Ptr(value float64) *float64 { - return &value -} - -// BoolPtr is a helper for defining OpenAPI schemas. -func BoolPtr(value bool) *bool { - return &value -} - -// Int64Ptr is a helper for defining OpenAPI schemas. -func Int64Ptr(value int64) *int64 { - return &value -} - -// Uint64Ptr is a helper for defining OpenAPI schemas. -func Uint64Ptr(value uint64) *uint64 { - return &value -} - -// componentNames returns the map keys in a sorted slice. -func componentNames[E any](s map[string]E) []string { - out := make([]string, 0, len(s)) - for i := range s { - out = append(out, i) - } - sort.Strings(out) - return out -} - -// copyURI makes a copy of the pointer. -func copyURI(u *url.URL) *url.URL { - if u == nil { - return nil - } - - c := *u // shallow-copy - return &c -} - -type ComponentRef interface { - RefString() string - RefPath() *url.URL - CollectionName() string -} - -// refersToSameDocument returns if the $ref refers to the same document. -// -// Documents in different directories will have distinct $ref values that resolve to -// the same document. -// For example, consider the 3 files: -// -// /records.yaml -// /root.yaml $ref: records.yaml -// /schema/other.yaml $ref: ../records.yaml -// -// The records.yaml reference in the 2 latter refers to the same document. -func refersToSameDocument(o1 ComponentRef, o2 ComponentRef) bool { - if o1 == nil || o2 == nil { - return false - } - - r1 := o1.RefPath() - r2 := o2.RefPath() - - if r1 == nil || r2 == nil { - return false - } - - // refURL is relative to the working directory & base spec file. - return referenceURIMatch(r1, r2) -} - -// referencesRootDocument returns if the $ref points to the root document of the OpenAPI spec. -// -// If the document has no location, perhaps loaded from data in memory, it always returns false. -func referencesRootDocument(doc *T, ref ComponentRef) bool { - if doc.url == nil || ref == nil || ref.RefPath() == nil { - return false - } - - refURL := *ref.RefPath() - refURL.Fragment = "" - - // Check referenced element was in the root document. - return referenceURIMatch(doc.url, &refURL) -} - -func referenceURIMatch(u1 *url.URL, u2 *url.URL) bool { - s1, s2 := *u1, *u2 - if s1.Scheme == "" { - s1.Scheme = "file" - } - if s2.Scheme == "" { - s2.Scheme = "file" - } - - return s1.String() == s2.String() -} - -// ReferencesComponentInRootDocument returns if the given component reference references -// the same document or element as another component reference in the root document's -// '#/components/'. If it does, it returns the name of it in the form -// '#/components//NameXXX' -// -// Of course given a component from the root document will always match itself. -// -// https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#reference-object -// https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#relative-references-in-urls -// -// Example. Take the spec with directory structure: -// -// openapi.yaml -// schemas/ -// ├─ record.yaml -// ├─ records.yaml -// -// In openapi.yaml we have: -// -// components: -// schemas: -// Record: -// $ref: schemas/record.yaml -// -// Case 1: records.yml references a component in the root document -// -// $ref: ../openapi.yaml#/components/schemas/Record -// -// This would return... -// -// #/components/schemas/Record -// -// Case 2: records.yml indirectly refers to the same schema -// as a schema the root document's '#/components/schemas'. -// -// $ref: ./record.yaml -// -// This would also return... -// -// #/components/schemas/Record -func ReferencesComponentInRootDocument(doc *T, ref ComponentRef) (string, bool) { - if ref == nil || ref.RefString() == "" { - return "", false - } - - // Case 1: - // Something like: ../another-folder/document.json#/myElement - if isRemoteReference(ref.RefString()) && isRootComponentReference(ref.RefString(), ref.CollectionName()) { - // Determine if it is *this* root doc. - if referencesRootDocument(doc, ref) { - _, name, _ := strings.Cut(ref.RefString(), path.Join("#/components/", ref.CollectionName())) - - return path.Join("#/components/", ref.CollectionName(), name), true - } - } - - // If there are no schemas defined in the root document return early. - if doc.Components == nil { - return "", false - } - - collection, _, err := jsonpointer.GetForToken(doc.Components, ref.CollectionName()) - if err != nil { - panic(err) // unreachable - } - - var components map[string]ComponentRef - - componentRefType := reflect.TypeOf(new(ComponentRef)).Elem() - if t := reflect.TypeOf(collection); t.Kind() == reflect.Map && - t.Key().Kind() == reflect.String && - t.Elem().AssignableTo(componentRefType) { - v := reflect.ValueOf(collection) - - components = make(map[string]ComponentRef, v.Len()) - for _, key := range v.MapKeys() { - strct := v.MapIndex(key) - // Type assertion safe, already checked via reflection above. - components[key.Interface().(string)] = strct.Interface().(ComponentRef) - } - } else { - return "", false - } - - // Case 2: - // Something like: ../openapi.yaml#/components/schemas/myElement - for name, s := range components { - // Must be a reference to a YAML file. - if !isWholeDocumentReference(s.RefString()) { - continue - } - - // Is the schema a ref to the same resource. - if !refersToSameDocument(s, ref) { - continue - } - - // Transform the remote ref to the equivalent schema in the root document. - return path.Join("#/components/", ref.CollectionName(), name), true - } - - return "", false -} - -// isElementReference takes a $ref value and checks if it references a specific element. -func isElementReference(ref string) bool { - return ref != "" && !isWholeDocumentReference(ref) -} - -// isSchemaReference takes a $ref value and checks if it references a schema element. -func isRootComponentReference(ref string, compType string) bool { - return isElementReference(ref) && strings.Contains(ref, path.Join("#/components/", compType)) -} - -// isWholeDocumentReference takes a $ref value and checks if it is whole document reference. -func isWholeDocumentReference(ref string) bool { - return ref != "" && !strings.ContainsAny(ref, "#") -} - -// isRemoteReference takes a $ref value and checks if it is remote reference. -func isRemoteReference(ref string) bool { - return ref != "" && !strings.HasPrefix(ref, "#") && !isURLReference(ref) -} - -// isURLReference takes a $ref value and checks if it is URL reference. -func isURLReference(ref string) bool { - return strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://") || strings.HasPrefix(ref, "//") -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/info.go b/vendor/github.com/getkin/kin-openapi/openapi3/info.go deleted file mode 100644 index e2468285c..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/info.go +++ /dev/null @@ -1,103 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" -) - -// Info is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#info-object -type Info struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Title string `json:"title" yaml:"title"` // Required - Description string `json:"description,omitempty" yaml:"description,omitempty"` - TermsOfService string `json:"termsOfService,omitempty" yaml:"termsOfService,omitempty"` - Contact *Contact `json:"contact,omitempty" yaml:"contact,omitempty"` - License *License `json:"license,omitempty" yaml:"license,omitempty"` - Version string `json:"version" yaml:"version"` // Required -} - -// MarshalJSON returns the JSON encoding of Info. -func (info Info) MarshalJSON() ([]byte, error) { - x, err := info.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Info. -func (info *Info) MarshalYAML() (any, error) { - if info == nil { - return nil, nil - } - m := make(map[string]any, 6+len(info.Extensions)) - for k, v := range info.Extensions { - m[k] = v - } - m["title"] = info.Title - if x := info.Description; x != "" { - m["description"] = x - } - if x := info.TermsOfService; x != "" { - m["termsOfService"] = x - } - if x := info.Contact; x != nil { - m["contact"] = x - } - if x := info.License; x != nil { - m["license"] = x - } - m["version"] = info.Version - return m, nil -} - -// UnmarshalJSON sets Info to a copy of data. -func (info *Info) UnmarshalJSON(data []byte) error { - type InfoBis Info - var x InfoBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "title") - delete(x.Extensions, "description") - delete(x.Extensions, "termsOfService") - delete(x.Extensions, "contact") - delete(x.Extensions, "license") - delete(x.Extensions, "version") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *info = Info(x) - return nil -} - -// Validate returns an error if Info does not comply with the OpenAPI spec. -func (info *Info) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if contact := info.Contact; contact != nil { - if err := contact.Validate(ctx); err != nil { - return err - } - } - - if license := info.License; license != nil { - if err := license.Validate(ctx); err != nil { - return err - } - } - - if info.Version == "" { - return errors.New("value of version must be a non-empty string") - } - - if info.Title == "" { - return errors.New("value of title must be a non-empty string") - } - - return validateExtensions(ctx, info.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/internalize_refs.go b/vendor/github.com/getkin/kin-openapi/openapi3/internalize_refs.go deleted file mode 100644 index 01f5dad88..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/internalize_refs.go +++ /dev/null @@ -1,546 +0,0 @@ -package openapi3 - -import ( - "context" - "path" - "strings" -) - -// RefNameResolver maps a component to an name that is used as it's internalized name. -// -// The function should avoid name collisions (i.e. be a injective mapping). -// It must only contain characters valid for fixed field names: [IdentifierRegExp]. -type RefNameResolver func(*T, ComponentRef) string - -// DefaultRefResolver is a default implementation of refNameResolver for the -// InternalizeRefs function. -// -// The external reference is internalized to (hopefully) a unique name. If -// the external reference matches (by path) to another reference in the root -// document then the name of that component is used. -// -// The transformation involves: -// - Cutting the "#/components/" part. -// - Cutting the file extensions (.yaml/.json) from documents. -// - Trimming the common directory with the root spec. -// - Replace invalid characters with with underscores. -// -// This is an injective mapping over a "reasonable" amount of the possible openapi -// spec domain space but is not perfect. There might be edge cases. -func DefaultRefNameResolver(doc *T, ref ComponentRef) string { - if ref.RefString() == "" || ref.RefPath() == nil { - panic("unable to resolve reference to name") - } - - name := ref.RefPath() - - // If refering to a component in the root spec, no need to internalize just use - // the existing component. - // XXX(percivalalb): since this function call is iterating over components behind the - // scenes during an internalization call it actually starts interating over - // new & replaced internalized components. This might caused some edge cases, - // haven't found one yet but this might need to actually be used on a frozen copy - // of doc. - if nameInRoot, found := ReferencesComponentInRootDocument(doc, ref); found { - nameInRoot = strings.TrimPrefix(nameInRoot, "#") - - rootCompURI := copyURI(doc.url) - rootCompURI.Fragment = nameInRoot - name = rootCompURI - } - - filePath, componentPath := name.Path, name.Fragment - - // Cut out the "#/components/" to make the names shorter. - // XXX(percivalalb): This might cause collisions but is worth the brevity. - if b, a, ok := strings.Cut(componentPath, path.Join("components", ref.CollectionName(), "")); ok { - componentPath = path.Join(b, a) - } - - if filePath != "" { - // If the path is the same as the root doc, just remove. - if doc.url != nil && filePath == doc.url.Path { - filePath = "" - } - - // Remove the path extentions to make this JSON/YAML agnostic. - for ext := path.Ext(filePath); len(ext) > 0; ext = path.Ext(filePath) { - filePath = strings.TrimSuffix(filePath, ext) - } - - // Trim the common prefix with the root doc path. - if doc.url != nil { - commonDir := path.Dir(doc.url.Path) - for { - if commonDir == "." { // no common prefix - break - } - - if p, found := cutDirectories(filePath, commonDir); found { - filePath = p - break - } - - commonDir = path.Dir(commonDir) - } - } - } - - var internalizedName string - - // Trim .'s & slashes from start e.g. otherwise ./doc.yaml would end up as __doc - if filePath != "" { - internalizedName = strings.TrimLeft(filePath, "./") - } - - if componentPath != "" { - if internalizedName != "" { - internalizedName += "_" - } - - internalizedName += strings.TrimLeft(componentPath, "./") - } - - // Replace invalid characters in component fixed field names. - internalizedName = InvalidIdentifierCharRegExp.ReplaceAllString(internalizedName, "_") - - return internalizedName -} - -// cutDirectories removes the given directories from the start of the path if -// the path is a child. -func cutDirectories(p, dirs string) (string, bool) { - if dirs == "" || p == "" { - return p, false - } - - p = strings.TrimRight(p, "/") - dirs = strings.TrimRight(dirs, "/") - - var sb strings.Builder - sb.Grow(len(ParameterInHeader)) - for _, segments := range strings.Split(p, "/") { - sb.WriteString(segments) - - if sb.String() == p { - return strings.TrimPrefix(p, dirs), true - } - - sb.WriteRune('/') - } - - return p, false -} - -func isExternalRef(ref string, parentIsExternal bool) bool { - return ref != "" && (!strings.HasPrefix(ref, "#/components/") || parentIsExternal) -} - -func (doc *T) addSchemaToSpec(s *SchemaRef, refNameResolver RefNameResolver, parentIsExternal bool) bool { - if s == nil || !isExternalRef(s.Ref, parentIsExternal) { - return false - } - - name := refNameResolver(doc, s) - if doc.Components != nil { - if _, ok := doc.Components.Schemas[name]; ok { - s.Ref = "#/components/schemas/" + name - return true - } - } - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.Schemas == nil { - doc.Components.Schemas = make(Schemas) - } - doc.Components.Schemas[name] = s.Value.NewRef() - s.Ref = "#/components/schemas/" + name - return true -} - -func (doc *T) addParameterToSpec(p *ParameterRef, refNameResolver RefNameResolver, parentIsExternal bool) bool { - if p == nil || !isExternalRef(p.Ref, parentIsExternal) { - return false - } - name := refNameResolver(doc, p) - if doc.Components != nil { - if _, ok := doc.Components.Parameters[name]; ok { - p.Ref = "#/components/parameters/" + name - return true - } - } - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.Parameters == nil { - doc.Components.Parameters = make(ParametersMap) - } - doc.Components.Parameters[name] = &ParameterRef{Value: p.Value} - p.Ref = "#/components/parameters/" + name - return true -} - -func (doc *T) addHeaderToSpec(h *HeaderRef, refNameResolver RefNameResolver, parentIsExternal bool) bool { - if h == nil || !isExternalRef(h.Ref, parentIsExternal) { - return false - } - name := refNameResolver(doc, h) - if doc.Components != nil { - if _, ok := doc.Components.Headers[name]; ok { - h.Ref = "#/components/headers/" + name - return true - } - } - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.Headers == nil { - doc.Components.Headers = make(Headers) - } - doc.Components.Headers[name] = &HeaderRef{Value: h.Value} - h.Ref = "#/components/headers/" + name - return true -} - -func (doc *T) addRequestBodyToSpec(r *RequestBodyRef, refNameResolver RefNameResolver, parentIsExternal bool) bool { - if r == nil || !isExternalRef(r.Ref, parentIsExternal) { - return false - } - name := refNameResolver(doc, r) - if doc.Components != nil { - if _, ok := doc.Components.RequestBodies[name]; ok { - r.Ref = "#/components/requestBodies/" + name - return true - } - } - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.RequestBodies == nil { - doc.Components.RequestBodies = make(RequestBodies) - } - doc.Components.RequestBodies[name] = &RequestBodyRef{Value: r.Value} - r.Ref = "#/components/requestBodies/" + name - return true -} - -func (doc *T) addResponseToSpec(r *ResponseRef, refNameResolver RefNameResolver, parentIsExternal bool) bool { - if r == nil || !isExternalRef(r.Ref, parentIsExternal) { - return false - } - name := refNameResolver(doc, r) - if doc.Components != nil { - if _, ok := doc.Components.Responses[name]; ok { - r.Ref = "#/components/responses/" + name - return true - } - } - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.Responses == nil { - doc.Components.Responses = make(ResponseBodies) - } - doc.Components.Responses[name] = &ResponseRef{Value: r.Value} - r.Ref = "#/components/responses/" + name - return true -} - -func (doc *T) addSecuritySchemeToSpec(ss *SecuritySchemeRef, refNameResolver RefNameResolver, parentIsExternal bool) { - if ss == nil || !isExternalRef(ss.Ref, parentIsExternal) { - return - } - name := refNameResolver(doc, ss) - if doc.Components != nil { - if _, ok := doc.Components.SecuritySchemes[name]; ok { - ss.Ref = "#/components/securitySchemes/" + name - return - } - } - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.SecuritySchemes == nil { - doc.Components.SecuritySchemes = make(SecuritySchemes) - } - doc.Components.SecuritySchemes[name] = &SecuritySchemeRef{Value: ss.Value} - ss.Ref = "#/components/securitySchemes/" + name - -} - -func (doc *T) addExampleToSpec(e *ExampleRef, refNameResolver RefNameResolver, parentIsExternal bool) { - if e == nil || !isExternalRef(e.Ref, parentIsExternal) { - return - } - name := refNameResolver(doc, e) - if doc.Components != nil { - if _, ok := doc.Components.Examples[name]; ok { - e.Ref = "#/components/examples/" + name - return - } - } - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.Examples == nil { - doc.Components.Examples = make(Examples) - } - doc.Components.Examples[name] = &ExampleRef{Value: e.Value} - e.Ref = "#/components/examples/" + name - -} - -func (doc *T) addLinkToSpec(l *LinkRef, refNameResolver RefNameResolver, parentIsExternal bool) { - if l == nil || !isExternalRef(l.Ref, parentIsExternal) { - return - } - name := refNameResolver(doc, l) - if doc.Components != nil { - if _, ok := doc.Components.Links[name]; ok { - l.Ref = "#/components/links/" + name - return - } - } - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.Links == nil { - doc.Components.Links = make(Links) - } - doc.Components.Links[name] = &LinkRef{Value: l.Value} - l.Ref = "#/components/links/" + name - -} - -func (doc *T) addCallbackToSpec(c *CallbackRef, refNameResolver RefNameResolver, parentIsExternal bool) bool { - if c == nil || !isExternalRef(c.Ref, parentIsExternal) { - return false - } - name := refNameResolver(doc, c) - - if doc.Components == nil { - doc.Components = &Components{} - } - if doc.Components.Callbacks == nil { - doc.Components.Callbacks = make(Callbacks) - } - c.Ref = "#/components/callbacks/" + name - doc.Components.Callbacks[name] = &CallbackRef{Value: c.Value} - return true -} - -func (doc *T) derefSchema(s *Schema, refNameResolver RefNameResolver, parentIsExternal bool) { - if s == nil || doc.isVisitedSchema(s) { - return - } - - for _, list := range []SchemaRefs{s.AllOf, s.AnyOf, s.OneOf} { - for _, s2 := range list { - isExternal := doc.addSchemaToSpec(s2, refNameResolver, parentIsExternal) - if s2 != nil { - doc.derefSchema(s2.Value, refNameResolver, isExternal || parentIsExternal) - } - } - } - - for _, name := range componentNames(s.Properties) { - s2 := s.Properties[name] - isExternal := doc.addSchemaToSpec(s2, refNameResolver, parentIsExternal) - if s2 != nil { - doc.derefSchema(s2.Value, refNameResolver, isExternal || parentIsExternal) - } - } - for _, ref := range []*SchemaRef{s.Not, s.AdditionalProperties.Schema, s.Items} { - isExternal := doc.addSchemaToSpec(ref, refNameResolver, parentIsExternal) - if ref != nil { - doc.derefSchema(ref.Value, refNameResolver, isExternal || parentIsExternal) - } - } -} - -func (doc *T) derefHeaders(hs Headers, refNameResolver RefNameResolver, parentIsExternal bool) { - for _, name := range componentNames(hs) { - h := hs[name] - isExternal := doc.addHeaderToSpec(h, refNameResolver, parentIsExternal) - if doc.isVisitedHeader(h.Value) { - continue - } - doc.derefParameter(h.Value.Parameter, refNameResolver, parentIsExternal || isExternal) - } -} - -func (doc *T) derefExamples(es Examples, refNameResolver RefNameResolver, parentIsExternal bool) { - for _, name := range componentNames(es) { - e := es[name] - doc.addExampleToSpec(e, refNameResolver, parentIsExternal) - } -} - -func (doc *T) derefContent(c Content, refNameResolver RefNameResolver, parentIsExternal bool) { - for _, name := range componentNames(c) { - mediatype := c[name] - isExternal := doc.addSchemaToSpec(mediatype.Schema, refNameResolver, parentIsExternal) - if mediatype.Schema != nil { - doc.derefSchema(mediatype.Schema.Value, refNameResolver, isExternal || parentIsExternal) - } - doc.derefExamples(mediatype.Examples, refNameResolver, parentIsExternal) - for _, name := range componentNames(mediatype.Encoding) { - e := mediatype.Encoding[name] - doc.derefHeaders(e.Headers, refNameResolver, parentIsExternal) - } - } -} - -func (doc *T) derefLinks(ls Links, refNameResolver RefNameResolver, parentIsExternal bool) { - for _, name := range componentNames(ls) { - l := ls[name] - doc.addLinkToSpec(l, refNameResolver, parentIsExternal) - } -} - -func (doc *T) derefResponse(r *ResponseRef, refNameResolver RefNameResolver, parentIsExternal bool) { - isExternal := doc.addResponseToSpec(r, refNameResolver, parentIsExternal) - if v := r.Value; v != nil { - doc.derefHeaders(v.Headers, refNameResolver, isExternal || parentIsExternal) - doc.derefContent(v.Content, refNameResolver, isExternal || parentIsExternal) - doc.derefLinks(v.Links, refNameResolver, isExternal || parentIsExternal) - } -} - -func (doc *T) derefResponses(rs *Responses, refNameResolver RefNameResolver, parentIsExternal bool) { - doc.derefResponseBodies(rs.Map(), refNameResolver, parentIsExternal) -} - -func (doc *T) derefResponseBodies(es ResponseBodies, refNameResolver RefNameResolver, parentIsExternal bool) { - for _, name := range componentNames(es) { - e := es[name] - doc.derefResponse(e, refNameResolver, parentIsExternal) - } -} - -func (doc *T) derefParameter(p Parameter, refNameResolver RefNameResolver, parentIsExternal bool) { - isExternal := doc.addSchemaToSpec(p.Schema, refNameResolver, parentIsExternal) - doc.derefContent(p.Content, refNameResolver, parentIsExternal) - if p.Schema != nil { - doc.derefSchema(p.Schema.Value, refNameResolver, isExternal || parentIsExternal) - } -} - -func (doc *T) derefRequestBody(r RequestBody, refNameResolver RefNameResolver, parentIsExternal bool) { - doc.derefContent(r.Content, refNameResolver, parentIsExternal) -} - -func (doc *T) derefPaths(paths map[string]*PathItem, refNameResolver RefNameResolver, parentIsExternal bool) { - for _, name := range componentNames(paths) { - ops := paths[name] - pathIsExternal := isExternalRef(ops.Ref, parentIsExternal) - // inline full operations - ops.Ref = "" - - for _, param := range ops.Parameters { - isExternal := doc.addParameterToSpec(param, refNameResolver, pathIsExternal) - if param.Value != nil { - doc.derefParameter(*param.Value, refNameResolver, pathIsExternal || isExternal) - } - } - - opsWithMethod := ops.Operations() - for _, name := range componentNames(opsWithMethod) { - op := opsWithMethod[name] - isExternal := doc.addRequestBodyToSpec(op.RequestBody, refNameResolver, pathIsExternal) - if op.RequestBody != nil && op.RequestBody.Value != nil { - doc.derefRequestBody(*op.RequestBody.Value, refNameResolver, pathIsExternal || isExternal) - } - for _, name := range componentNames(op.Callbacks) { - cb := op.Callbacks[name] - isExternal := doc.addCallbackToSpec(cb, refNameResolver, pathIsExternal) - if cb.Value != nil { - cbValue := (*cb.Value).Map() - doc.derefPaths(cbValue, refNameResolver, pathIsExternal || isExternal) - } - } - doc.derefResponses(op.Responses, refNameResolver, pathIsExternal) - for _, param := range op.Parameters { - isExternal := doc.addParameterToSpec(param, refNameResolver, pathIsExternal) - if param.Value != nil { - doc.derefParameter(*param.Value, refNameResolver, pathIsExternal || isExternal) - } - } - } - } -} - -// InternalizeRefs removes all references to external files from the spec and moves them -// to the components section. -// -// refNameResolver takes in references to returns a name to store the reference under locally. -// It MUST return a unique name for each reference type. -// A default implementation is provided that will suffice for most use cases. See the function -// documentation for more details. -// -// Example: -// -// doc.InternalizeRefs(context.Background(), nil) -func (doc *T) InternalizeRefs(ctx context.Context, refNameResolver func(*T, ComponentRef) string) { - doc.resetVisited() - - if refNameResolver == nil { - refNameResolver = DefaultRefNameResolver - } - - if components := doc.Components; components != nil { - for _, name := range componentNames(components.Schemas) { - schema := components.Schemas[name] - isExternal := doc.addSchemaToSpec(schema, refNameResolver, false) - if schema != nil { - schema.Ref = "" // always dereference the top level - doc.derefSchema(schema.Value, refNameResolver, isExternal) - } - } - for _, name := range componentNames(components.Parameters) { - p := components.Parameters[name] - isExternal := doc.addParameterToSpec(p, refNameResolver, false) - if p != nil && p.Value != nil { - p.Ref = "" // always dereference the top level - doc.derefParameter(*p.Value, refNameResolver, isExternal) - } - } - doc.derefHeaders(components.Headers, refNameResolver, false) - for _, name := range componentNames(components.RequestBodies) { - req := components.RequestBodies[name] - isExternal := doc.addRequestBodyToSpec(req, refNameResolver, false) - if req != nil && req.Value != nil { - req.Ref = "" // always dereference the top level - doc.derefRequestBody(*req.Value, refNameResolver, isExternal) - } - } - doc.derefResponseBodies(components.Responses, refNameResolver, false) - for _, name := range componentNames(components.SecuritySchemes) { - ss := components.SecuritySchemes[name] - doc.addSecuritySchemeToSpec(ss, refNameResolver, false) - } - doc.derefExamples(components.Examples, refNameResolver, false) - doc.derefLinks(components.Links, refNameResolver, false) - - for _, name := range componentNames(components.Callbacks) { - cb := components.Callbacks[name] - isExternal := doc.addCallbackToSpec(cb, refNameResolver, false) - if cb != nil && cb.Value != nil { - cb.Ref = "" // always dereference the top level - cbValue := (*cb.Value).Map() - doc.derefPaths(cbValue, refNameResolver, isExternal) - } - } - } - - doc.derefPaths(doc.Paths.Map(), refNameResolver, false) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/license.go b/vendor/github.com/getkin/kin-openapi/openapi3/license.go deleted file mode 100644 index c4f6c8dc3..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/license.go +++ /dev/null @@ -1,66 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" -) - -// License is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#license-object -type License struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Name string `json:"name" yaml:"name"` // Required - URL string `json:"url,omitempty" yaml:"url,omitempty"` -} - -// MarshalJSON returns the JSON encoding of License. -func (license License) MarshalJSON() ([]byte, error) { - x, err := license.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of License. -func (license License) MarshalYAML() (any, error) { - m := make(map[string]any, 2+len(license.Extensions)) - for k, v := range license.Extensions { - m[k] = v - } - m["name"] = license.Name - if x := license.URL; x != "" { - m["url"] = x - } - return m, nil -} - -// UnmarshalJSON sets License to a copy of data. -func (license *License) UnmarshalJSON(data []byte) error { - type LicenseBis License - var x LicenseBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "name") - delete(x.Extensions, "url") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *license = License(x) - return nil -} - -// Validate returns an error if License does not comply with the OpenAPI spec. -func (license *License) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if license.Name == "" { - return errors.New("value of license name must be a non-empty string") - } - - return validateExtensions(ctx, license.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/link.go b/vendor/github.com/getkin/kin-openapi/openapi3/link.go deleted file mode 100644 index 132f67803..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/link.go +++ /dev/null @@ -1,94 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" -) - -// Link is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#link-object -type Link struct { - Extensions map[string]any `json:"-" yaml:"-"` - - OperationRef string `json:"operationRef,omitempty" yaml:"operationRef,omitempty"` - OperationID string `json:"operationId,omitempty" yaml:"operationId,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Parameters map[string]any `json:"parameters,omitempty" yaml:"parameters,omitempty"` - Server *Server `json:"server,omitempty" yaml:"server,omitempty"` - RequestBody any `json:"requestBody,omitempty" yaml:"requestBody,omitempty"` -} - -// MarshalJSON returns the JSON encoding of Link. -func (link Link) MarshalJSON() ([]byte, error) { - x, err := link.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Link. -func (link Link) MarshalYAML() (any, error) { - m := make(map[string]any, 6+len(link.Extensions)) - for k, v := range link.Extensions { - m[k] = v - } - - if x := link.OperationRef; x != "" { - m["operationRef"] = x - } - if x := link.OperationID; x != "" { - m["operationId"] = x - } - if x := link.Description; x != "" { - m["description"] = x - } - if x := link.Parameters; len(x) != 0 { - m["parameters"] = x - } - if x := link.Server; x != nil { - m["server"] = x - } - if x := link.RequestBody; x != nil { - m["requestBody"] = x - } - - return m, nil -} - -// UnmarshalJSON sets Link to a copy of data. -func (link *Link) UnmarshalJSON(data []byte) error { - type LinkBis Link - var x LinkBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "operationRef") - delete(x.Extensions, "operationId") - delete(x.Extensions, "description") - delete(x.Extensions, "parameters") - delete(x.Extensions, "server") - delete(x.Extensions, "requestBody") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *link = Link(x) - return nil -} - -// Validate returns an error if Link does not comply with the OpenAPI spec. -func (link *Link) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if link.OperationID == "" && link.OperationRef == "" { - return errors.New("missing operationId or operationRef on link") - } - if link.OperationID != "" && link.OperationRef != "" { - return fmt.Errorf("operationId %q and operationRef %q are mutually exclusive", link.OperationID, link.OperationRef) - } - - return validateExtensions(ctx, link.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/loader.go b/vendor/github.com/getkin/kin-openapi/openapi3/loader.go deleted file mode 100644 index 31c340761..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/loader.go +++ /dev/null @@ -1,1213 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/url" - "os" - "path" - "path/filepath" - "reflect" - "strconv" - "strings" -) - -func foundUnresolvedRef(ref string) error { - return fmt.Errorf("found unresolved ref: %q", ref) -} - -func failedToResolveRefFragmentPart(value, what string) error { - return fmt.Errorf("failed to resolve %q in fragment in URI: %q", what, value) -} - -// Loader helps deserialize an OpenAPIv3 document -type Loader struct { - // IsExternalRefsAllowed enables visiting other files - IsExternalRefsAllowed bool - - // ReadFromURIFunc allows overriding the any file/URL reading func - ReadFromURIFunc ReadFromURIFunc - - Context context.Context - - rootDir string - rootLocation string - - visitedPathItemRefs map[string]struct{} - - visitedDocuments map[string]*T - - visitedRefs map[string]struct{} - visitedPath []string - backtrack map[string][]func(value any) -} - -// NewLoader returns an empty Loader -func NewLoader() *Loader { - return &Loader{ - Context: context.Background(), - } -} - -func (loader *Loader) resetVisitedPathItemRefs() { - loader.visitedPathItemRefs = make(map[string]struct{}) - loader.visitedRefs = make(map[string]struct{}) - loader.visitedPath = nil - loader.backtrack = make(map[string][]func(value any)) -} - -// LoadFromURI loads a spec from a remote URL -func (loader *Loader) LoadFromURI(location *url.URL) (*T, error) { - loader.resetVisitedPathItemRefs() - return loader.loadFromURIInternal(location) -} - -// LoadFromFile loads a spec from a local file path -func (loader *Loader) LoadFromFile(location string) (*T, error) { - loader.rootDir = path.Dir(location) - return loader.LoadFromURI(&url.URL{Path: filepath.ToSlash(location)}) -} - -func (loader *Loader) loadFromURIInternal(location *url.URL) (*T, error) { - data, err := loader.readURL(location) - if err != nil { - return nil, err - } - return loader.loadFromDataWithPathInternal(data, location) -} - -func (loader *Loader) allowsExternalRefs(ref string) (err error) { - if !loader.IsExternalRefsAllowed { - err = fmt.Errorf("encountered disallowed external reference: %q", ref) - } - return -} - -func (loader *Loader) loadSingleElementFromURI(ref string, rootPath *url.URL, element any) (*url.URL, error) { - if err := loader.allowsExternalRefs(ref); err != nil { - return nil, err - } - - resolvedPath, err := resolvePathWithRef(ref, rootPath) - if err != nil { - return nil, err - } - if frag := resolvedPath.Fragment; frag != "" { - return nil, fmt.Errorf("unexpected ref fragment %q", frag) - } - - data, err := loader.readURL(resolvedPath) - if err != nil { - return nil, err - } - if err := unmarshal(data, element); err != nil { - return nil, err - } - - return resolvedPath, nil -} - -func (loader *Loader) readURL(location *url.URL) ([]byte, error) { - if f := loader.ReadFromURIFunc; f != nil { - return f(loader, location) - } - return DefaultReadFromURI(loader, location) -} - -// LoadFromStdin loads a spec from stdin -func (loader *Loader) LoadFromStdin() (*T, error) { - return loader.LoadFromIoReader(os.Stdin) -} - -// LoadFromStdin loads a spec from io.Reader -func (loader *Loader) LoadFromIoReader(reader io.Reader) (*T, error) { - if reader == nil { - return nil, fmt.Errorf("invalid reader: %v", reader) - } - - data, err := io.ReadAll(reader) - if err != nil { - return nil, err - } - return loader.LoadFromData(data) -} - -// LoadFromData loads a spec from a byte array -func (loader *Loader) LoadFromData(data []byte) (*T, error) { - loader.resetVisitedPathItemRefs() - doc := &T{} - if err := unmarshal(data, doc); err != nil { - return nil, err - } - if err := loader.ResolveRefsIn(doc, nil); err != nil { - return nil, err - } - return doc, nil -} - -// LoadFromDataWithPath takes the OpenAPI document data in bytes and a path where the resolver can find referred -// elements and returns a *T with all resolved data or an error if unable to load data or resolve refs. -func (loader *Loader) LoadFromDataWithPath(data []byte, location *url.URL) (*T, error) { - loader.resetVisitedPathItemRefs() - return loader.loadFromDataWithPathInternal(data, location) -} - -func (loader *Loader) loadFromDataWithPathInternal(data []byte, location *url.URL) (*T, error) { - if loader.visitedDocuments == nil { - loader.visitedDocuments = make(map[string]*T) - loader.rootLocation = location.Path - } - uri := location.String() - if doc, ok := loader.visitedDocuments[uri]; ok { - return doc, nil - } - - doc := &T{} - loader.visitedDocuments[uri] = doc - - if err := unmarshal(data, doc); err != nil { - return nil, err - } - - doc.url = copyURI(location) - - if err := loader.ResolveRefsIn(doc, location); err != nil { - return nil, err - } - - return doc, nil -} - -// ResolveRefsIn expands references if for instance spec was just unmarshaled -func (loader *Loader) ResolveRefsIn(doc *T, location *url.URL) (err error) { - if loader.Context == nil { - loader.Context = context.Background() - } - - if loader.visitedPathItemRefs == nil { - loader.resetVisitedPathItemRefs() - } - - if components := doc.Components; components != nil { - for _, name := range componentNames(components.Headers) { - component := components.Headers[name] - if err = loader.resolveHeaderRef(doc, component, location); err != nil { - return - } - } - for _, name := range componentNames(components.Parameters) { - component := components.Parameters[name] - if err = loader.resolveParameterRef(doc, component, location); err != nil { - return - } - } - for _, name := range componentNames(components.RequestBodies) { - component := components.RequestBodies[name] - if err = loader.resolveRequestBodyRef(doc, component, location); err != nil { - return - } - } - for _, name := range componentNames(components.Responses) { - component := components.Responses[name] - if err = loader.resolveResponseRef(doc, component, location); err != nil { - return - } - } - for _, name := range componentNames(components.Schemas) { - component := components.Schemas[name] - if err = loader.resolveSchemaRef(doc, component, location, []string{}); err != nil { - return - } - } - for _, name := range componentNames(components.SecuritySchemes) { - component := components.SecuritySchemes[name] - if err = loader.resolveSecuritySchemeRef(doc, component, location); err != nil { - return - } - } - for _, name := range componentNames(components.Examples) { - component := components.Examples[name] - if err = loader.resolveExampleRef(doc, component, location); err != nil { - return - } - } - for _, name := range componentNames(components.Callbacks) { - component := components.Callbacks[name] - if err = loader.resolveCallbackRef(doc, component, location); err != nil { - return - } - } - } - - // Visit all operations - pathItems := doc.Paths.Map() - for _, name := range componentNames(pathItems) { - pathItem := pathItems[name] - if pathItem == nil { - continue - } - if err = loader.resolvePathItemRef(doc, pathItem, location); err != nil { - return - } - } - - return -} - -func join(basePath *url.URL, relativePath *url.URL) *url.URL { - if basePath == nil { - return relativePath - } - newPath := *basePath - newPath.Path = path.Join(path.Dir(newPath.Path), relativePath.Path) - return &newPath -} - -func resolvePath(basePath *url.URL, componentPath *url.URL) *url.URL { - if is_file(componentPath) { - // support absolute paths - if filepath.IsAbs(componentPath.Path) { - return componentPath - } - return join(basePath, componentPath) - } - return componentPath -} - -func resolvePathWithRef(ref string, rootPath *url.URL) (*url.URL, error) { - parsedURL, err := url.Parse(ref) - if err != nil { - return nil, fmt.Errorf("cannot parse reference: %q: %w", ref, err) - } - - resolvedPath := resolvePath(rootPath, parsedURL) - resolvedPath.Fragment = parsedURL.Fragment - return resolvedPath, nil -} - -func (loader *Loader) resolveRefPath(ref string, path *url.URL) (*url.URL, error) { - if ref != "" && ref[0] == '#' { - path = copyURI(path) - // Resolving internal refs of a doc loaded from memory - // has no path, so just set the Fragment. - if path == nil { - path = new(url.URL) - } - - path.Fragment = ref - return path, nil - } - - if err := loader.allowsExternalRefs(ref); err != nil { - return nil, err - } - - resolvedPath, err := resolvePathWithRef(ref, path) - if err != nil { - return nil, err - } - - return resolvedPath, nil -} - -func isSingleRefElement(ref string) bool { - return !strings.Contains(ref, "#") -} - -func (loader *Loader) visitRef(ref string) { - if loader.visitedRefs == nil { - loader.visitedRefs = make(map[string]struct{}) - loader.backtrack = make(map[string][]func(value any)) - } - loader.visitedPath = append(loader.visitedPath, ref) - loader.visitedRefs[ref] = struct{}{} -} - -func (loader *Loader) unvisitRef(ref string, value any) { - if value != nil { - for _, fn := range loader.backtrack[ref] { - fn(value) - } - } - delete(loader.visitedRefs, ref) - delete(loader.backtrack, ref) - loader.visitedPath = loader.visitedPath[:len(loader.visitedPath)-1] -} - -func (loader *Loader) shouldVisitRef(ref string, fn func(value any)) bool { - if _, ok := loader.visitedRefs[ref]; ok { - loader.backtrack[ref] = append(loader.backtrack[ref], fn) - return false - } - return true -} - -func (loader *Loader) resolveComponent(doc *T, ref string, path *url.URL, resolved any) ( - componentDoc *T, - componentPath *url.URL, - err error, -) { - if componentDoc, ref, componentPath, err = loader.resolveRefAndDocument(doc, ref, path); err != nil { - return nil, nil, err - } - - parsedURL, err := url.Parse(ref) - if err != nil { - return nil, nil, fmt.Errorf("cannot parse reference: %q: %v", ref, parsedURL) - } - fragment := parsedURL.Fragment - if fragment == "" { - fragment = "/" - } - if fragment[0] != '/' { - return nil, nil, fmt.Errorf("expected fragment prefix '#/' in URI %q", ref) - } - - drill := func(cursor any) (any, error) { - for _, pathPart := range strings.Split(fragment[1:], "/") { - pathPart = unescapeRefString(pathPart) - attempted := false - - switch c := cursor.(type) { - // Special case of T - // See issue856: a ref to doc => we assume that doc is a T => things live in T.Extensions - case *T: - if pathPart == "" { - cursor = c.Extensions - attempted = true - } - - // Special case due to multijson - case *SchemaRef: - if pathPart == "additionalProperties" { - if ap := c.Value.AdditionalProperties.Has; ap != nil { - cursor = *ap - } else { - cursor = c.Value.AdditionalProperties.Schema - } - attempted = true - } - - case *Responses: - cursor = c.m // m map[string]*ResponseRef - case *Callback: - cursor = c.m // m map[string]*PathItem - case *Paths: - cursor = c.m // m map[string]*PathItem - } - - if !attempted { - if cursor, err = drillIntoField(cursor, pathPart); err != nil { - e := failedToResolveRefFragmentPart(ref, pathPart) - return nil, fmt.Errorf("%s: %w", e, err) - } - } - - if cursor == nil { - return nil, failedToResolveRefFragmentPart(ref, pathPart) - } - } - return cursor, nil - } - var cursor any - if cursor, err = drill(componentDoc); err != nil { - if path == nil { - return nil, nil, err - } - var err2 error - data, err2 := loader.readURL(path) - if err2 != nil { - return nil, nil, err - } - if err2 = unmarshal(data, &cursor); err2 != nil { - return nil, nil, err - } - if cursor, err2 = drill(cursor); err2 != nil || cursor == nil { - return nil, nil, err - } - err = nil - } - - setPathRef := func(target any) { - if i, ok := target.(interface { - setRefPath(*url.URL) - }); ok { - pathRef := copyURI(componentPath) - // Resolving internal refs of a doc loaded from memory - // has no path, so just set the Fragment. - if pathRef == nil { - pathRef = new(url.URL) - } - pathRef.Fragment = fragment - - i.setRefPath(pathRef) - } - } - - switch { - case reflect.TypeOf(cursor) == reflect.TypeOf(resolved): - setPathRef(cursor) - - reflect.ValueOf(resolved).Elem().Set(reflect.ValueOf(cursor).Elem()) - return componentDoc, componentPath, nil - - case reflect.TypeOf(cursor) == reflect.TypeOf(map[string]any{}): - codec := func(got, expect any) error { - enc, err := json.Marshal(got) - if err != nil { - return err - } - if err = json.Unmarshal(enc, expect); err != nil { - return err - } - - setPathRef(expect) - return nil - } - if err := codec(cursor, resolved); err != nil { - return nil, nil, fmt.Errorf("bad data in %q (expecting %s)", ref, readableType(resolved)) - } - return componentDoc, componentPath, nil - - default: - return nil, nil, fmt.Errorf("bad data in %q (expecting %s)", ref, readableType(resolved)) - } -} - -func readableType(x any) string { - switch x.(type) { - case *Callback: - return "callback object" - case *CallbackRef: - return "ref to callback object" - case *ExampleRef: - return "ref to example object" - case *HeaderRef: - return "ref to header object" - case *LinkRef: - return "ref to link object" - case *ParameterRef: - return "ref to parameter object" - case *PathItem: - return "pathItem object" - case *RequestBodyRef: - return "ref to requestBody object" - case *ResponseRef: - return "ref to response object" - case *SchemaRef: - return "ref to schema object" - case *SecuritySchemeRef: - return "ref to securityScheme object" - default: - panic(fmt.Sprintf("unreachable %T", x)) - } -} - -func drillIntoField(cursor any, fieldName string) (any, error) { - switch val := reflect.Indirect(reflect.ValueOf(cursor)); val.Kind() { - - case reflect.Map: - elementValue := val.MapIndex(reflect.ValueOf(fieldName)) - if !elementValue.IsValid() { - return nil, fmt.Errorf("map key %q not found", fieldName) - } - return elementValue.Interface(), nil - - case reflect.Slice: - i, err := strconv.ParseUint(fieldName, 10, 32) - if err != nil { - return nil, err - } - index := int(i) - if 0 > index || index >= val.Len() { - return nil, errors.New("slice index out of bounds") - } - return val.Index(index).Interface(), nil - - case reflect.Struct: - hasFields := false - for i := 0; i < val.NumField(); i++ { - hasFields = true - if yamlTag := val.Type().Field(i).Tag.Get("yaml"); yamlTag != "-" { - if tagName := strings.Split(yamlTag, ",")[0]; tagName != "" { - if fieldName == tagName { - return val.Field(i).Interface(), nil - } - } - } - } - - // if cursor is a "ref wrapper" struct (e.g. RequestBodyRef), - if _, ok := val.Type().FieldByName("Value"); ok { - // try digging into its Value field - return drillIntoField(val.FieldByName("Value").Interface(), fieldName) - } - if hasFields { - if ff := val.Type().Field(0); ff.PkgPath == "" && ff.Name == "Extensions" { - extensions := val.Field(0).Interface().(map[string]any) - if enc, ok := extensions[fieldName]; ok { - return enc, nil - } - } - } - return nil, fmt.Errorf("struct field %q not found", fieldName) - - default: - return nil, errors.New("not a map, slice nor struct") - } -} - -func (loader *Loader) resolveRefAndDocument(doc *T, ref string, path *url.URL) (*T, string, *url.URL, error) { - if ref != "" && ref[0] == '#' { - return doc, ref, path, nil - } - - fragment, resolvedPath, err := loader.resolveRef(ref, path) - if err != nil { - return nil, "", nil, err - } - - if doc, err = loader.loadFromURIInternal(resolvedPath); err != nil { - return nil, "", nil, fmt.Errorf("error resolving reference %q: %w", ref, err) - } - - return doc, fragment, resolvedPath, nil -} - -func (loader *Loader) resolveRef(ref string, path *url.URL) (string, *url.URL, error) { - resolvedPathRef, err := loader.resolveRefPath(ref, path) - if err != nil { - return "", nil, err - } - - fragment := "#" + resolvedPathRef.Fragment - resolvedPathRef.Fragment = "" - return fragment, resolvedPathRef, nil -} - -var ( - errMUSTCallback = errors.New("invalid callback: value MUST be an object") - errMUSTExample = errors.New("invalid example: value MUST be an object") - errMUSTHeader = errors.New("invalid header: value MUST be an object") - errMUSTLink = errors.New("invalid link: value MUST be an object") - errMUSTParameter = errors.New("invalid parameter: value MUST be an object") - errMUSTPathItem = errors.New("invalid path item: value MUST be an object") - errMUSTRequestBody = errors.New("invalid requestBody: value MUST be an object") - errMUSTResponse = errors.New("invalid response: value MUST be an object") - errMUSTSchema = errors.New("invalid schema: value MUST be an object") - errMUSTSecurityScheme = errors.New("invalid securityScheme: value MUST be an object") -) - -func (loader *Loader) resolveHeaderRef(doc *T, component *HeaderRef, documentPath *url.URL) (err error) { - if component.isEmpty() { - return errMUSTHeader - } - - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*Header) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var header Header - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &header); err != nil { - return err - } - component.Value = &header - component.setRefPath(documentPath) - } else { - var resolved HeaderRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveHeaderRef(doc, &resolved, componentPath); err != nil { - if err == errMUSTHeader { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - value := component.Value - if value == nil { - return nil - } - - if schema := value.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath, []string{}); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveParameterRef(doc *T, component *ParameterRef, documentPath *url.URL) (err error) { - if component.isEmpty() { - return errMUSTParameter - } - - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*Parameter) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var param Parameter - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, ¶m); err != nil { - return err - } - component.Value = ¶m - component.setRefPath(documentPath) - } else { - var resolved ParameterRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveParameterRef(doc, &resolved, componentPath); err != nil { - if err == errMUSTParameter { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - value := component.Value - if value == nil { - return nil - } - - if value.Content != nil && value.Schema != nil { - return errors.New("cannot contain both schema and content in a parameter") - } - for _, name := range componentNames(value.Content) { - contentType := value.Content[name] - if schema := contentType.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath, []string{}); err != nil { - return err - } - } - } - if schema := value.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath, []string{}); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveRequestBodyRef(doc *T, component *RequestBodyRef, documentPath *url.URL) (err error) { - if component.isEmpty() { - return errMUSTRequestBody - } - - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*RequestBody) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var requestBody RequestBody - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &requestBody); err != nil { - return err - } - component.Value = &requestBody - component.setRefPath(documentPath) - } else { - var resolved RequestBodyRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err = loader.resolveRequestBodyRef(doc, &resolved, componentPath); err != nil { - if err == errMUSTRequestBody { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - value := component.Value - if value == nil { - return nil - } - - for _, name := range componentNames(value.Content) { - contentType := value.Content[name] - if contentType == nil { - continue - } - for _, name := range componentNames(contentType.Examples) { - example := contentType.Examples[name] - if err := loader.resolveExampleRef(doc, example, documentPath); err != nil { - return err - } - contentType.Examples[name] = example - } - if schema := contentType.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath, []string{}); err != nil { - return err - } - } - } - return nil -} - -func (loader *Loader) resolveResponseRef(doc *T, component *ResponseRef, documentPath *url.URL) (err error) { - if component.isEmpty() { - return errMUSTResponse - } - - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*Response) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var resp Response - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &resp); err != nil { - return err - } - component.Value = &resp - component.setRefPath(documentPath) - } else { - var resolved ResponseRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveResponseRef(doc, &resolved, componentPath); err != nil { - if err == errMUSTResponse { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - value := component.Value - if value == nil { - return nil - } - - for _, name := range componentNames(value.Headers) { - header := value.Headers[name] - if err := loader.resolveHeaderRef(doc, header, documentPath); err != nil { - return err - } - } - for _, name := range componentNames(value.Content) { - contentType := value.Content[name] - if contentType == nil { - continue - } - for _, name := range componentNames(contentType.Examples) { - example := contentType.Examples[name] - if err := loader.resolveExampleRef(doc, example, documentPath); err != nil { - return err - } - contentType.Examples[name] = example - } - if schema := contentType.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath, []string{}); err != nil { - return err - } - contentType.Schema = schema - } - } - for _, name := range componentNames(value.Links) { - link := value.Links[name] - if err := loader.resolveLinkRef(doc, link, documentPath); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveSchemaRef(doc *T, component *SchemaRef, documentPath *url.URL, visited []string) (err error) { - if component.isEmpty() { - return errMUSTSchema - } - - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*Schema) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var schema Schema - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &schema); err != nil { - return err - } - component.Value = &schema - component.setRefPath(documentPath) - } else { - var resolved SchemaRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveSchemaRef(doc, &resolved, componentPath, visited); err != nil { - if err == errMUSTSchema { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - value := component.Value - if value == nil { - return nil - } - - // ResolveRefs referred schemas - if v := value.Items; v != nil { - if err := loader.resolveSchemaRef(doc, v, documentPath, visited); err != nil { - return err - } - } - for _, name := range componentNames(value.Properties) { - v := value.Properties[name] - if err := loader.resolveSchemaRef(doc, v, documentPath, visited); err != nil { - return err - } - } - if v := value.AdditionalProperties.Schema; v != nil { - if err := loader.resolveSchemaRef(doc, v, documentPath, visited); err != nil { - return err - } - } - if v := value.Not; v != nil { - if err := loader.resolveSchemaRef(doc, v, documentPath, visited); err != nil { - return err - } - } - for _, v := range value.AllOf { - if err := loader.resolveSchemaRef(doc, v, documentPath, visited); err != nil { - return err - } - } - for _, v := range value.AnyOf { - if err := loader.resolveSchemaRef(doc, v, documentPath, visited); err != nil { - return err - } - } - for _, v := range value.OneOf { - if err := loader.resolveSchemaRef(doc, v, documentPath, visited); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveSecuritySchemeRef(doc *T, component *SecuritySchemeRef, documentPath *url.URL) (err error) { - if component.isEmpty() { - return errMUSTSecurityScheme - } - - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*SecurityScheme) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var scheme SecurityScheme - if _, err = loader.loadSingleElementFromURI(ref, documentPath, &scheme); err != nil { - return err - } - component.Value = &scheme - component.setRefPath(documentPath) - } else { - var resolved SecuritySchemeRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveSecuritySchemeRef(doc, &resolved, componentPath); err != nil { - if err == errMUSTSecurityScheme { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - return nil -} - -func (loader *Loader) resolveExampleRef(doc *T, component *ExampleRef, documentPath *url.URL) (err error) { - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*Example) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var example Example - if _, err = loader.loadSingleElementFromURI(ref, documentPath, &example); err != nil { - return err - } - component.Value = &example - component.setRefPath(documentPath) - } else { - var resolved ExampleRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveExampleRef(doc, &resolved, componentPath); err != nil { - if err == errMUSTExample { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - return nil -} - -func (loader *Loader) resolveCallbackRef(doc *T, component *CallbackRef, documentPath *url.URL) (err error) { - if component.isEmpty() { - return errMUSTCallback - } - - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*Callback) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var resolved Callback - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &resolved); err != nil { - return err - } - component.Value = &resolved - component.setRefPath(documentPath) - } else { - var resolved CallbackRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err = loader.resolveCallbackRef(doc, &resolved, componentPath); err != nil { - if err == errMUSTCallback { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - value := component.Value - if value == nil { - return nil - } - - pathItems := value.Map() - for _, name := range componentNames(pathItems) { - pathItem := pathItems[name] - if err = loader.resolvePathItemRef(doc, pathItem, documentPath); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveLinkRef(doc *T, component *LinkRef, documentPath *url.URL) (err error) { - if component.isEmpty() { - return errMUSTLink - } - - if ref := component.Ref; ref != "" { - if component.Value != nil { - return nil - } - if !loader.shouldVisitRef(ref, func(value any) { - component.Value = value.(*Link) - refPath, _ := loader.resolveRefPath(ref, documentPath) - component.setRefPath(refPath) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var link Link - if _, err = loader.loadSingleElementFromURI(ref, documentPath, &link); err != nil { - return err - } - component.Value = &link - component.setRefPath(documentPath) - } else { - var resolved LinkRef - doc, componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveLinkRef(doc, &resolved, componentPath); err != nil { - if err == errMUSTLink { - return nil - } - return err - } - component.Value = resolved.Value - component.setRefPath(resolved.RefPath()) - } - defer loader.unvisitRef(ref, component.Value) - } - return nil -} - -func (loader *Loader) resolvePathItemRef(doc *T, pathItem *PathItem, documentPath *url.URL) (err error) { - if pathItem == nil { - err = errMUSTPathItem - return - } - - if ref := pathItem.Ref; ref != "" { - if !pathItem.isEmpty() { - return - } - if !loader.shouldVisitRef(ref, func(value any) { - *pathItem = *value.(*PathItem) - }) { - return nil - } - loader.visitRef(ref) - if isSingleRefElement(ref) { - var p PathItem - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &p); err != nil { - return - } - *pathItem = p - } else { - var resolved PathItem - if doc, documentPath, err = loader.resolveComponent(doc, ref, documentPath, &resolved); err != nil { - if err == errMUSTPathItem { - return nil - } - return - } - *pathItem = resolved - } - pathItem.Ref = ref - defer loader.unvisitRef(ref, pathItem) - } - - for _, parameter := range pathItem.Parameters { - if err = loader.resolveParameterRef(doc, parameter, documentPath); err != nil { - return - } - } - operations := pathItem.Operations() - for _, name := range componentNames(operations) { - operation := operations[name] - for _, parameter := range operation.Parameters { - if err = loader.resolveParameterRef(doc, parameter, documentPath); err != nil { - return - } - } - if requestBody := operation.RequestBody; requestBody != nil { - if err = loader.resolveRequestBodyRef(doc, requestBody, documentPath); err != nil { - return - } - } - responses := operation.Responses.Map() - for _, name := range componentNames(responses) { - response := responses[name] - if err = loader.resolveResponseRef(doc, response, documentPath); err != nil { - return - } - } - for _, name := range componentNames(operation.Callbacks) { - callback := operation.Callbacks[name] - if err = loader.resolveCallbackRef(doc, callback, documentPath); err != nil { - return - } - } - } - return -} - -func unescapeRefString(ref string) string { - return strings.Replace(strings.Replace(ref, "~1", "/", -1), "~0", "~", -1) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/loader_uri_reader.go b/vendor/github.com/getkin/kin-openapi/openapi3/loader_uri_reader.go deleted file mode 100644 index b023dfb29..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/loader_uri_reader.go +++ /dev/null @@ -1,116 +0,0 @@ -package openapi3 - -import ( - "errors" - "fmt" - "io" - "net/http" - "net/url" - "os" - "path/filepath" - "sync" -) - -// ReadFromURIFunc defines a function which reads the contents of a resource -// located at a URI. -type ReadFromURIFunc func(loader *Loader, url *url.URL) ([]byte, error) - -var uriMu = &sync.RWMutex{} - -// ErrURINotSupported indicates the ReadFromURIFunc does not know how to handle a -// given URI. -var ErrURINotSupported = errors.New("unsupported URI") - -// ReadFromURIs returns a ReadFromURIFunc which tries to read a URI using the -// given reader functions, in the same order. If a reader function does not -// support the URI and returns ErrURINotSupported, the next function is checked -// until a match is found, or the URI is not supported by any. -func ReadFromURIs(readers ...ReadFromURIFunc) ReadFromURIFunc { - return func(loader *Loader, url *url.URL) ([]byte, error) { - for i := range readers { - buf, err := readers[i](loader, url) - if err == ErrURINotSupported { - continue - } else if err != nil { - return nil, err - } - return buf, nil - } - return nil, ErrURINotSupported - } -} - -// DefaultReadFromURI returns a caching ReadFromURIFunc which can read remote -// HTTP URIs and local file URIs. -var DefaultReadFromURI = URIMapCache(ReadFromURIs(ReadFromHTTP(http.DefaultClient), ReadFromFile)) - -// ReadFromHTTP returns a ReadFromURIFunc which uses the given http.Client to -// read the contents from a remote HTTP URI. This client may be customized to -// implement timeouts, RFC 7234 caching, etc. -func ReadFromHTTP(cl *http.Client) ReadFromURIFunc { - return func(loader *Loader, location *url.URL) ([]byte, error) { - if location.Scheme == "" || location.Host == "" { - return nil, ErrURINotSupported - } - req, err := http.NewRequest("GET", location.String(), nil) - if err != nil { - return nil, err - } - resp, err := cl.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - if resp.StatusCode > 399 { - return nil, fmt.Errorf("error loading %q: request returned status code %d", location.String(), resp.StatusCode) - } - return io.ReadAll(resp.Body) - } -} - -func is_file(location *url.URL) bool { - return location.Path != "" && - location.Host == "" && - (location.Scheme == "" || location.Scheme == "file") -} - -// ReadFromFile is a ReadFromURIFunc which reads local file URIs. -func ReadFromFile(loader *Loader, location *url.URL) ([]byte, error) { - if !is_file(location) { - return nil, ErrURINotSupported - } - return os.ReadFile(filepath.FromSlash(location.Path)) -} - -// URIMapCache returns a ReadFromURIFunc that caches the contents read from URI -// locations in a simple map. This cache implementation is suitable for -// short-lived processes such as command-line tools which process OpenAPI -// documents. -func URIMapCache(reader ReadFromURIFunc) ReadFromURIFunc { - cache := map[string][]byte{} - return func(loader *Loader, location *url.URL) (buf []byte, err error) { - if location.Scheme == "" || location.Scheme == "file" { - if !filepath.IsAbs(location.Path) { - // Do not cache relative file paths; this can cause trouble if - // the current working directory changes when processing - // multiple top-level documents. - return reader(loader, location) - } - } - uri := location.String() - var ok bool - uriMu.RLock() - if buf, ok = cache[uri]; ok { - uriMu.RUnlock() - return - } - uriMu.RUnlock() - if buf, err = reader(loader, location); err != nil { - return - } - uriMu.Lock() - defer uriMu.Unlock() - cache[uri] = buf - return - } -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/maplike.go b/vendor/github.com/getkin/kin-openapi/openapi3/maplike.go deleted file mode 100644 index 7b8045c67..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/maplike.go +++ /dev/null @@ -1,402 +0,0 @@ -package openapi3 - -import ( - "encoding/json" - "sort" - "strings" - - "github.com/go-openapi/jsonpointer" -) - -// NewResponsesWithCapacity builds a responses object of the given capacity. -func NewResponsesWithCapacity(cap int) *Responses { - if cap == 0 { - return &Responses{m: make(map[string]*ResponseRef)} - } - return &Responses{m: make(map[string]*ResponseRef, cap)} -} - -// Value returns the responses for key or nil -func (responses *Responses) Value(key string) *ResponseRef { - if responses.Len() == 0 { - return nil - } - return responses.m[key] -} - -// Set adds or replaces key 'key' of 'responses' with 'value'. -// Note: 'responses' MUST be non-nil -func (responses *Responses) Set(key string, value *ResponseRef) { - if responses.m == nil { - responses.m = make(map[string]*ResponseRef) - } - responses.m[key] = value -} - -// Len returns the amount of keys in responses excluding responses.Extensions. -func (responses *Responses) Len() int { - if responses == nil || responses.m == nil { - return 0 - } - return len(responses.m) -} - -// Delete removes the entry associated with key 'key' from 'responses'. -func (responses *Responses) Delete(key string) { - if responses != nil && responses.m != nil { - delete(responses.m, key) - } -} - -// Map returns responses as a 'map'. -// Note: iteration on Go maps is not ordered. -func (responses *Responses) Map() (m map[string]*ResponseRef) { - if responses == nil || len(responses.m) == 0 { - return make(map[string]*ResponseRef) - } - m = make(map[string]*ResponseRef, len(responses.m)) - for k, v := range responses.m { - m[k] = v - } - return -} - -var _ jsonpointer.JSONPointable = (*Responses)(nil) - -// JSONLookup implements https://github.com/go-openapi/jsonpointer#JSONPointable -func (responses Responses) JSONLookup(token string) (any, error) { - if v := responses.Value(token); v == nil { - vv, _, err := jsonpointer.GetForToken(responses.Extensions, token) - return vv, err - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - var vv *Response = v.Value - return vv, nil - } -} - -// MarshalYAML returns the YAML encoding of Responses. -func (responses *Responses) MarshalYAML() (any, error) { - if responses == nil { - return nil, nil - } - m := make(map[string]any, responses.Len()+len(responses.Extensions)) - for k, v := range responses.Extensions { - m[k] = v - } - for k, v := range responses.Map() { - m[k] = v - } - return m, nil -} - -// MarshalJSON returns the JSON encoding of Responses. -func (responses *Responses) MarshalJSON() ([]byte, error) { - responsesYaml, err := responses.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(responsesYaml) -} - -// UnmarshalJSON sets Responses to a copy of data. -func (responses *Responses) UnmarshalJSON(data []byte) (err error) { - var m map[string]any - if err = json.Unmarshal(data, &m); err != nil { - return - } - - ks := make([]string, 0, len(m)) - for k := range m { - ks = append(ks, k) - } - sort.Strings(ks) - - x := Responses{ - Extensions: make(map[string]any), - m: make(map[string]*ResponseRef, len(m)), - } - - for _, k := range ks { - v := m[k] - if strings.HasPrefix(k, "x-") { - x.Extensions[k] = v - continue - } - - var data []byte - if data, err = json.Marshal(v); err != nil { - return - } - var vv ResponseRef - if err = vv.UnmarshalJSON(data); err != nil { - return - } - x.m[k] = &vv - } - *responses = x - return -} - -// NewCallbackWithCapacity builds a callback object of the given capacity. -func NewCallbackWithCapacity(cap int) *Callback { - if cap == 0 { - return &Callback{m: make(map[string]*PathItem)} - } - return &Callback{m: make(map[string]*PathItem, cap)} -} - -// Value returns the callback for key or nil -func (callback *Callback) Value(key string) *PathItem { - if callback.Len() == 0 { - return nil - } - return callback.m[key] -} - -// Set adds or replaces key 'key' of 'callback' with 'value'. -// Note: 'callback' MUST be non-nil -func (callback *Callback) Set(key string, value *PathItem) { - if callback.m == nil { - callback.m = make(map[string]*PathItem) - } - callback.m[key] = value -} - -// Len returns the amount of keys in callback excluding callback.Extensions. -func (callback *Callback) Len() int { - if callback == nil || callback.m == nil { - return 0 - } - return len(callback.m) -} - -// Delete removes the entry associated with key 'key' from 'callback'. -func (callback *Callback) Delete(key string) { - if callback != nil && callback.m != nil { - delete(callback.m, key) - } -} - -// Map returns callback as a 'map'. -// Note: iteration on Go maps is not ordered. -func (callback *Callback) Map() (m map[string]*PathItem) { - if callback == nil || len(callback.m) == 0 { - return make(map[string]*PathItem) - } - m = make(map[string]*PathItem, len(callback.m)) - for k, v := range callback.m { - m[k] = v - } - return -} - -var _ jsonpointer.JSONPointable = (*Callback)(nil) - -// JSONLookup implements https://github.com/go-openapi/jsonpointer#JSONPointable -func (callback Callback) JSONLookup(token string) (any, error) { - if v := callback.Value(token); v == nil { - vv, _, err := jsonpointer.GetForToken(callback.Extensions, token) - return vv, err - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - var vv *PathItem = v - return vv, nil - } -} - -// MarshalYAML returns the YAML encoding of Callback. -func (callback *Callback) MarshalYAML() (any, error) { - if callback == nil { - return nil, nil - } - m := make(map[string]any, callback.Len()+len(callback.Extensions)) - for k, v := range callback.Extensions { - m[k] = v - } - for k, v := range callback.Map() { - m[k] = v - } - return m, nil -} - -// MarshalJSON returns the JSON encoding of Callback. -func (callback *Callback) MarshalJSON() ([]byte, error) { - callbackYaml, err := callback.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(callbackYaml) -} - -// UnmarshalJSON sets Callback to a copy of data. -func (callback *Callback) UnmarshalJSON(data []byte) (err error) { - var m map[string]any - if err = json.Unmarshal(data, &m); err != nil { - return - } - - ks := make([]string, 0, len(m)) - for k := range m { - ks = append(ks, k) - } - sort.Strings(ks) - - x := Callback{ - Extensions: make(map[string]any), - m: make(map[string]*PathItem, len(m)), - } - - for _, k := range ks { - v := m[k] - if strings.HasPrefix(k, "x-") { - x.Extensions[k] = v - continue - } - - var data []byte - if data, err = json.Marshal(v); err != nil { - return - } - var vv PathItem - if err = vv.UnmarshalJSON(data); err != nil { - return - } - x.m[k] = &vv - } - *callback = x - return -} - -// NewPathsWithCapacity builds a paths object of the given capacity. -func NewPathsWithCapacity(cap int) *Paths { - if cap == 0 { - return &Paths{m: make(map[string]*PathItem)} - } - return &Paths{m: make(map[string]*PathItem, cap)} -} - -// Value returns the paths for key or nil -func (paths *Paths) Value(key string) *PathItem { - if paths.Len() == 0 { - return nil - } - return paths.m[key] -} - -// Set adds or replaces key 'key' of 'paths' with 'value'. -// Note: 'paths' MUST be non-nil -func (paths *Paths) Set(key string, value *PathItem) { - if paths.m == nil { - paths.m = make(map[string]*PathItem) - } - paths.m[key] = value -} - -// Len returns the amount of keys in paths excluding paths.Extensions. -func (paths *Paths) Len() int { - if paths == nil || paths.m == nil { - return 0 - } - return len(paths.m) -} - -// Delete removes the entry associated with key 'key' from 'paths'. -func (paths *Paths) Delete(key string) { - if paths != nil && paths.m != nil { - delete(paths.m, key) - } -} - -// Map returns paths as a 'map'. -// Note: iteration on Go maps is not ordered. -func (paths *Paths) Map() (m map[string]*PathItem) { - if paths == nil || len(paths.m) == 0 { - return make(map[string]*PathItem) - } - m = make(map[string]*PathItem, len(paths.m)) - for k, v := range paths.m { - m[k] = v - } - return -} - -var _ jsonpointer.JSONPointable = (*Paths)(nil) - -// JSONLookup implements https://github.com/go-openapi/jsonpointer#JSONPointable -func (paths Paths) JSONLookup(token string) (any, error) { - if v := paths.Value(token); v == nil { - vv, _, err := jsonpointer.GetForToken(paths.Extensions, token) - return vv, err - } else if ref := v.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } else { - var vv *PathItem = v - return vv, nil - } -} - -// MarshalYAML returns the YAML encoding of Paths. -func (paths *Paths) MarshalYAML() (any, error) { - if paths == nil { - return nil, nil - } - m := make(map[string]any, paths.Len()+len(paths.Extensions)) - for k, v := range paths.Extensions { - m[k] = v - } - for k, v := range paths.Map() { - m[k] = v - } - return m, nil -} - -// MarshalJSON returns the JSON encoding of Paths. -func (paths *Paths) MarshalJSON() ([]byte, error) { - pathsYaml, err := paths.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(pathsYaml) -} - -// UnmarshalJSON sets Paths to a copy of data. -func (paths *Paths) UnmarshalJSON(data []byte) (err error) { - var m map[string]any - if err = json.Unmarshal(data, &m); err != nil { - return - } - - ks := make([]string, 0, len(m)) - for k := range m { - ks = append(ks, k) - } - sort.Strings(ks) - - x := Paths{ - Extensions: make(map[string]any), - m: make(map[string]*PathItem, len(m)), - } - - for _, k := range ks { - v := m[k] - if strings.HasPrefix(k, "x-") { - x.Extensions[k] = v - continue - } - - var data []byte - if data, err = json.Marshal(v); err != nil { - return - } - var vv PathItem - if err = vv.UnmarshalJSON(data); err != nil { - return - } - x.m[k] = &vv - } - *paths = x - return -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/marsh.go b/vendor/github.com/getkin/kin-openapi/openapi3/marsh.go deleted file mode 100644 index daa937551..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/marsh.go +++ /dev/null @@ -1,34 +0,0 @@ -package openapi3 - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/invopop/yaml" -) - -func unmarshalError(jsonUnmarshalErr error) error { - if before, after, found := strings.Cut(jsonUnmarshalErr.Error(), "Bis"); found && before != "" && after != "" { - before = strings.ReplaceAll(before, " Go struct ", " ") - return fmt.Errorf("%s%s", before, strings.ReplaceAll(after, "Bis", "")) - } - return jsonUnmarshalErr -} - -func unmarshal(data []byte, v any) error { - var jsonErr, yamlErr error - - // See https://github.com/getkin/kin-openapi/issues/680 - if jsonErr = json.Unmarshal(data, v); jsonErr == nil { - return nil - } - - // UnmarshalStrict(data, v) TODO: investigate how ymlv3 handles duplicate map keys - if yamlErr = yaml.Unmarshal(data, v); yamlErr == nil { - return nil - } - - // If both unmarshaling attempts fail, return a new error that includes both errors - return fmt.Errorf("failed to unmarshal data: json error: %v, yaml error: %v", jsonErr, yamlErr) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/media_type.go b/vendor/github.com/getkin/kin-openapi/openapi3/media_type.go deleted file mode 100644 index d4466bcf5..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/media_type.go +++ /dev/null @@ -1,179 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "sort" - - "github.com/go-openapi/jsonpointer" -) - -// MediaType is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#media-type-object -type MediaType struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Schema *SchemaRef `json:"schema,omitempty" yaml:"schema,omitempty"` - Example any `json:"example,omitempty" yaml:"example,omitempty"` - Examples Examples `json:"examples,omitempty" yaml:"examples,omitempty"` - Encoding map[string]*Encoding `json:"encoding,omitempty" yaml:"encoding,omitempty"` -} - -var _ jsonpointer.JSONPointable = (*MediaType)(nil) - -func NewMediaType() *MediaType { - return &MediaType{} -} - -func (mediaType *MediaType) WithSchema(schema *Schema) *MediaType { - if schema == nil { - mediaType.Schema = nil - } else { - mediaType.Schema = &SchemaRef{Value: schema} - } - return mediaType -} - -func (mediaType *MediaType) WithSchemaRef(schema *SchemaRef) *MediaType { - mediaType.Schema = schema - return mediaType -} - -func (mediaType *MediaType) WithExample(name string, value any) *MediaType { - example := mediaType.Examples - if example == nil { - example = make(map[string]*ExampleRef) - mediaType.Examples = example - } - example[name] = &ExampleRef{ - Value: NewExample(value), - } - return mediaType -} - -func (mediaType *MediaType) WithEncoding(name string, enc *Encoding) *MediaType { - encoding := mediaType.Encoding - if encoding == nil { - encoding = make(map[string]*Encoding) - mediaType.Encoding = encoding - } - encoding[name] = enc - return mediaType -} - -// MarshalJSON returns the JSON encoding of MediaType. -func (mediaType MediaType) MarshalJSON() ([]byte, error) { - x, err := mediaType.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of MediaType. -func (mediaType MediaType) MarshalYAML() (any, error) { - m := make(map[string]any, 4+len(mediaType.Extensions)) - for k, v := range mediaType.Extensions { - m[k] = v - } - if x := mediaType.Schema; x != nil { - m["schema"] = x - } - if x := mediaType.Example; x != nil { - m["example"] = x - } - if x := mediaType.Examples; len(x) != 0 { - m["examples"] = x - } - if x := mediaType.Encoding; len(x) != 0 { - m["encoding"] = x - } - return m, nil -} - -// UnmarshalJSON sets MediaType to a copy of data. -func (mediaType *MediaType) UnmarshalJSON(data []byte) error { - type MediaTypeBis MediaType - var x MediaTypeBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "schema") - delete(x.Extensions, "example") - delete(x.Extensions, "examples") - delete(x.Extensions, "encoding") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *mediaType = MediaType(x) - return nil -} - -// Validate returns an error if MediaType does not comply with the OpenAPI spec. -func (mediaType *MediaType) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if mediaType == nil { - return nil - } - if schema := mediaType.Schema; schema != nil { - if err := schema.Validate(ctx); err != nil { - return err - } - - if mediaType.Example != nil && mediaType.Examples != nil { - return errors.New("example and examples are mutually exclusive") - } - - if vo := getValidationOptions(ctx); !vo.examplesValidationDisabled { - if example := mediaType.Example; example != nil { - if err := validateExampleValue(ctx, example, schema.Value); err != nil { - return fmt.Errorf("invalid example: %w", err) - } - } - - if examples := mediaType.Examples; examples != nil { - names := make([]string, 0, len(examples)) - for name := range examples { - names = append(names, name) - } - sort.Strings(names) - for _, k := range names { - v := examples[k] - if err := v.Validate(ctx); err != nil { - return fmt.Errorf("example %s: %w", k, err) - } - if err := validateExampleValue(ctx, v.Value.Value, schema.Value); err != nil { - return fmt.Errorf("example %s: %w", k, err) - } - } - } - } - } - - return validateExtensions(ctx, mediaType.Extensions) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (mediaType MediaType) JSONLookup(token string) (any, error) { - switch token { - case "schema": - if mediaType.Schema != nil { - if mediaType.Schema.Ref != "" { - return &Ref{Ref: mediaType.Schema.Ref}, nil - } - return mediaType.Schema.Value, nil - } - case "example": - return mediaType.Example, nil - case "examples": - return mediaType.Examples, nil - case "encoding": - return mediaType.Encoding, nil - } - v, _, err := jsonpointer.GetForToken(mediaType.Extensions, token) - return v, err -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/openapi3.go b/vendor/github.com/getkin/kin-openapi/openapi3/openapi3.go deleted file mode 100644 index ef1592e8c..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/openapi3.go +++ /dev/null @@ -1,205 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/url" - - "github.com/go-openapi/jsonpointer" -) - -// T is the root of an OpenAPI v3 document -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#openapi-object -type T struct { - Extensions map[string]any `json:"-" yaml:"-"` - - OpenAPI string `json:"openapi" yaml:"openapi"` // Required - Components *Components `json:"components,omitempty" yaml:"components,omitempty"` - Info *Info `json:"info" yaml:"info"` // Required - Paths *Paths `json:"paths" yaml:"paths"` // Required - Security SecurityRequirements `json:"security,omitempty" yaml:"security,omitempty"` - Servers Servers `json:"servers,omitempty" yaml:"servers,omitempty"` - Tags Tags `json:"tags,omitempty" yaml:"tags,omitempty"` - ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"` - - visited visitedComponent - url *url.URL -} - -var _ jsonpointer.JSONPointable = (*T)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (doc *T) JSONLookup(token string) (any, error) { - switch token { - case "openapi": - return doc.OpenAPI, nil - case "components": - return doc.Components, nil - case "info": - return doc.Info, nil - case "paths": - return doc.Paths, nil - case "security": - return doc.Security, nil - case "servers": - return doc.Servers, nil - case "tags": - return doc.Tags, nil - case "externalDocs": - return doc.ExternalDocs, nil - } - - v, _, err := jsonpointer.GetForToken(doc.Extensions, token) - return v, err -} - -// MarshalJSON returns the JSON encoding of T. -func (doc *T) MarshalJSON() ([]byte, error) { - x, err := doc.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of T. -func (doc *T) MarshalYAML() (any, error) { - if doc == nil { - return nil, nil - } - m := make(map[string]any, 4+len(doc.Extensions)) - for k, v := range doc.Extensions { - m[k] = v - } - m["openapi"] = doc.OpenAPI - if x := doc.Components; x != nil { - m["components"] = x - } - m["info"] = doc.Info - m["paths"] = doc.Paths - if x := doc.Security; len(x) != 0 { - m["security"] = x - } - if x := doc.Servers; len(x) != 0 { - m["servers"] = x - } - if x := doc.Tags; len(x) != 0 { - m["tags"] = x - } - if x := doc.ExternalDocs; x != nil { - m["externalDocs"] = x - } - return m, nil -} - -// UnmarshalJSON sets T to a copy of data. -func (doc *T) UnmarshalJSON(data []byte) error { - type TBis T - var x TBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "openapi") - delete(x.Extensions, "components") - delete(x.Extensions, "info") - delete(x.Extensions, "paths") - delete(x.Extensions, "security") - delete(x.Extensions, "servers") - delete(x.Extensions, "tags") - delete(x.Extensions, "externalDocs") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *doc = T(x) - return nil -} - -func (doc *T) AddOperation(path string, method string, operation *Operation) { - if doc.Paths == nil { - doc.Paths = NewPaths() - } - pathItem := doc.Paths.Value(path) - if pathItem == nil { - pathItem = &PathItem{} - doc.Paths.Set(path, pathItem) - } - pathItem.SetOperation(method, operation) -} - -func (doc *T) AddServer(server *Server) { - doc.Servers = append(doc.Servers, server) -} - -func (doc *T) AddServers(servers ...*Server) { - doc.Servers = append(doc.Servers, servers...) -} - -// Validate returns an error if T does not comply with the OpenAPI spec. -// Validations Options can be provided to modify the validation behavior. -func (doc *T) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if doc.OpenAPI == "" { - return errors.New("value of openapi must be a non-empty string") - } - - var wrap func(error) error - - wrap = func(e error) error { return fmt.Errorf("invalid components: %w", e) } - if v := doc.Components; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - - wrap = func(e error) error { return fmt.Errorf("invalid info: %w", e) } - if v := doc.Info; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } else { - return wrap(errors.New("must be an object")) - } - - wrap = func(e error) error { return fmt.Errorf("invalid paths: %w", e) } - if v := doc.Paths; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } else { - return wrap(errors.New("must be an object")) - } - - wrap = func(e error) error { return fmt.Errorf("invalid security: %w", e) } - if v := doc.Security; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - - wrap = func(e error) error { return fmt.Errorf("invalid servers: %w", e) } - if v := doc.Servers; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - - wrap = func(e error) error { return fmt.Errorf("invalid tags: %w", e) } - if v := doc.Tags; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - - wrap = func(e error) error { return fmt.Errorf("invalid external docs: %w", e) } - if v := doc.ExternalDocs; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - - return validateExtensions(ctx, doc.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/operation.go b/vendor/github.com/getkin/kin-openapi/openapi3/operation.go deleted file mode 100644 index 40abf73c0..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/operation.go +++ /dev/null @@ -1,222 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strconv" - - "github.com/go-openapi/jsonpointer" -) - -// Operation represents "operation" specified by" OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object -type Operation struct { - Extensions map[string]any `json:"-" yaml:"-"` - - // Optional tags for documentation. - Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` - - // Optional short summary. - Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` - - // Optional description. Should use CommonMark syntax. - Description string `json:"description,omitempty" yaml:"description,omitempty"` - - // Optional operation ID. - OperationID string `json:"operationId,omitempty" yaml:"operationId,omitempty"` - - // Optional parameters. - Parameters Parameters `json:"parameters,omitempty" yaml:"parameters,omitempty"` - - // Optional body parameter. - RequestBody *RequestBodyRef `json:"requestBody,omitempty" yaml:"requestBody,omitempty"` - - // Responses. - Responses *Responses `json:"responses" yaml:"responses"` // Required - - // Optional callbacks - Callbacks Callbacks `json:"callbacks,omitempty" yaml:"callbacks,omitempty"` - - Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` - - // Optional security requirements that overrides top-level security. - Security *SecurityRequirements `json:"security,omitempty" yaml:"security,omitempty"` - - // Optional servers that overrides top-level servers. - Servers *Servers `json:"servers,omitempty" yaml:"servers,omitempty"` - - ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"` -} - -var _ jsonpointer.JSONPointable = (*Operation)(nil) - -func NewOperation() *Operation { - return &Operation{} -} - -// MarshalJSON returns the JSON encoding of Operation. -func (operation Operation) MarshalJSON() ([]byte, error) { - x, err := operation.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Operation. -func (operation Operation) MarshalYAML() (any, error) { - m := make(map[string]any, 12+len(operation.Extensions)) - for k, v := range operation.Extensions { - m[k] = v - } - if x := operation.Tags; len(x) != 0 { - m["tags"] = x - } - if x := operation.Summary; x != "" { - m["summary"] = x - } - if x := operation.Description; x != "" { - m["description"] = x - } - if x := operation.OperationID; x != "" { - m["operationId"] = x - } - if x := operation.Parameters; len(x) != 0 { - m["parameters"] = x - } - if x := operation.RequestBody; x != nil { - m["requestBody"] = x - } - m["responses"] = operation.Responses - if x := operation.Callbacks; len(x) != 0 { - m["callbacks"] = x - } - if x := operation.Deprecated; x { - m["deprecated"] = x - } - if x := operation.Security; x != nil { - m["security"] = x - } - if x := operation.Servers; x != nil { - m["servers"] = x - } - if x := operation.ExternalDocs; x != nil { - m["externalDocs"] = x - } - return m, nil -} - -// UnmarshalJSON sets Operation to a copy of data. -func (operation *Operation) UnmarshalJSON(data []byte) error { - type OperationBis Operation - var x OperationBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "tags") - delete(x.Extensions, "summary") - delete(x.Extensions, "description") - delete(x.Extensions, "operationId") - delete(x.Extensions, "parameters") - delete(x.Extensions, "requestBody") - delete(x.Extensions, "responses") - delete(x.Extensions, "callbacks") - delete(x.Extensions, "deprecated") - delete(x.Extensions, "security") - delete(x.Extensions, "servers") - delete(x.Extensions, "externalDocs") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *operation = Operation(x) - return nil -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (operation Operation) JSONLookup(token string) (any, error) { - switch token { - case "requestBody": - if operation.RequestBody != nil { - if operation.RequestBody.Ref != "" { - return &Ref{Ref: operation.RequestBody.Ref}, nil - } - return operation.RequestBody.Value, nil - } - case "tags": - return operation.Tags, nil - case "summary": - return operation.Summary, nil - case "description": - return operation.Description, nil - case "operationID": - return operation.OperationID, nil - case "parameters": - return operation.Parameters, nil - case "responses": - return operation.Responses, nil - case "callbacks": - return operation.Callbacks, nil - case "deprecated": - return operation.Deprecated, nil - case "security": - return operation.Security, nil - case "servers": - return operation.Servers, nil - case "externalDocs": - return operation.ExternalDocs, nil - } - - v, _, err := jsonpointer.GetForToken(operation.Extensions, token) - return v, err -} - -func (operation *Operation) AddParameter(p *Parameter) { - operation.Parameters = append(operation.Parameters, &ParameterRef{Value: p}) -} - -func (operation *Operation) AddResponse(status int, response *Response) { - code := "default" - if 0 < status && status < 1000 { - code = strconv.FormatInt(int64(status), 10) - } - if operation.Responses == nil { - operation.Responses = NewResponses() - } - operation.Responses.Set(code, &ResponseRef{Value: response}) -} - -// Validate returns an error if Operation does not comply with the OpenAPI spec. -func (operation *Operation) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if v := operation.Parameters; v != nil { - if err := v.Validate(ctx); err != nil { - return err - } - } - - if v := operation.RequestBody; v != nil { - if err := v.Validate(ctx); err != nil { - return err - } - } - - if v := operation.Responses; v != nil { - if err := v.Validate(ctx); err != nil { - return err - } - } else { - return errors.New("value of responses must be an object") - } - - if v := operation.ExternalDocs; v != nil { - if err := v.Validate(ctx); err != nil { - return fmt.Errorf("invalid external docs: %w", err) - } - } - - return validateExtensions(ctx, operation.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/parameter.go b/vendor/github.com/getkin/kin-openapi/openapi3/parameter.go deleted file mode 100644 index 34fe29118..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/parameter.go +++ /dev/null @@ -1,416 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "sort" - "strconv" - - "github.com/go-openapi/jsonpointer" -) - -// Parameters is specified by OpenAPI/Swagger 3.0 standard. -type Parameters []*ParameterRef - -var _ jsonpointer.JSONPointable = (*Parameters)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (p Parameters) JSONLookup(token string) (any, error) { - index, err := strconv.Atoi(token) - if err != nil { - return nil, err - } - if index < 0 || index >= len(p) { - return nil, fmt.Errorf("index %d out of bounds of array of length %d", index, len(p)) - } - - ref := p[index] - if ref != nil && ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -func NewParameters() Parameters { - return make(Parameters, 0, 4) -} - -func (parameters Parameters) GetByInAndName(in string, name string) *Parameter { - for _, item := range parameters { - if v := item.Value; v != nil { - if v.Name == name && v.In == in { - return v - } - } - } - return nil -} - -// Validate returns an error if Parameters does not comply with the OpenAPI spec. -func (parameters Parameters) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - dupes := make(map[string]struct{}) - for _, parameterRef := range parameters { - if v := parameterRef.Value; v != nil { - key := v.In + ":" + v.Name - if _, ok := dupes[key]; ok { - return fmt.Errorf("more than one %q parameter has name %q", v.In, v.Name) - } - dupes[key] = struct{}{} - } - - if err := parameterRef.Validate(ctx); err != nil { - return err - } - } - return nil -} - -// Parameter is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameter-object -type Parameter struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Name string `json:"name,omitempty" yaml:"name,omitempty"` - In string `json:"in,omitempty" yaml:"in,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Style string `json:"style,omitempty" yaml:"style,omitempty"` - Explode *bool `json:"explode,omitempty" yaml:"explode,omitempty"` - AllowEmptyValue bool `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"` - AllowReserved bool `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"` - Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` - Required bool `json:"required,omitempty" yaml:"required,omitempty"` - Schema *SchemaRef `json:"schema,omitempty" yaml:"schema,omitempty"` - Example any `json:"example,omitempty" yaml:"example,omitempty"` - Examples Examples `json:"examples,omitempty" yaml:"examples,omitempty"` - Content Content `json:"content,omitempty" yaml:"content,omitempty"` -} - -var _ jsonpointer.JSONPointable = (*Parameter)(nil) - -const ( - ParameterInPath = "path" - ParameterInQuery = "query" - ParameterInHeader = "header" - ParameterInCookie = "cookie" -) - -func NewPathParameter(name string) *Parameter { - return &Parameter{ - Name: name, - In: ParameterInPath, - Required: true, - } -} - -func NewQueryParameter(name string) *Parameter { - return &Parameter{ - Name: name, - In: ParameterInQuery, - } -} - -func NewHeaderParameter(name string) *Parameter { - return &Parameter{ - Name: name, - In: ParameterInHeader, - } -} - -func NewCookieParameter(name string) *Parameter { - return &Parameter{ - Name: name, - In: ParameterInCookie, - } -} - -func (parameter *Parameter) WithDescription(value string) *Parameter { - parameter.Description = value - return parameter -} - -func (parameter *Parameter) WithRequired(value bool) *Parameter { - parameter.Required = value - return parameter -} - -func (parameter *Parameter) WithSchema(value *Schema) *Parameter { - if value == nil { - parameter.Schema = nil - } else { - parameter.Schema = &SchemaRef{ - Value: value, - } - } - return parameter -} - -// MarshalJSON returns the JSON encoding of Parameter. -func (parameter Parameter) MarshalJSON() ([]byte, error) { - x, err := parameter.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Parameter. -func (parameter Parameter) MarshalYAML() (any, error) { - m := make(map[string]any, 13+len(parameter.Extensions)) - for k, v := range parameter.Extensions { - m[k] = v - } - - if x := parameter.Name; x != "" { - m["name"] = x - } - if x := parameter.In; x != "" { - m["in"] = x - } - if x := parameter.Description; x != "" { - m["description"] = x - } - if x := parameter.Style; x != "" { - m["style"] = x - } - if x := parameter.Explode; x != nil { - m["explode"] = x - } - if x := parameter.AllowEmptyValue; x { - m["allowEmptyValue"] = x - } - if x := parameter.AllowReserved; x { - m["allowReserved"] = x - } - if x := parameter.Deprecated; x { - m["deprecated"] = x - } - if x := parameter.Required; x { - m["required"] = x - } - if x := parameter.Schema; x != nil { - m["schema"] = x - } - if x := parameter.Example; x != nil { - m["example"] = x - } - if x := parameter.Examples; len(x) != 0 { - m["examples"] = x - } - if x := parameter.Content; len(x) != 0 { - m["content"] = x - } - - return m, nil -} - -// UnmarshalJSON sets Parameter to a copy of data. -func (parameter *Parameter) UnmarshalJSON(data []byte) error { - type ParameterBis Parameter - var x ParameterBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - - delete(x.Extensions, "name") - delete(x.Extensions, "in") - delete(x.Extensions, "description") - delete(x.Extensions, "style") - delete(x.Extensions, "explode") - delete(x.Extensions, "allowEmptyValue") - delete(x.Extensions, "allowReserved") - delete(x.Extensions, "deprecated") - delete(x.Extensions, "required") - delete(x.Extensions, "schema") - delete(x.Extensions, "example") - delete(x.Extensions, "examples") - delete(x.Extensions, "content") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - - *parameter = Parameter(x) - return nil -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (parameter Parameter) JSONLookup(token string) (any, error) { - switch token { - case "schema": - if parameter.Schema != nil { - if parameter.Schema.Ref != "" { - return &Ref{Ref: parameter.Schema.Ref}, nil - } - return parameter.Schema.Value, nil - } - case "name": - return parameter.Name, nil - case "in": - return parameter.In, nil - case "description": - return parameter.Description, nil - case "style": - return parameter.Style, nil - case "explode": - return parameter.Explode, nil - case "allowEmptyValue": - return parameter.AllowEmptyValue, nil - case "allowReserved": - return parameter.AllowReserved, nil - case "deprecated": - return parameter.Deprecated, nil - case "required": - return parameter.Required, nil - case "example": - return parameter.Example, nil - case "examples": - return parameter.Examples, nil - case "content": - return parameter.Content, nil - } - - v, _, err := jsonpointer.GetForToken(parameter.Extensions, token) - return v, err -} - -// SerializationMethod returns a parameter's serialization method. -// When a parameter's serialization method is not defined the method returns -// the default serialization method corresponding to a parameter's location. -func (parameter *Parameter) SerializationMethod() (*SerializationMethod, error) { - switch parameter.In { - case ParameterInPath, ParameterInHeader: - style := parameter.Style - if style == "" { - style = SerializationSimple - } - explode := false - if parameter.Explode != nil { - explode = *parameter.Explode - } - return &SerializationMethod{Style: style, Explode: explode}, nil - case ParameterInQuery, ParameterInCookie: - style := parameter.Style - if style == "" { - style = SerializationForm - } - explode := true - if parameter.Explode != nil { - explode = *parameter.Explode - } - return &SerializationMethod{Style: style, Explode: explode}, nil - default: - return nil, fmt.Errorf("unexpected parameter's 'in': %q", parameter.In) - } -} - -// Validate returns an error if Parameter does not comply with the OpenAPI spec. -func (parameter *Parameter) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if parameter.Name == "" { - return errors.New("parameter name can't be blank") - } - in := parameter.In - switch in { - case - ParameterInPath, - ParameterInQuery, - ParameterInHeader, - ParameterInCookie: - default: - return fmt.Errorf("parameter can't have 'in' value %q", parameter.In) - } - - if in == ParameterInPath && !parameter.Required { - return fmt.Errorf("path parameter %q must be required", parameter.Name) - } - - // Validate a parameter's serialization method. - sm, err := parameter.SerializationMethod() - if err != nil { - return err - } - var smSupported bool - switch { - case parameter.In == ParameterInPath && sm.Style == SerializationSimple && !sm.Explode, - parameter.In == ParameterInPath && sm.Style == SerializationSimple && sm.Explode, - parameter.In == ParameterInPath && sm.Style == SerializationLabel && !sm.Explode, - parameter.In == ParameterInPath && sm.Style == SerializationLabel && sm.Explode, - parameter.In == ParameterInPath && sm.Style == SerializationMatrix && !sm.Explode, - parameter.In == ParameterInPath && sm.Style == SerializationMatrix && sm.Explode, - - parameter.In == ParameterInQuery && sm.Style == SerializationForm && sm.Explode, - parameter.In == ParameterInQuery && sm.Style == SerializationForm && !sm.Explode, - parameter.In == ParameterInQuery && sm.Style == SerializationSpaceDelimited && sm.Explode, - parameter.In == ParameterInQuery && sm.Style == SerializationSpaceDelimited && !sm.Explode, - parameter.In == ParameterInQuery && sm.Style == SerializationPipeDelimited && sm.Explode, - parameter.In == ParameterInQuery && sm.Style == SerializationPipeDelimited && !sm.Explode, - parameter.In == ParameterInQuery && sm.Style == SerializationDeepObject && sm.Explode, - - parameter.In == ParameterInHeader && sm.Style == SerializationSimple && !sm.Explode, - parameter.In == ParameterInHeader && sm.Style == SerializationSimple && sm.Explode, - - parameter.In == ParameterInCookie && sm.Style == SerializationForm && !sm.Explode, - parameter.In == ParameterInCookie && sm.Style == SerializationForm && sm.Explode: - smSupported = true - } - if !smSupported { - e := fmt.Errorf("serialization method with style=%q and explode=%v is not supported by a %s parameter", sm.Style, sm.Explode, in) - return fmt.Errorf("parameter %q schema is invalid: %w", parameter.Name, e) - } - - if (parameter.Schema == nil) == (len(parameter.Content) == 0) { - e := errors.New("parameter must contain exactly one of content and schema") - return fmt.Errorf("parameter %q schema is invalid: %w", parameter.Name, e) - } - - if content := parameter.Content; content != nil { - e := errors.New("parameter content must only contain one entry") - if len(content) > 1 { - return fmt.Errorf("parameter %q content is invalid: %w", parameter.Name, e) - } - - if err := content.Validate(ctx); err != nil { - return fmt.Errorf("parameter %q content is invalid: %w", parameter.Name, err) - } - } - - if schema := parameter.Schema; schema != nil { - if err := schema.Validate(ctx); err != nil { - return fmt.Errorf("parameter %q schema is invalid: %w", parameter.Name, err) - } - if parameter.Example != nil && parameter.Examples != nil { - return fmt.Errorf("parameter %q example and examples are mutually exclusive", parameter.Name) - } - - if vo := getValidationOptions(ctx); vo.examplesValidationDisabled { - return nil - } - if example := parameter.Example; example != nil { - if err := validateExampleValue(ctx, example, schema.Value); err != nil { - return fmt.Errorf("invalid example: %w", err) - } - } else if examples := parameter.Examples; examples != nil { - names := make([]string, 0, len(examples)) - for name := range examples { - names = append(names, name) - } - sort.Strings(names) - for _, k := range names { - v := examples[k] - if err := v.Validate(ctx); err != nil { - return fmt.Errorf("%s: %w", k, err) - } - if err := validateExampleValue(ctx, v.Value.Value, schema.Value); err != nil { - return fmt.Errorf("%s: %w", k, err) - } - } - } - } - - return validateExtensions(ctx, parameter.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/path_item.go b/vendor/github.com/getkin/kin-openapi/openapi3/path_item.go deleted file mode 100644 index 859634fe6..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/path_item.go +++ /dev/null @@ -1,248 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "sort" -) - -// PathItem is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#path-item-object -type PathItem struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Ref string `json:"$ref,omitempty" yaml:"$ref,omitempty"` - Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Connect *Operation `json:"connect,omitempty" yaml:"connect,omitempty"` - Delete *Operation `json:"delete,omitempty" yaml:"delete,omitempty"` - Get *Operation `json:"get,omitempty" yaml:"get,omitempty"` - Head *Operation `json:"head,omitempty" yaml:"head,omitempty"` - Options *Operation `json:"options,omitempty" yaml:"options,omitempty"` - Patch *Operation `json:"patch,omitempty" yaml:"patch,omitempty"` - Post *Operation `json:"post,omitempty" yaml:"post,omitempty"` - Put *Operation `json:"put,omitempty" yaml:"put,omitempty"` - Trace *Operation `json:"trace,omitempty" yaml:"trace,omitempty"` - Servers Servers `json:"servers,omitempty" yaml:"servers,omitempty"` - Parameters Parameters `json:"parameters,omitempty" yaml:"parameters,omitempty"` -} - -// MarshalJSON returns the JSON encoding of PathItem. -func (pathItem PathItem) MarshalJSON() ([]byte, error) { - x, err := pathItem.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of PathItem. -func (pathItem PathItem) MarshalYAML() (any, error) { - if ref := pathItem.Ref; ref != "" { - return Ref{Ref: ref}, nil - } - - m := make(map[string]any, 13+len(pathItem.Extensions)) - for k, v := range pathItem.Extensions { - m[k] = v - } - if x := pathItem.Summary; x != "" { - m["summary"] = x - } - if x := pathItem.Description; x != "" { - m["description"] = x - } - if x := pathItem.Connect; x != nil { - m["connect"] = x - } - if x := pathItem.Delete; x != nil { - m["delete"] = x - } - if x := pathItem.Get; x != nil { - m["get"] = x - } - if x := pathItem.Head; x != nil { - m["head"] = x - } - if x := pathItem.Options; x != nil { - m["options"] = x - } - if x := pathItem.Patch; x != nil { - m["patch"] = x - } - if x := pathItem.Post; x != nil { - m["post"] = x - } - if x := pathItem.Put; x != nil { - m["put"] = x - } - if x := pathItem.Trace; x != nil { - m["trace"] = x - } - if x := pathItem.Servers; len(x) != 0 { - m["servers"] = x - } - if x := pathItem.Parameters; len(x) != 0 { - m["parameters"] = x - } - return m, nil -} - -// UnmarshalJSON sets PathItem to a copy of data. -func (pathItem *PathItem) UnmarshalJSON(data []byte) error { - type PathItemBis PathItem - var x PathItemBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "$ref") - delete(x.Extensions, "summary") - delete(x.Extensions, "description") - delete(x.Extensions, "connect") - delete(x.Extensions, "delete") - delete(x.Extensions, "get") - delete(x.Extensions, "head") - delete(x.Extensions, "options") - delete(x.Extensions, "patch") - delete(x.Extensions, "post") - delete(x.Extensions, "put") - delete(x.Extensions, "trace") - delete(x.Extensions, "servers") - delete(x.Extensions, "parameters") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *pathItem = PathItem(x) - return nil -} - -func (pathItem *PathItem) Operations() map[string]*Operation { - operations := make(map[string]*Operation) - if v := pathItem.Connect; v != nil { - operations[http.MethodConnect] = v - } - if v := pathItem.Delete; v != nil { - operations[http.MethodDelete] = v - } - if v := pathItem.Get; v != nil { - operations[http.MethodGet] = v - } - if v := pathItem.Head; v != nil { - operations[http.MethodHead] = v - } - if v := pathItem.Options; v != nil { - operations[http.MethodOptions] = v - } - if v := pathItem.Patch; v != nil { - operations[http.MethodPatch] = v - } - if v := pathItem.Post; v != nil { - operations[http.MethodPost] = v - } - if v := pathItem.Put; v != nil { - operations[http.MethodPut] = v - } - if v := pathItem.Trace; v != nil { - operations[http.MethodTrace] = v - } - return operations -} - -func (pathItem *PathItem) GetOperation(method string) *Operation { - switch method { - case http.MethodConnect: - return pathItem.Connect - case http.MethodDelete: - return pathItem.Delete - case http.MethodGet: - return pathItem.Get - case http.MethodHead: - return pathItem.Head - case http.MethodOptions: - return pathItem.Options - case http.MethodPatch: - return pathItem.Patch - case http.MethodPost: - return pathItem.Post - case http.MethodPut: - return pathItem.Put - case http.MethodTrace: - return pathItem.Trace - default: - panic(fmt.Errorf("unsupported HTTP method %q", method)) - } -} - -func (pathItem *PathItem) SetOperation(method string, operation *Operation) { - switch method { - case http.MethodConnect: - pathItem.Connect = operation - case http.MethodDelete: - pathItem.Delete = operation - case http.MethodGet: - pathItem.Get = operation - case http.MethodHead: - pathItem.Head = operation - case http.MethodOptions: - pathItem.Options = operation - case http.MethodPatch: - pathItem.Patch = operation - case http.MethodPost: - pathItem.Post = operation - case http.MethodPut: - pathItem.Put = operation - case http.MethodTrace: - pathItem.Trace = operation - default: - panic(fmt.Errorf("unsupported HTTP method %q", method)) - } -} - -// Validate returns an error if PathItem does not comply with the OpenAPI spec. -func (pathItem *PathItem) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - operations := pathItem.Operations() - - methods := make([]string, 0, len(operations)) - for method := range operations { - methods = append(methods, method) - } - sort.Strings(methods) - for _, method := range methods { - operation := operations[method] - if err := operation.Validate(ctx); err != nil { - return fmt.Errorf("invalid operation %s: %v", method, err) - } - } - - if v := pathItem.Parameters; v != nil { - if err := v.Validate(ctx); err != nil { - return err - } - } - - return validateExtensions(ctx, pathItem.Extensions) -} - -// isEmpty's introduced in 546590b1 -func (pathItem *PathItem) isEmpty() bool { - // NOTE: ignores pathItem.Extensions - // NOTE: ignores pathItem.Ref - return pathItem.Summary == "" && - pathItem.Description == "" && - pathItem.Connect == nil && - pathItem.Delete == nil && - pathItem.Get == nil && - pathItem.Head == nil && - pathItem.Options == nil && - pathItem.Patch == nil && - pathItem.Post == nil && - pathItem.Put == nil && - pathItem.Trace == nil && - len(pathItem.Servers) == 0 && - len(pathItem.Parameters) == 0 -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/paths.go b/vendor/github.com/getkin/kin-openapi/openapi3/paths.go deleted file mode 100644 index 76747412b..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/paths.go +++ /dev/null @@ -1,268 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - "sort" - "strings" -) - -// Paths is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#paths-object -type Paths struct { - Extensions map[string]any `json:"-" yaml:"-"` - - m map[string]*PathItem -} - -// NewPaths builds a paths object with path items in insertion order. -func NewPaths(opts ...NewPathsOption) *Paths { - paths := NewPathsWithCapacity(len(opts)) - for _, opt := range opts { - opt(paths) - } - return paths -} - -// NewPathsOption describes options to NewPaths func -type NewPathsOption func(*Paths) - -// WithPath adds a named path item -func WithPath(path string, pathItem *PathItem) NewPathsOption { - return func(paths *Paths) { - if p := pathItem; p != nil && path != "" { - paths.Set(path, p) - } - } -} - -// Validate returns an error if Paths does not comply with the OpenAPI spec. -func (paths *Paths) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - normalizedPaths := make(map[string]string, paths.Len()) - - keys := make([]string, 0, paths.Len()) - for key := range paths.Map() { - keys = append(keys, key) - } - sort.Strings(keys) - for _, path := range keys { - pathItem := paths.Value(path) - if path == "" || path[0] != '/' { - return fmt.Errorf("path %q does not start with a forward slash (/)", path) - } - - if pathItem == nil { - pathItem = &PathItem{} - paths.Set(path, pathItem) - } - - normalizedPath, _, varsInPath := normalizeTemplatedPath(path) - if oldPath, ok := normalizedPaths[normalizedPath]; ok { - return fmt.Errorf("conflicting paths %q and %q", path, oldPath) - } - normalizedPaths[path] = path - - var commonParams []string - for _, parameterRef := range pathItem.Parameters { - if parameterRef != nil { - if parameter := parameterRef.Value; parameter != nil && parameter.In == ParameterInPath { - commonParams = append(commonParams, parameter.Name) - } - } - } - operations := pathItem.Operations() - methods := make([]string, 0, len(operations)) - for method := range operations { - methods = append(methods, method) - } - sort.Strings(methods) - for _, method := range methods { - operation := operations[method] - var setParams []string - for _, parameterRef := range operation.Parameters { - if parameterRef != nil { - if parameter := parameterRef.Value; parameter != nil && parameter.In == ParameterInPath { - setParams = append(setParams, parameter.Name) - } - } - } - if expected := len(setParams) + len(commonParams); expected != len(varsInPath) { - expected -= len(varsInPath) - if expected < 0 { - expected *= -1 - } - missing := make(map[string]struct{}, expected) - definedParams := append(setParams, commonParams...) - for _, name := range definedParams { - if _, ok := varsInPath[name]; !ok { - missing[name] = struct{}{} - } - } - for name := range varsInPath { - got := false - for _, othername := range definedParams { - if othername == name { - got = true - break - } - } - if !got { - missing[name] = struct{}{} - } - } - if len(missing) != 0 { - missings := make([]string, 0, len(missing)) - for name := range missing { - missings = append(missings, name) - } - return fmt.Errorf("operation %s %s must define exactly all path parameters (missing: %v)", method, path, missings) - } - } - } - - if err := pathItem.Validate(ctx); err != nil { - return fmt.Errorf("invalid path %s: %v", path, err) - } - } - - if err := paths.validateUniqueOperationIDs(); err != nil { - return err - } - - return validateExtensions(ctx, paths.Extensions) -} - -// InMatchingOrder returns paths in the order they are matched against URLs. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#paths-object -// When matching URLs, concrete (non-templated) paths would be matched -// before their templated counterparts. -func (paths *Paths) InMatchingOrder() []string { - // NOTE: sorting by number of variables ASC then by descending lexicographical - // order seems to be a good heuristic. - if paths.Len() == 0 { - return nil - } - - vars := make(map[int][]string) - max := 0 - for path := range paths.Map() { - count := strings.Count(path, "}") - vars[count] = append(vars[count], path) - if count > max { - max = count - } - } - - ordered := make([]string, 0, paths.Len()) - for c := 0; c <= max; c++ { - if ps, ok := vars[c]; ok { - sort.Sort(sort.Reverse(sort.StringSlice(ps))) - ordered = append(ordered, ps...) - } - } - return ordered -} - -// Find returns a path that matches the key. -// -// The method ignores differences in template variable names (except possible "*" suffix). -// -// For example: -// -// paths := openapi3.Paths { -// "/person/{personName}": &openapi3.PathItem{}, -// } -// pathItem := path.Find("/person/{name}") -// -// would return the correct path item. -func (paths *Paths) Find(key string) *PathItem { - // Try directly access the map - pathItem := paths.Value(key) - if pathItem != nil { - return pathItem - } - - normalizedPath, expected, _ := normalizeTemplatedPath(key) - for path, pathItem := range paths.Map() { - pathNormalized, got, _ := normalizeTemplatedPath(path) - if got == expected && pathNormalized == normalizedPath { - return pathItem - } - } - return nil -} - -func (paths *Paths) validateUniqueOperationIDs() error { - operationIDs := make(map[string]string) - for urlPath, pathItem := range paths.Map() { - if pathItem == nil { - continue - } - for httpMethod, operation := range pathItem.Operations() { - if operation == nil || operation.OperationID == "" { - continue - } - endpoint := httpMethod + " " + urlPath - if endpointDup, ok := operationIDs[operation.OperationID]; ok { - if endpoint > endpointDup { // For make error message a bit more deterministic. May be useful for tests. - endpoint, endpointDup = endpointDup, endpoint - } - return fmt.Errorf("operations %q and %q have the same operation id %q", - endpoint, endpointDup, operation.OperationID) - } - operationIDs[operation.OperationID] = endpoint - } - } - return nil -} - -func normalizeTemplatedPath(path string) (string, uint, map[string]struct{}) { - if strings.IndexByte(path, '{') < 0 { - return path, 0, nil - } - - var buffTpl strings.Builder - buffTpl.Grow(len(path)) - - var ( - cc rune - count uint - isVariable bool - vars = make(map[string]struct{}) - buffVar strings.Builder - ) - for i, c := range path { - if isVariable { - if c == '}' { - // End path variable - isVariable = false - - vars[buffVar.String()] = struct{}{} - buffVar = strings.Builder{} - - // First append possible '*' before this character - // The character '}' will be appended - if i > 0 && cc == '*' { - buffTpl.WriteRune(cc) - } - } else { - buffVar.WriteRune(c) - continue - } - - } else if c == '{' { - // Begin path variable - isVariable = true - - // The character '{' will be appended - count++ - } - - // Append the character - buffTpl.WriteRune(c) - cc = c - } - return buffTpl.String(), count, vars -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/ref.go b/vendor/github.com/getkin/kin-openapi/openapi3/ref.go deleted file mode 100644 index 07060731f..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/ref.go +++ /dev/null @@ -1,9 +0,0 @@ -package openapi3 - -//go:generate go run refsgenerator.go - -// Ref is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#reference-object -type Ref struct { - Ref string `json:"$ref" yaml:"$ref"` -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/refs.go b/vendor/github.com/getkin/kin-openapi/openapi3/refs.go deleted file mode 100644 index d337b0e3d..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/refs.go +++ /dev/null @@ -1,1238 +0,0 @@ -// Code generated by go generate; DO NOT EDIT. -package openapi3 - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - "sort" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/perimeterx/marshmallow" -) - -// CallbackRef represents either a Callback or a $ref to a Callback. -// When serializing and both fields are set, Ref is preferred over Value. -type CallbackRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *Callback - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*CallbackRef)(nil) - -func (x *CallbackRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *CallbackRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *CallbackRef) CollectionName() string { return "callbacks" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *CallbackRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *CallbackRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of CallbackRef. -func (x CallbackRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of CallbackRef. -func (x CallbackRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets CallbackRef to a copy of data. -func (x *CallbackRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if CallbackRef does not comply with the OpenAPI spec. -func (x *CallbackRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *CallbackRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} - -// ExampleRef represents either a Example or a $ref to a Example. -// When serializing and both fields are set, Ref is preferred over Value. -type ExampleRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *Example - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*ExampleRef)(nil) - -func (x *ExampleRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *ExampleRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *ExampleRef) CollectionName() string { return "examples" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *ExampleRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *ExampleRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of ExampleRef. -func (x ExampleRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of ExampleRef. -func (x ExampleRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets ExampleRef to a copy of data. -func (x *ExampleRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if ExampleRef does not comply with the OpenAPI spec. -func (x *ExampleRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *ExampleRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} - -// HeaderRef represents either a Header or a $ref to a Header. -// When serializing and both fields are set, Ref is preferred over Value. -type HeaderRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *Header - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*HeaderRef)(nil) - -func (x *HeaderRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *HeaderRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *HeaderRef) CollectionName() string { return "headers" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *HeaderRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *HeaderRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of HeaderRef. -func (x HeaderRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of HeaderRef. -func (x HeaderRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets HeaderRef to a copy of data. -func (x *HeaderRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if HeaderRef does not comply with the OpenAPI spec. -func (x *HeaderRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *HeaderRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} - -// LinkRef represents either a Link or a $ref to a Link. -// When serializing and both fields are set, Ref is preferred over Value. -type LinkRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *Link - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*LinkRef)(nil) - -func (x *LinkRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *LinkRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *LinkRef) CollectionName() string { return "links" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *LinkRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *LinkRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of LinkRef. -func (x LinkRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of LinkRef. -func (x LinkRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets LinkRef to a copy of data. -func (x *LinkRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if LinkRef does not comply with the OpenAPI spec. -func (x *LinkRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *LinkRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} - -// ParameterRef represents either a Parameter or a $ref to a Parameter. -// When serializing and both fields are set, Ref is preferred over Value. -type ParameterRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *Parameter - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*ParameterRef)(nil) - -func (x *ParameterRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *ParameterRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *ParameterRef) CollectionName() string { return "parameters" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *ParameterRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *ParameterRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of ParameterRef. -func (x ParameterRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of ParameterRef. -func (x ParameterRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets ParameterRef to a copy of data. -func (x *ParameterRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if ParameterRef does not comply with the OpenAPI spec. -func (x *ParameterRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *ParameterRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} - -// RequestBodyRef represents either a RequestBody or a $ref to a RequestBody. -// When serializing and both fields are set, Ref is preferred over Value. -type RequestBodyRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *RequestBody - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*RequestBodyRef)(nil) - -func (x *RequestBodyRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *RequestBodyRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *RequestBodyRef) CollectionName() string { return "requestBodies" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *RequestBodyRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *RequestBodyRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of RequestBodyRef. -func (x RequestBodyRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of RequestBodyRef. -func (x RequestBodyRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets RequestBodyRef to a copy of data. -func (x *RequestBodyRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if RequestBodyRef does not comply with the OpenAPI spec. -func (x *RequestBodyRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *RequestBodyRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} - -// ResponseRef represents either a Response or a $ref to a Response. -// When serializing and both fields are set, Ref is preferred over Value. -type ResponseRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *Response - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*ResponseRef)(nil) - -func (x *ResponseRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *ResponseRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *ResponseRef) CollectionName() string { return "responses" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *ResponseRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *ResponseRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of ResponseRef. -func (x ResponseRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of ResponseRef. -func (x ResponseRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets ResponseRef to a copy of data. -func (x *ResponseRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if ResponseRef does not comply with the OpenAPI spec. -func (x *ResponseRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *ResponseRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} - -// SchemaRef represents either a Schema or a $ref to a Schema. -// When serializing and both fields are set, Ref is preferred over Value. -type SchemaRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *Schema - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*SchemaRef)(nil) - -func (x *SchemaRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *SchemaRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *SchemaRef) CollectionName() string { return "schemas" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *SchemaRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *SchemaRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of SchemaRef. -func (x SchemaRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of SchemaRef. -func (x SchemaRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets SchemaRef to a copy of data. -func (x *SchemaRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if SchemaRef does not comply with the OpenAPI spec. -func (x *SchemaRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *SchemaRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} - -// SecuritySchemeRef represents either a SecurityScheme or a $ref to a SecurityScheme. -// When serializing and both fields are set, Ref is preferred over Value. -type SecuritySchemeRef struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *SecurityScheme - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*SecuritySchemeRef)(nil) - -func (x *SecuritySchemeRef) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *SecuritySchemeRef) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *SecuritySchemeRef) CollectionName() string { return "securitySchemes" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *SecuritySchemeRef) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *SecuritySchemeRef) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of SecuritySchemeRef. -func (x SecuritySchemeRef) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of SecuritySchemeRef. -func (x SecuritySchemeRef) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets SecuritySchemeRef to a copy of data. -func (x *SecuritySchemeRef) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if SecuritySchemeRef does not comply with the OpenAPI spec. -func (x *SecuritySchemeRef) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *SecuritySchemeRef) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/refs.tmpl b/vendor/github.com/getkin/kin-openapi/openapi3/refs.tmpl deleted file mode 100644 index a3f5bdab7..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/refs.tmpl +++ /dev/null @@ -1,151 +0,0 @@ -// Code generated by go generate; DO NOT EDIT. -package {{ .Package }} - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - "sort" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/perimeterx/marshmallow" -) -{{ range $type := .Types }} -// {{ $type.Name }}Ref represents either a {{ $type.Name }} or a $ref to a {{ $type.Name }}. -// When serializing and both fields are set, Ref is preferred over Value. -type {{ $type.Name }}Ref struct { - // Extensions only captures fields starting with 'x-' as no other fields - // are allowed by the openapi spec. - Extensions map[string]any - - Ref string - Value *{{ $type.Name }} - extra []string - - refPath *url.URL -} - -var _ jsonpointer.JSONPointable = (*{{ $type.Name }}Ref)(nil) - -func (x *{{ $type.Name }}Ref) isEmpty() bool { return x == nil || x.Ref == "" && x.Value == nil } - -// RefString returns the $ref value. -func (x *{{ $type.Name }}Ref) RefString() string { return x.Ref } - -// CollectionName returns the JSON string used for a collection of these components. -func (x *{{ $type.Name }}Ref) CollectionName() string { return "{{ $type.CollectionName }}" } - -// RefPath returns the path of the $ref relative to the root document. -func (x *{{ $type.Name }}Ref) RefPath() *url.URL { return copyURI(x.refPath) } - -func (x *{{ $type.Name }}Ref) setRefPath(u *url.URL) { - // Once the refPath is set don't override. References can be loaded - // multiple times not all with access to the correct path info. - if x.refPath != nil { - return - } - - x.refPath = copyURI(u) -} - -// MarshalYAML returns the YAML encoding of {{ $type.Name }}Ref. -func (x {{ $type.Name }}Ref) MarshalYAML() (any, error) { - if ref := x.Ref; ref != "" { - return &Ref{Ref: ref}, nil - } - return x.Value.MarshalYAML() -} - -// MarshalJSON returns the JSON encoding of {{ $type.Name }}Ref. -func (x {{ $type.Name }}Ref) MarshalJSON() ([]byte, error) { - y, err := x.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(y) -} - -// UnmarshalJSON sets {{ $type.Name }}Ref to a copy of data. -func (x *{{ $type.Name }}Ref) UnmarshalJSON(data []byte) error { - var refOnly Ref - if extra, err := marshmallow.Unmarshal(data, &refOnly, marshmallow.WithExcludeKnownFieldsFromMap(true)); err == nil && refOnly.Ref != "" { - x.Ref = refOnly.Ref - if len(extra) != 0 { - x.extra = make([]string, 0, len(extra)) - for key := range extra { - x.extra = append(x.extra, key) - } - sort.Strings(x.extra) - for k := range extra { - if !strings.HasPrefix(k, "x-") { - delete(extra, k) - } - } - if len(extra) != 0 { - x.Extensions = extra - } - } - return nil - } - return json.Unmarshal(data, &x.Value) -} - -// Validate returns an error if {{ $type.Name }}Ref does not comply with the OpenAPI spec. -func (x *{{ $type.Name }}Ref) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - exProhibited := getValidationOptions(ctx).schemaExtensionsInRefProhibited - var extras []string - if extra := x.extra; len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for _, ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - // extras in the Extensions checked below - if _, ok := x.Extensions[ex]; !ok { - extras = append(extras, ex) - } - } - } - - if extra := x.Extensions; exProhibited && len(extra) != 0 { - allowed := getValidationOptions(ctx).extraSiblingFieldsAllowed - for ex := range extra { - if allowed != nil { - if _, ok := allowed[ex]; ok { - continue - } - } - extras = append(extras, ex) - } - } - - if len(extras) != 0 { - return fmt.Errorf("extra sibling fields: %+v", extras) - } - - if v := x.Value; v != nil { - return v.Validate(ctx) - } - - return foundUnresolvedRef(x.Ref) -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (x *{{ $type.Name }}Ref) JSONLookup(token string) (any, error) { - if token == "$ref" { - return x.Ref, nil - } - - if v, ok := x.Extensions[token]; ok { - return v, nil - } - - ptr, _, err := jsonpointer.GetForToken(x.Value, token) - return ptr, err -} -{{ end -}} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/refs_test.tmpl b/vendor/github.com/getkin/kin-openapi/openapi3/refs_test.tmpl deleted file mode 100644 index 634fccf6f..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/refs_test.tmpl +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by go generate; DO NOT EDIT. -package {{ .Package }} - -import ( - "context" - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) -{{ range $type := .Types }} -func Test{{ $type.Name }}Ref_Extensions(t *testing.T) { - data := []byte(`{"$ref":"#/components/schemas/Pet","something":"integer","x-order":1}`) - - ref := {{ $type.Name }}Ref{} - err := json.Unmarshal(data, &ref) - assert.NoError(t, err) - - // captures extension - assert.Equal(t, "#/components/schemas/Pet", ref.Ref) - assert.Equal(t, float64(1), ref.Extensions["x-order"]) - - // does not capture non-extensions - assert.Nil(t, ref.Extensions["something"]) - - // validation - err = ref.Validate(context.Background()) - require.EqualError(t, err, "extra sibling fields: [something]") - - err = ref.Validate(context.Background(), ProhibitExtensionsWithRef()) - require.EqualError(t, err, "extra sibling fields: [something x-order]") - - err = ref.Validate(context.Background(), AllowExtraSiblingFields("something")) - assert.ErrorContains(t, err, "found unresolved ref") // expected since value not defined - - // non-extension not json lookable - _, err = ref.JSONLookup("something") - assert.Error(t, err) -{{ if ne $type.Name "Header" }} - t.Run("extentions in value", func(t *testing.T) { - ref.Value = &{{ $type.Name }}{Extensions: map[string]any{}} - ref.Value.Extensions["x-order"] = 2.0 - - // prefers the value next to the \$ref over the one in the \$ref. - v, err := ref.JSONLookup("x-order") - assert.NoError(t, err) - assert.Equal(t, float64(1), v) - }) -{{ else }} - // Header does not have its own extensions. -{{ end -}} -} -{{ end -}} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/request_body.go b/vendor/github.com/getkin/kin-openapi/openapi3/request_body.go deleted file mode 100644 index 6d4b8185e..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/request_body.go +++ /dev/null @@ -1,138 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" -) - -// RequestBody is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#request-body-object -type RequestBody struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Required bool `json:"required,omitempty" yaml:"required,omitempty"` - Content Content `json:"content" yaml:"content"` -} - -func NewRequestBody() *RequestBody { - return &RequestBody{} -} - -func (requestBody *RequestBody) WithDescription(value string) *RequestBody { - requestBody.Description = value - return requestBody -} - -func (requestBody *RequestBody) WithRequired(value bool) *RequestBody { - requestBody.Required = value - return requestBody -} - -func (requestBody *RequestBody) WithContent(content Content) *RequestBody { - requestBody.Content = content - return requestBody -} - -func (requestBody *RequestBody) WithSchemaRef(value *SchemaRef, consumes []string) *RequestBody { - requestBody.Content = NewContentWithSchemaRef(value, consumes) - return requestBody -} - -func (requestBody *RequestBody) WithSchema(value *Schema, consumes []string) *RequestBody { - requestBody.Content = NewContentWithSchema(value, consumes) - return requestBody -} - -func (requestBody *RequestBody) WithJSONSchemaRef(value *SchemaRef) *RequestBody { - requestBody.Content = NewContentWithJSONSchemaRef(value) - return requestBody -} - -func (requestBody *RequestBody) WithJSONSchema(value *Schema) *RequestBody { - requestBody.Content = NewContentWithJSONSchema(value) - return requestBody -} - -func (requestBody *RequestBody) WithFormDataSchemaRef(value *SchemaRef) *RequestBody { - requestBody.Content = NewContentWithFormDataSchemaRef(value) - return requestBody -} - -func (requestBody *RequestBody) WithFormDataSchema(value *Schema) *RequestBody { - requestBody.Content = NewContentWithFormDataSchema(value) - return requestBody -} - -func (requestBody *RequestBody) GetMediaType(mediaType string) *MediaType { - m := requestBody.Content - if m == nil { - return nil - } - return m[mediaType] -} - -// MarshalJSON returns the JSON encoding of RequestBody. -func (requestBody RequestBody) MarshalJSON() ([]byte, error) { - x, err := requestBody.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of RequestBody. -func (requestBody RequestBody) MarshalYAML() (any, error) { - m := make(map[string]any, 3+len(requestBody.Extensions)) - for k, v := range requestBody.Extensions { - m[k] = v - } - if x := requestBody.Description; x != "" { - m["description"] = requestBody.Description - } - if x := requestBody.Required; x { - m["required"] = x - } - if x := requestBody.Content; true { - m["content"] = x - } - return m, nil -} - -// UnmarshalJSON sets RequestBody to a copy of data. -func (requestBody *RequestBody) UnmarshalJSON(data []byte) error { - type RequestBodyBis RequestBody - var x RequestBodyBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "description") - delete(x.Extensions, "required") - delete(x.Extensions, "content") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *requestBody = RequestBody(x) - return nil -} - -// Validate returns an error if RequestBody does not comply with the OpenAPI spec. -func (requestBody *RequestBody) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if requestBody.Content == nil { - return errors.New("content of the request body is required") - } - - if vo := getValidationOptions(ctx); !vo.examplesValidationDisabled { - vo.examplesValidationAsReq, vo.examplesValidationAsRes = true, false - } - - if err := requestBody.Content.Validate(ctx); err != nil { - return err - } - - return validateExtensions(ctx, requestBody.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/response.go b/vendor/github.com/getkin/kin-openapi/openapi3/response.go deleted file mode 100644 index af8fda6f7..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/response.go +++ /dev/null @@ -1,227 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "sort" - "strconv" -) - -// Responses is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#responses-object -type Responses struct { - Extensions map[string]any `json:"-" yaml:"-"` - - m map[string]*ResponseRef -} - -// NewResponses builds a responses object with response objects in insertion order. -// Given no arguments, NewResponses returns a valid responses object containing a default match-all reponse. -func NewResponses(opts ...NewResponsesOption) *Responses { - if len(opts) == 0 { - return NewResponses(WithName("default", NewResponse().WithDescription(""))) - } - responses := NewResponsesWithCapacity(len(opts)) - for _, opt := range opts { - opt(responses) - } - return responses -} - -// NewResponsesOption describes options to NewResponses func -type NewResponsesOption func(*Responses) - -// WithStatus adds a status code keyed ResponseRef -func WithStatus(status int, responseRef *ResponseRef) NewResponsesOption { - return func(responses *Responses) { - if r := responseRef; r != nil { - code := strconv.FormatInt(int64(status), 10) - responses.Set(code, r) - } - } -} - -// WithName adds a name-keyed Response -func WithName(name string, response *Response) NewResponsesOption { - return func(responses *Responses) { - if r := response; r != nil && name != "" { - responses.Set(name, &ResponseRef{Value: r}) - } - } -} - -// Default returns the default response -func (responses *Responses) Default() *ResponseRef { - return responses.Value("default") -} - -// Status returns a ResponseRef for the given status -// If an exact match isn't initially found a patterned field is checked using -// the first digit to determine the range (eg: 201 to 2XX) -// See https://spec.openapis.org/oas/v3.0.3#patterned-fields-0 -func (responses *Responses) Status(status int) *ResponseRef { - st := strconv.FormatInt(int64(status), 10) - if rref := responses.Value(st); rref != nil { - return rref - } - if 99 < status && status < 600 { - st = string(st[0]) + "XX" - switch st { - case "1XX", "2XX", "3XX", "4XX", "5XX": - return responses.Value(st) - } - } - return nil -} - -// Validate returns an error if Responses does not comply with the OpenAPI spec. -func (responses *Responses) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if responses.Len() == 0 { - return errors.New("the responses object MUST contain at least one response code") - } - - keys := make([]string, 0, responses.Len()) - for key := range responses.Map() { - keys = append(keys, key) - } - sort.Strings(keys) - for _, key := range keys { - v := responses.Value(key) - if err := v.Validate(ctx); err != nil { - return err - } - } - - return validateExtensions(ctx, responses.Extensions) -} - -// Response is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#response-object -type Response struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Description *string `json:"description,omitempty" yaml:"description,omitempty"` - Headers Headers `json:"headers,omitempty" yaml:"headers,omitempty"` - Content Content `json:"content,omitempty" yaml:"content,omitempty"` - Links Links `json:"links,omitempty" yaml:"links,omitempty"` -} - -func NewResponse() *Response { - return &Response{} -} - -func (response *Response) WithDescription(value string) *Response { - response.Description = &value - return response -} - -func (response *Response) WithContent(content Content) *Response { - response.Content = content - return response -} - -func (response *Response) WithJSONSchema(schema *Schema) *Response { - response.Content = NewContentWithJSONSchema(schema) - return response -} - -func (response *Response) WithJSONSchemaRef(schema *SchemaRef) *Response { - response.Content = NewContentWithJSONSchemaRef(schema) - return response -} - -// MarshalJSON returns the JSON encoding of Response. -func (response Response) MarshalJSON() ([]byte, error) { - x, err := response.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Response. -func (response Response) MarshalYAML() (any, error) { - m := make(map[string]any, 4+len(response.Extensions)) - for k, v := range response.Extensions { - m[k] = v - } - if x := response.Description; x != nil { - m["description"] = x - } - if x := response.Headers; len(x) != 0 { - m["headers"] = x - } - if x := response.Content; len(x) != 0 { - m["content"] = x - } - if x := response.Links; len(x) != 0 { - m["links"] = x - } - return m, nil -} - -// UnmarshalJSON sets Response to a copy of data. -func (response *Response) UnmarshalJSON(data []byte) error { - type ResponseBis Response - var x ResponseBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "description") - delete(x.Extensions, "headers") - delete(x.Extensions, "content") - delete(x.Extensions, "links") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *response = Response(x) - return nil -} - -// Validate returns an error if Response does not comply with the OpenAPI spec. -func (response *Response) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if response.Description == nil { - return errors.New("a short description of the response is required") - } - if vo := getValidationOptions(ctx); !vo.examplesValidationDisabled { - vo.examplesValidationAsReq, vo.examplesValidationAsRes = false, true - } - - if content := response.Content; content != nil { - if err := content.Validate(ctx); err != nil { - return err - } - } - - headers := make([]string, 0, len(response.Headers)) - for name := range response.Headers { - headers = append(headers, name) - } - sort.Strings(headers) - for _, name := range headers { - header := response.Headers[name] - if err := header.Validate(ctx); err != nil { - return err - } - } - - links := make([]string, 0, len(response.Links)) - for name := range response.Links { - links = append(links, name) - } - sort.Strings(links) - for _, name := range links { - link := response.Links[name] - if err := link.Validate(ctx); err != nil { - return err - } - } - - return validateExtensions(ctx, response.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/schema.go b/vendor/github.com/getkin/kin-openapi/openapi3/schema.go deleted file mode 100644 index f81196066..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/schema.go +++ /dev/null @@ -1,2246 +0,0 @@ -package openapi3 - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "math" - "math/big" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "unicode/utf16" - - "github.com/go-openapi/jsonpointer" - "github.com/mohae/deepcopy" -) - -const ( - TypeArray = "array" - TypeBoolean = "boolean" - TypeInteger = "integer" - TypeNumber = "number" - TypeObject = "object" - TypeString = "string" - TypeNull = "null" -) - -var ( - // SchemaErrorDetailsDisabled disables printing of details about schema errors. - SchemaErrorDetailsDisabled = false - - errSchema = errors.New("input does not match the schema") - - // ErrOneOfConflict is the SchemaError Origin when data matches more than one oneOf schema - ErrOneOfConflict = errors.New("input matches more than one oneOf schemas") - - // ErrSchemaInputNaN may be returned when validating a number - ErrSchemaInputNaN = errors.New("floating point NaN is not allowed") - // ErrSchemaInputInf may be returned when validating a number - ErrSchemaInputInf = errors.New("floating point Inf is not allowed") - - compiledPatterns sync.Map -) - -// NewSchemaRef simply builds a SchemaRef -func NewSchemaRef(ref string, value *Schema) *SchemaRef { - return &SchemaRef{ - Ref: ref, - Value: value, - } -} - -type SchemaRefs []*SchemaRef - -var _ jsonpointer.JSONPointable = (*SchemaRefs)(nil) - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (s SchemaRefs) JSONLookup(token string) (any, error) { - i, err := strconv.ParseUint(token, 10, 64) - if err != nil { - return nil, err - } - - if i >= uint64(len(s)) { - return nil, fmt.Errorf("index out of range: %d", i) - } - - ref := s[i] - - if ref == nil || ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -// Schema is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object -type Schema struct { - Extensions map[string]any `json:"-" yaml:"-"` - - OneOf SchemaRefs `json:"oneOf,omitempty" yaml:"oneOf,omitempty"` - AnyOf SchemaRefs `json:"anyOf,omitempty" yaml:"anyOf,omitempty"` - AllOf SchemaRefs `json:"allOf,omitempty" yaml:"allOf,omitempty"` - Not *SchemaRef `json:"not,omitempty" yaml:"not,omitempty"` - Type *Types `json:"type,omitempty" yaml:"type,omitempty"` - Title string `json:"title,omitempty" yaml:"title,omitempty"` - Format string `json:"format,omitempty" yaml:"format,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Enum []any `json:"enum,omitempty" yaml:"enum,omitempty"` - Default any `json:"default,omitempty" yaml:"default,omitempty"` - Example any `json:"example,omitempty" yaml:"example,omitempty"` - ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"` - - // Array-related, here for struct compactness - UniqueItems bool `json:"uniqueItems,omitempty" yaml:"uniqueItems,omitempty"` - // Number-related, here for struct compactness - ExclusiveMin bool `json:"exclusiveMinimum,omitempty" yaml:"exclusiveMinimum,omitempty"` - ExclusiveMax bool `json:"exclusiveMaximum,omitempty" yaml:"exclusiveMaximum,omitempty"` - // Properties - Nullable bool `json:"nullable,omitempty" yaml:"nullable,omitempty"` - ReadOnly bool `json:"readOnly,omitempty" yaml:"readOnly,omitempty"` - WriteOnly bool `json:"writeOnly,omitempty" yaml:"writeOnly,omitempty"` - AllowEmptyValue bool `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"` - Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` - XML *XML `json:"xml,omitempty" yaml:"xml,omitempty"` - - // Number - Min *float64 `json:"minimum,omitempty" yaml:"minimum,omitempty"` - Max *float64 `json:"maximum,omitempty" yaml:"maximum,omitempty"` - MultipleOf *float64 `json:"multipleOf,omitempty" yaml:"multipleOf,omitempty"` - - // String - MinLength uint64 `json:"minLength,omitempty" yaml:"minLength,omitempty"` - MaxLength *uint64 `json:"maxLength,omitempty" yaml:"maxLength,omitempty"` - Pattern string `json:"pattern,omitempty" yaml:"pattern,omitempty"` - - // Array - MinItems uint64 `json:"minItems,omitempty" yaml:"minItems,omitempty"` - MaxItems *uint64 `json:"maxItems,omitempty" yaml:"maxItems,omitempty"` - Items *SchemaRef `json:"items,omitempty" yaml:"items,omitempty"` - - // Object - Required []string `json:"required,omitempty" yaml:"required,omitempty"` - Properties Schemas `json:"properties,omitempty" yaml:"properties,omitempty"` - MinProps uint64 `json:"minProperties,omitempty" yaml:"minProperties,omitempty"` - MaxProps *uint64 `json:"maxProperties,omitempty" yaml:"maxProperties,omitempty"` - AdditionalProperties AdditionalProperties `json:"additionalProperties,omitempty" yaml:"additionalProperties,omitempty"` - Discriminator *Discriminator `json:"discriminator,omitempty" yaml:"discriminator,omitempty"` -} - -type Types []string - -func (types *Types) Is(typ string) bool { - return types != nil && len(*types) == 1 && (*types)[0] == typ -} - -func (types *Types) Slice() []string { - if types == nil { - return nil - } - return *types -} - -func (pTypes *Types) Includes(typ string) bool { - if pTypes == nil { - return false - } - types := *pTypes - for _, candidate := range types { - if candidate == typ { - return true - } - } - return false -} - -func (types *Types) Permits(typ string) bool { - if types == nil { - return true - } - return types.Includes(typ) -} - -func (pTypes *Types) MarshalJSON() ([]byte, error) { - x, err := pTypes.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -func (pTypes *Types) MarshalYAML() (any, error) { - if pTypes == nil { - return nil, nil - } - types := *pTypes - switch len(types) { - case 0: - return nil, nil - case 1: - return types[0], nil - default: - return []string(types), nil - } -} - -func (types *Types) UnmarshalJSON(data []byte) error { - var strings []string - if err := json.Unmarshal(data, &strings); err != nil { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return unmarshalError(err) - } - strings = []string{s} - } - *types = strings - return nil -} - -type AdditionalProperties struct { - Has *bool - Schema *SchemaRef -} - -// MarshalYAML returns the YAML encoding of AdditionalProperties. -func (addProps AdditionalProperties) MarshalYAML() (any, error) { - if x := addProps.Has; x != nil { - if *x { - return true, nil - } - return false, nil - } - if x := addProps.Schema; x != nil { - return x.MarshalYAML() - } - return nil, nil -} - -// MarshalJSON returns the JSON encoding of AdditionalProperties. -func (addProps AdditionalProperties) MarshalJSON() ([]byte, error) { - x, err := addProps.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// UnmarshalJSON sets AdditionalProperties to a copy of data. -func (addProps *AdditionalProperties) UnmarshalJSON(data []byte) error { - var x any - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - switch y := x.(type) { - case nil: - case bool: - addProps.Has = &y - case map[string]any: - if len(y) == 0 { - addProps.Schema = &SchemaRef{Value: &Schema{}} - } else { - buf := new(bytes.Buffer) - json.NewEncoder(buf).Encode(y) - if err := json.NewDecoder(buf).Decode(&addProps.Schema); err != nil { - return err - } - } - default: - return errors.New("cannot unmarshal additionalProperties: value must be either a schema object or a boolean") - } - return nil -} - -var _ jsonpointer.JSONPointable = (*Schema)(nil) - -func NewSchema() *Schema { - return &Schema{} -} - -// MarshalJSON returns the JSON encoding of Schema. -func (schema Schema) MarshalJSON() ([]byte, error) { - m, err := schema.MarshalYAML() - if err != nil { - return nil, err - } - - return json.Marshal(m) -} - -// MarshalYAML returns the YAML encoding of Schema. -func (schema Schema) MarshalYAML() (any, error) { - m := make(map[string]any, 36+len(schema.Extensions)) - for k, v := range schema.Extensions { - m[k] = v - } - - if x := schema.OneOf; len(x) != 0 { - m["oneOf"] = x - } - if x := schema.AnyOf; len(x) != 0 { - m["anyOf"] = x - } - if x := schema.AllOf; len(x) != 0 { - m["allOf"] = x - } - if x := schema.Not; x != nil { - m["not"] = x - } - if x := schema.Type; x != nil { - m["type"] = x - } - if x := schema.Title; len(x) != 0 { - m["title"] = x - } - if x := schema.Format; len(x) != 0 { - m["format"] = x - } - if x := schema.Description; len(x) != 0 { - m["description"] = x - } - if x := schema.Enum; len(x) != 0 { - m["enum"] = x - } - if x := schema.Default; x != nil { - m["default"] = x - } - if x := schema.Example; x != nil { - m["example"] = x - } - if x := schema.ExternalDocs; x != nil { - m["externalDocs"] = x - } - - // Array-related - if x := schema.UniqueItems; x { - m["uniqueItems"] = x - } - // Number-related - if x := schema.ExclusiveMin; x { - m["exclusiveMinimum"] = x - } - if x := schema.ExclusiveMax; x { - m["exclusiveMaximum"] = x - } - // Properties - if x := schema.Nullable; x { - m["nullable"] = x - } - if x := schema.ReadOnly; x { - m["readOnly"] = x - } - if x := schema.WriteOnly; x { - m["writeOnly"] = x - } - if x := schema.AllowEmptyValue; x { - m["allowEmptyValue"] = x - } - if x := schema.Deprecated; x { - m["deprecated"] = x - } - if x := schema.XML; x != nil { - m["xml"] = x - } - - // Number - if x := schema.Min; x != nil { - m["minimum"] = x - } - if x := schema.Max; x != nil { - m["maximum"] = x - } - if x := schema.MultipleOf; x != nil { - m["multipleOf"] = x - } - - // String - if x := schema.MinLength; x != 0 { - m["minLength"] = x - } - if x := schema.MaxLength; x != nil { - m["maxLength"] = x - } - if x := schema.Pattern; x != "" { - m["pattern"] = x - } - - // Array - if x := schema.MinItems; x != 0 { - m["minItems"] = x - } - if x := schema.MaxItems; x != nil { - m["maxItems"] = x - } - if x := schema.Items; x != nil { - m["items"] = x - } - - // Object - if x := schema.Required; len(x) != 0 { - m["required"] = x - } - if x := schema.Properties; len(x) != 0 { - m["properties"] = x - } - if x := schema.MinProps; x != 0 { - m["minProperties"] = x - } - if x := schema.MaxProps; x != nil { - m["maxProperties"] = x - } - if x := schema.AdditionalProperties; x.Has != nil || x.Schema != nil { - m["additionalProperties"] = &x - } - if x := schema.Discriminator; x != nil { - m["discriminator"] = x - } - - return m, nil -} - -// UnmarshalJSON sets Schema to a copy of data. -func (schema *Schema) UnmarshalJSON(data []byte) error { - type SchemaBis Schema - var x SchemaBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - - delete(x.Extensions, "oneOf") - delete(x.Extensions, "anyOf") - delete(x.Extensions, "allOf") - delete(x.Extensions, "not") - delete(x.Extensions, "type") - delete(x.Extensions, "title") - delete(x.Extensions, "format") - delete(x.Extensions, "description") - delete(x.Extensions, "enum") - delete(x.Extensions, "default") - delete(x.Extensions, "example") - delete(x.Extensions, "externalDocs") - - // Array-related - delete(x.Extensions, "uniqueItems") - // Number-related - delete(x.Extensions, "exclusiveMinimum") - delete(x.Extensions, "exclusiveMaximum") - // Properties - delete(x.Extensions, "nullable") - delete(x.Extensions, "readOnly") - delete(x.Extensions, "writeOnly") - delete(x.Extensions, "allowEmptyValue") - delete(x.Extensions, "deprecated") - delete(x.Extensions, "xml") - - // Number - delete(x.Extensions, "minimum") - delete(x.Extensions, "maximum") - delete(x.Extensions, "multipleOf") - - // String - delete(x.Extensions, "minLength") - delete(x.Extensions, "maxLength") - delete(x.Extensions, "pattern") - - // Array - delete(x.Extensions, "minItems") - delete(x.Extensions, "maxItems") - delete(x.Extensions, "items") - - // Object - delete(x.Extensions, "required") - delete(x.Extensions, "properties") - delete(x.Extensions, "minProperties") - delete(x.Extensions, "maxProperties") - delete(x.Extensions, "additionalProperties") - delete(x.Extensions, "discriminator") - - if len(x.Extensions) == 0 { - x.Extensions = nil - } - - *schema = Schema(x) - - if schema.Format == "date" { - // This is a fix for: https://github.com/getkin/kin-openapi/issues/697 - if eg, ok := schema.Example.(string); ok { - schema.Example = strings.TrimSuffix(eg, "T00:00:00Z") - } - } - return nil -} - -// JSONLookup implements https://pkg.go.dev/github.com/go-openapi/jsonpointer#JSONPointable -func (schema Schema) JSONLookup(token string) (any, error) { - switch token { - case "additionalProperties": - if addProps := schema.AdditionalProperties.Has; addProps != nil { - return *addProps, nil - } - if addProps := schema.AdditionalProperties.Schema; addProps != nil { - if addProps.Ref != "" { - return &Ref{Ref: addProps.Ref}, nil - } - return addProps.Value, nil - } - case "not": - if schema.Not != nil { - if schema.Not.Ref != "" { - return &Ref{Ref: schema.Not.Ref}, nil - } - return schema.Not.Value, nil - } - case "items": - if schema.Items != nil { - if schema.Items.Ref != "" { - return &Ref{Ref: schema.Items.Ref}, nil - } - return schema.Items.Value, nil - } - case "oneOf": - return schema.OneOf, nil - case "anyOf": - return schema.AnyOf, nil - case "allOf": - return schema.AllOf, nil - case "type": - return schema.Type, nil - case "title": - return schema.Title, nil - case "format": - return schema.Format, nil - case "description": - return schema.Description, nil - case "enum": - return schema.Enum, nil - case "default": - return schema.Default, nil - case "example": - return schema.Example, nil - case "externalDocs": - return schema.ExternalDocs, nil - case "uniqueItems": - return schema.UniqueItems, nil - case "exclusiveMin": - return schema.ExclusiveMin, nil - case "exclusiveMax": - return schema.ExclusiveMax, nil - case "nullable": - return schema.Nullable, nil - case "readOnly": - return schema.ReadOnly, nil - case "writeOnly": - return schema.WriteOnly, nil - case "allowEmptyValue": - return schema.AllowEmptyValue, nil - case "xml": - return schema.XML, nil - case "deprecated": - return schema.Deprecated, nil - case "min": - return schema.Min, nil - case "max": - return schema.Max, nil - case "multipleOf": - return schema.MultipleOf, nil - case "minLength": - return schema.MinLength, nil - case "maxLength": - return schema.MaxLength, nil - case "pattern": - return schema.Pattern, nil - case "minItems": - return schema.MinItems, nil - case "maxItems": - return schema.MaxItems, nil - case "required": - return schema.Required, nil - case "properties": - return schema.Properties, nil - case "minProps": - return schema.MinProps, nil - case "maxProps": - return schema.MaxProps, nil - case "discriminator": - return schema.Discriminator, nil - } - - v, _, err := jsonpointer.GetForToken(schema.Extensions, token) - return v, err -} - -func (schema *Schema) NewRef() *SchemaRef { - return &SchemaRef{ - Value: schema, - } -} - -func NewOneOfSchema(schemas ...*Schema) *Schema { - refs := make([]*SchemaRef, 0, len(schemas)) - for _, schema := range schemas { - refs = append(refs, &SchemaRef{Value: schema}) - } - return &Schema{ - OneOf: refs, - } -} - -func NewAnyOfSchema(schemas ...*Schema) *Schema { - refs := make([]*SchemaRef, 0, len(schemas)) - for _, schema := range schemas { - refs = append(refs, &SchemaRef{Value: schema}) - } - return &Schema{ - AnyOf: refs, - } -} - -func NewAllOfSchema(schemas ...*Schema) *Schema { - refs := make([]*SchemaRef, 0, len(schemas)) - for _, schema := range schemas { - refs = append(refs, &SchemaRef{Value: schema}) - } - return &Schema{ - AllOf: refs, - } -} - -func NewBoolSchema() *Schema { - return &Schema{ - Type: &Types{TypeBoolean}, - } -} - -func NewFloat64Schema() *Schema { - return &Schema{ - Type: &Types{TypeNumber}, - } -} - -func NewIntegerSchema() *Schema { - return &Schema{ - Type: &Types{TypeInteger}, - } -} - -func NewInt32Schema() *Schema { - return &Schema{ - Type: &Types{TypeInteger}, - Format: "int32", - } -} - -func NewInt64Schema() *Schema { - return &Schema{ - Type: &Types{TypeInteger}, - Format: "int64", - } -} - -func NewStringSchema() *Schema { - return &Schema{ - Type: &Types{TypeString}, - } -} - -func NewDateTimeSchema() *Schema { - return &Schema{ - Type: &Types{TypeString}, - Format: "date-time", - } -} - -func NewUUIDSchema() *Schema { - return &Schema{ - Type: &Types{TypeString}, - Format: "uuid", - } -} - -func NewBytesSchema() *Schema { - return &Schema{ - Type: &Types{TypeString}, - Format: "byte", - } -} - -func NewArraySchema() *Schema { - return &Schema{ - Type: &Types{TypeArray}, - } -} - -func NewObjectSchema() *Schema { - return &Schema{ - Type: &Types{TypeObject}, - Properties: make(Schemas), - } -} - -func (schema *Schema) WithNullable() *Schema { - schema.Nullable = true - return schema -} - -func (schema *Schema) WithMin(value float64) *Schema { - schema.Min = &value - return schema -} - -func (schema *Schema) WithMax(value float64) *Schema { - schema.Max = &value - return schema -} - -func (schema *Schema) WithExclusiveMin(value bool) *Schema { - schema.ExclusiveMin = value - return schema -} - -func (schema *Schema) WithExclusiveMax(value bool) *Schema { - schema.ExclusiveMax = value - return schema -} - -func (schema *Schema) WithEnum(values ...any) *Schema { - schema.Enum = values - return schema -} - -func (schema *Schema) WithDefault(defaultValue any) *Schema { - schema.Default = defaultValue - return schema -} - -func (schema *Schema) WithFormat(value string) *Schema { - schema.Format = value - return schema -} - -func (schema *Schema) WithLength(i int64) *Schema { - n := uint64(i) - schema.MinLength = n - schema.MaxLength = &n - return schema -} - -func (schema *Schema) WithMinLength(i int64) *Schema { - n := uint64(i) - schema.MinLength = n - return schema -} - -func (schema *Schema) WithMaxLength(i int64) *Schema { - n := uint64(i) - schema.MaxLength = &n - return schema -} - -func (schema *Schema) WithLengthDecodedBase64(i int64) *Schema { - n := uint64(i) - v := (n*8 + 5) / 6 - schema.MinLength = v - schema.MaxLength = &v - return schema -} - -func (schema *Schema) WithMinLengthDecodedBase64(i int64) *Schema { - n := uint64(i) - schema.MinLength = (n*8 + 5) / 6 - return schema -} - -func (schema *Schema) WithMaxLengthDecodedBase64(i int64) *Schema { - n := uint64(i) - schema.MinLength = (n*8 + 5) / 6 - return schema -} - -func (schema *Schema) WithPattern(pattern string) *Schema { - schema.Pattern = pattern - return schema -} - -func (schema *Schema) WithItems(value *Schema) *Schema { - schema.Items = &SchemaRef{ - Value: value, - } - return schema -} - -func (schema *Schema) WithMinItems(i int64) *Schema { - n := uint64(i) - schema.MinItems = n - return schema -} - -func (schema *Schema) WithMaxItems(i int64) *Schema { - n := uint64(i) - schema.MaxItems = &n - return schema -} - -func (schema *Schema) WithUniqueItems(unique bool) *Schema { - schema.UniqueItems = unique - return schema -} - -func (schema *Schema) WithProperty(name string, propertySchema *Schema) *Schema { - return schema.WithPropertyRef(name, &SchemaRef{ - Value: propertySchema, - }) -} - -func (schema *Schema) WithPropertyRef(name string, ref *SchemaRef) *Schema { - properties := schema.Properties - if properties == nil { - properties = make(Schemas) - schema.Properties = properties - } - properties[name] = ref - return schema -} - -func (schema *Schema) WithProperties(properties map[string]*Schema) *Schema { - result := make(Schemas, len(properties)) - for k, v := range properties { - result[k] = &SchemaRef{ - Value: v, - } - } - schema.Properties = result - return schema -} - -func (schema *Schema) WithRequired(required []string) *Schema { - schema.Required = required - return schema -} - -func (schema *Schema) WithMinProperties(i int64) *Schema { - n := uint64(i) - schema.MinProps = n - return schema -} - -func (schema *Schema) WithMaxProperties(i int64) *Schema { - n := uint64(i) - schema.MaxProps = &n - return schema -} - -func (schema *Schema) WithAnyAdditionalProperties() *Schema { - schema.AdditionalProperties = AdditionalProperties{Has: BoolPtr(true)} - return schema -} - -func (schema *Schema) WithoutAdditionalProperties() *Schema { - schema.AdditionalProperties = AdditionalProperties{Has: BoolPtr(false)} - return schema -} - -func (schema *Schema) WithAdditionalProperties(v *Schema) *Schema { - schema.AdditionalProperties = AdditionalProperties{} - if v != nil { - schema.AdditionalProperties.Schema = &SchemaRef{Value: v} - } - return schema -} - -func (schema *Schema) PermitsNull() bool { - return schema.Nullable || schema.Type.Includes("null") -} - -// IsEmpty tells whether schema is equivalent to the empty schema `{}`. -func (schema *Schema) IsEmpty() bool { - if schema.Type != nil || schema.Format != "" || len(schema.Enum) != 0 || - schema.UniqueItems || schema.ExclusiveMin || schema.ExclusiveMax || - schema.Nullable || schema.ReadOnly || schema.WriteOnly || schema.AllowEmptyValue || - schema.Min != nil || schema.Max != nil || schema.MultipleOf != nil || - schema.MinLength != 0 || schema.MaxLength != nil || schema.Pattern != "" || - schema.MinItems != 0 || schema.MaxItems != nil || - len(schema.Required) != 0 || - schema.MinProps != 0 || schema.MaxProps != nil { - return false - } - if n := schema.Not; n != nil && n.Value != nil && !n.Value.IsEmpty() { - return false - } - if ap := schema.AdditionalProperties.Schema; ap != nil && ap.Value != nil && !ap.Value.IsEmpty() { - return false - } - if apa := schema.AdditionalProperties.Has; apa != nil && !*apa { - return false - } - if items := schema.Items; items != nil && items.Value != nil && !items.Value.IsEmpty() { - return false - } - for _, s := range schema.Properties { - if ss := s.Value; ss != nil && !ss.IsEmpty() { - return false - } - } - for _, s := range schema.OneOf { - if ss := s.Value; ss != nil && !ss.IsEmpty() { - return false - } - } - for _, s := range schema.AnyOf { - if ss := s.Value; ss != nil && !ss.IsEmpty() { - return false - } - } - for _, s := range schema.AllOf { - if ss := s.Value; ss != nil && !ss.IsEmpty() { - return false - } - } - return true -} - -// Validate returns an error if Schema does not comply with the OpenAPI spec. -func (schema *Schema) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - _, err := schema.validate(ctx, []*Schema{}) - return err -} - -// returns the updated stack and an error if Schema does not comply with the OpenAPI spec. -func (schema *Schema) validate(ctx context.Context, stack []*Schema) ([]*Schema, error) { - validationOpts := getValidationOptions(ctx) - - for _, existing := range stack { - if existing == schema { - return stack, nil - } - } - stack = append(stack, schema) - - if schema.ReadOnly && schema.WriteOnly { - return stack, errors.New("a property MUST NOT be marked as both readOnly and writeOnly being true") - } - - for _, item := range schema.OneOf { - v := item.Value - if v == nil { - return stack, foundUnresolvedRef(item.Ref) - } - - var err error - if stack, err = v.validate(ctx, stack); err != nil { - return stack, err - } - } - - for _, item := range schema.AnyOf { - v := item.Value - if v == nil { - return stack, foundUnresolvedRef(item.Ref) - } - - var err error - if stack, err = v.validate(ctx, stack); err != nil { - return stack, err - } - } - - for _, item := range schema.AllOf { - v := item.Value - if v == nil { - return stack, foundUnresolvedRef(item.Ref) - } - - var err error - if stack, err = v.validate(ctx, stack); err != nil { - return stack, err - } - } - - if ref := schema.Not; ref != nil { - v := ref.Value - if v == nil { - return stack, foundUnresolvedRef(ref.Ref) - } - - var err error - if stack, err = v.validate(ctx, stack); err != nil { - return stack, err - } - } - - for _, schemaType := range schema.Type.Slice() { - switch schemaType { - case TypeBoolean: - case TypeNumber: - if format := schema.Format; len(format) > 0 { - switch format { - case "float", "double": - default: - if _, ok := SchemaNumberFormats[format]; !ok && validationOpts.schemaFormatValidationEnabled { - return stack, unsupportedFormat(format) - } - } - } - case TypeInteger: - if format := schema.Format; len(format) > 0 { - switch format { - case "int32", "int64": - default: - if _, ok := SchemaIntegerFormats[format]; !ok && validationOpts.schemaFormatValidationEnabled { - return stack, unsupportedFormat(format) - } - } - } - case TypeString: - if format := schema.Format; len(format) > 0 { - switch format { - // Supported by OpenAPIv3.0.3: - // https://spec.openapis.org/oas/v3.0.3 - case "byte", "binary", "date", "date-time", "password": - // In JSON Draft-07 (not validated yet though): - // https://json-schema.org/draft-07/json-schema-release-notes.html#formats - case "iri", "iri-reference", "uri-template", "idn-email", "idn-hostname": - case "json-pointer", "relative-json-pointer", "regex", "time": - // In JSON Draft 2019-09 (not validated yet though): - // https://json-schema.org/draft/2019-09/release-notes.html#format-vocabulary - case "duration", "uuid": - // Defined in some other specification - case "email", "hostname", "ipv4", "ipv6", "uri", "uri-reference": - default: - if _, ok := SchemaStringFormats[format]; !ok && validationOpts.schemaFormatValidationEnabled { - return stack, unsupportedFormat(format) - } - } - } - if !validationOpts.schemaPatternValidationDisabled && schema.Pattern != "" { - if _, err := schema.compilePattern(validationOpts.regexCompilerFunc); err != nil { - return stack, err - } - } - case TypeArray: - if schema.Items == nil { - return stack, errors.New("when schema type is 'array', schema 'items' must be non-null") - } - case TypeObject: - default: - return stack, fmt.Errorf("unsupported 'type' value %q", schemaType) - } - } - - if ref := schema.Items; ref != nil { - v := ref.Value - if v == nil { - return stack, foundUnresolvedRef(ref.Ref) - } - - var err error - if stack, err = v.validate(ctx, stack); err != nil { - return stack, err - } - } - - properties := make([]string, 0, len(schema.Properties)) - for name := range schema.Properties { - properties = append(properties, name) - } - sort.Strings(properties) - for _, name := range properties { - ref := schema.Properties[name] - v := ref.Value - if v == nil { - return stack, foundUnresolvedRef(ref.Ref) - } - - var err error - if stack, err = v.validate(ctx, stack); err != nil { - return stack, err - } - } - - if schema.AdditionalProperties.Has != nil && schema.AdditionalProperties.Schema != nil { - return stack, errors.New("additionalProperties are set to both boolean and schema") - } - if ref := schema.AdditionalProperties.Schema; ref != nil { - v := ref.Value - if v == nil { - return stack, foundUnresolvedRef(ref.Ref) - } - - var err error - if stack, err = v.validate(ctx, stack); err != nil { - return stack, err - } - } - - if v := schema.ExternalDocs; v != nil { - if err := v.Validate(ctx); err != nil { - return stack, fmt.Errorf("invalid external docs: %w", err) - } - } - - if v := schema.Default; v != nil && !validationOpts.schemaDefaultsValidationDisabled { - if err := schema.VisitJSON(v); err != nil { - return stack, fmt.Errorf("invalid default: %w", err) - } - } - - if x := schema.Example; x != nil && !validationOpts.examplesValidationDisabled { - if err := validateExampleValue(ctx, x, schema); err != nil { - return stack, fmt.Errorf("invalid example: %w", err) - } - } - - return stack, validateExtensions(ctx, schema.Extensions) -} - -func (schema *Schema) IsMatching(value any) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONBoolean(value bool) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONNumber(value float64) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONString(value string) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONArray(value []any) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONObject(value map[string]any) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) VisitJSON(value any, opts ...SchemaValidationOption) error { - settings := newSchemaValidationSettings(opts...) - return schema.visitJSON(settings, value) -} - -func (schema *Schema) visitJSON(settings *schemaValidationSettings, value any) (err error) { - switch value := value.(type) { - case nil: - // Don't use VisitJSONNull, as we still want to reach 'visitXOFOperations', since - // those could allow for a nullable value even though this one doesn't - if schema.PermitsNull() { - return - } - case float64: - if math.IsNaN(value) { - return ErrSchemaInputNaN - } - if math.IsInf(value, 0) { - return ErrSchemaInputInf - } - } - - if schema.IsEmpty() { - switch value.(type) { - case nil: - return schema.visitJSONNull(settings) - default: - return - } - } - - if err = schema.visitNotOperation(settings, value); err != nil { - return - } - var run bool - if err, run = schema.visitXOFOperations(settings, value); err != nil || !run { - return - } - if err = schema.visitEnumOperation(settings, value); err != nil { - return - } - - switch value := value.(type) { - case nil: - return schema.visitJSONNull(settings) - case bool: - return schema.visitJSONBoolean(settings, value) - case json.Number: - valueFloat64, err := value.Float64() - if err != nil { - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "type", - Reason: "cannot convert json.Number to float64", - customizeMessageError: settings.customizeMessageError, - Origin: err, - } - } - return schema.visitJSONNumber(settings, valueFloat64) - case int: - return schema.visitJSONNumber(settings, float64(value)) - case int32: - return schema.visitJSONNumber(settings, float64(value)) - case int64: - return schema.visitJSONNumber(settings, float64(value)) - case float64: - return schema.visitJSONNumber(settings, value) - case string: - return schema.visitJSONString(settings, value) - case []any: - return schema.visitJSONArray(settings, value) - case map[string]any: - return schema.visitJSONObject(settings, value) - case map[any]any: // for YAML cf. issue https://github.com/getkin/kin-openapi/issues/444 - values := make(map[string]any, len(value)) - for key, v := range value { - if k, ok := key.(string); ok { - values[k] = v - } - } - if len(value) == len(values) { - return schema.visitJSONObject(settings, values) - } - } - - // Catch slice of non-empty interface type - if reflect.TypeOf(value).Kind() == reflect.Slice { - valueR := reflect.ValueOf(value) - newValue := make([]any, 0, valueR.Len()) - for i := 0; i < valueR.Len(); i++ { - newValue = append(newValue, valueR.Index(i).Interface()) - } - return schema.visitJSONArray(settings, newValue) - } - - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "type", - Reason: fmt.Sprintf("unhandled value of type %T", value), - customizeMessageError: settings.customizeMessageError, - } -} - -func (schema *Schema) visitEnumOperation(settings *schemaValidationSettings, value any) (err error) { - if enum := schema.Enum; len(enum) != 0 { - for _, v := range enum { - switch c := value.(type) { - case json.Number: - var f float64 - if f, err = strconv.ParseFloat(c.String(), 64); err != nil { - return err - } - if v == f { - return - } - case int64: - if v == float64(c) { - return - } - default: - if reflect.DeepEqual(v, value) { - return - } - } - } - if settings.failfast { - return errSchema - } - allowedValues, _ := json.Marshal(enum) - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "enum", - Reason: fmt.Sprintf("value is not one of the allowed values %s", string(allowedValues)), - customizeMessageError: settings.customizeMessageError, - } - } - return -} - -func (schema *Schema) visitNotOperation(settings *schemaValidationSettings, value any) (err error) { - if ref := schema.Not; ref != nil { - v := ref.Value - if v == nil { - return foundUnresolvedRef(ref.Ref) - } - if err := v.visitJSON(settings, value); err == nil { - if settings.failfast { - return errSchema - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "not", - customizeMessageError: settings.customizeMessageError, - } - } - } - return -} - -// If the XOF operations pass successfully, abort further run of validation, as they will already be satisfied (unless the schema -// itself is badly specified -func (schema *Schema) visitXOFOperations(settings *schemaValidationSettings, value any) (err error, run bool) { - var visitedOneOf, visitedAnyOf, visitedAllOf bool - if v := schema.OneOf; len(v) > 0 { - var discriminatorRef string - if schema.Discriminator != nil { - pn := schema.Discriminator.PropertyName - if valuemap, okcheck := value.(map[string]any); okcheck { - discriminatorVal, okcheck := valuemap[pn] - if !okcheck { - return &SchemaError{ - Schema: schema, - SchemaField: "discriminator", - Reason: fmt.Sprintf("input does not contain the discriminator property %q", pn), - }, false - } - - discriminatorValString, okcheck := discriminatorVal.(string) - if !okcheck { - return &SchemaError{ - Value: discriminatorVal, - Schema: schema, - SchemaField: "discriminator", - Reason: fmt.Sprintf("value of discriminator property %q is not a string", pn), - }, false - } - - if discriminatorRef, okcheck = schema.Discriminator.Mapping[discriminatorValString]; len(schema.Discriminator.Mapping) > 0 && !okcheck { - return &SchemaError{ - Value: discriminatorVal, - Schema: schema, - SchemaField: "discriminator", - Reason: fmt.Sprintf("discriminator property %q has invalid value", pn), - }, false - } - } - } - - var ( - ok = 0 - validationErrors = multiErrorForOneOf{} - matchedOneOfIndices = make([]int, 0) - tempValue = value - ) - for idx, item := range v { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref), false - } - - if discriminatorRef != "" && discriminatorRef != item.Ref { - continue - } - - // make a deep copy to protect origin value from being injected default value that defined in mismatched oneOf schema - if settings.asreq || settings.asrep { - tempValue = deepcopy.Copy(value) - } - - if err := v.visitJSON(settings, tempValue); err != nil { - validationErrors = append(validationErrors, err) - continue - } - - matchedOneOfIndices = append(matchedOneOfIndices, idx) - ok++ - } - - if ok != 1 { - if settings.failfast { - return errSchema, false - } - e := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "oneOf", - customizeMessageError: settings.customizeMessageError, - } - if ok > 1 { - e.Origin = ErrOneOfConflict - e.Reason = fmt.Sprintf(`value matches more than one schema from "oneOf" (matches schemas at indices %v)`, matchedOneOfIndices) - } else { - e.Origin = fmt.Errorf("doesn't match schema due to: %w", validationErrors) - e.Reason = `value doesn't match any schema from "oneOf"` - } - - return e, false - } - - // run again to inject default value that defined in matched oneOf schema - if settings.asreq || settings.asrep { - _ = v[matchedOneOfIndices[0]].Value.visitJSON(settings, value) - } - visitedOneOf = true - } - - if v := schema.AnyOf; len(v) > 0 { - var ( - ok = false - matchedAnyOfIdx = 0 - tempValue = value - ) - for idx, item := range v { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref), false - } - // make a deep copy to protect origin value from being injected default value that defined in mismatched anyOf schema - if settings.asreq || settings.asrep { - tempValue = deepcopy.Copy(value) - } - if err := v.visitJSON(settings, tempValue); err == nil { - ok = true - matchedAnyOfIdx = idx - break - } - } - if !ok { - if settings.failfast { - return errSchema, false - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "anyOf", - Reason: `doesn't match any schema from "anyOf"`, - customizeMessageError: settings.customizeMessageError, - }, false - } - - _ = v[matchedAnyOfIdx].Value.visitJSON(settings, value) - visitedAnyOf = true - } - - for _, item := range schema.AllOf { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref), false - } - if err := v.visitJSON(settings, value); err != nil { - if settings.failfast { - return errSchema, false - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "allOf", - Reason: `doesn't match all schemas from "allOf"`, - Origin: err, - customizeMessageError: settings.customizeMessageError, - }, false - } - visitedAllOf = true - } - - run = !((visitedOneOf || visitedAnyOf || visitedAllOf) && value == nil) - return -} - -// The value is not considered in visitJSONNull because according to the spec -// "null is not supported as a type" unless `nullable` is also set to true -// https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#data-types -// https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object -func (schema *Schema) visitJSONNull(settings *schemaValidationSettings) (err error) { - if schema.PermitsNull() { - return - } - if settings.failfast { - return errSchema - } - return &SchemaError{ - Value: nil, - Schema: schema, - SchemaField: "nullable", - Reason: "Value is not nullable", - customizeMessageError: settings.customizeMessageError, - } -} - -func (schema *Schema) VisitJSONBoolean(value bool) error { - settings := newSchemaValidationSettings() - return schema.visitJSONBoolean(settings, value) -} - -func (schema *Schema) visitJSONBoolean(settings *schemaValidationSettings, value bool) (err error) { - if !schema.Type.Permits(TypeBoolean) { - return schema.expectedType(settings, value) - } - return -} - -func (schema *Schema) VisitJSONNumber(value float64) error { - settings := newSchemaValidationSettings() - return schema.visitJSONNumber(settings, value) -} - -func (schema *Schema) visitJSONNumber(settings *schemaValidationSettings, value float64) error { - var me MultiError - schemaType := schema.Type - requireInteger := false - if schemaType.Permits(TypeInteger) && !schemaType.Permits(TypeNumber) { - requireInteger = true - if bigFloat := big.NewFloat(value); !bigFloat.IsInt() { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "type", - Reason: "value must be an integer", - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - } else if !(schemaType.Permits(TypeInteger) || schemaType.Permits(TypeNumber)) { - return schema.expectedType(settings, value) - } - - // formats - var formatStrErr string - var formatErr error - format := schema.Format - if format != "" { - if requireInteger { - if f, ok := SchemaIntegerFormats[format]; ok { - if err := f.Validate(int64(value)); err != nil { - var reason string - schemaErr := &SchemaError{} - if errors.As(err, &schemaErr) { - reason = schemaErr.Reason - } else { - reason = err.Error() - } - formatStrErr = fmt.Sprintf(`integer doesn't match the format %q (%v)`, format, reason) - formatErr = fmt.Errorf("integer doesn't match the format %q: %w", format, err) - } - } - } else { - if f, ok := SchemaNumberFormats[format]; ok { - if err := f.Validate(value); err != nil { - var reason string - schemaErr := &SchemaError{} - if errors.As(err, &schemaErr) { - reason = schemaErr.Reason - } else { - reason = err.Error() - } - formatStrErr = fmt.Sprintf(`number doesn't match the format %q (%v)`, format, reason) - formatErr = fmt.Errorf("number doesn't match the format %q: %w", format, err) - } - } - } - } - - if formatStrErr != "" || formatErr != nil { - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "format", - Reason: formatStrErr, - Origin: formatErr, - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "exclusiveMinimum" - if v := schema.ExclusiveMin; v && !(*schema.Min < value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "exclusiveMinimum", - Reason: fmt.Sprintf("number must be more than %g", *schema.Min), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "exclusiveMaximum" - if v := schema.ExclusiveMax; v && !(*schema.Max > value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "exclusiveMaximum", - Reason: fmt.Sprintf("number must be less than %g", *schema.Max), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "minimum" - if v := schema.Min; v != nil && !(*v <= value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "minimum", - Reason: fmt.Sprintf("number must be at least %g", *v), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "maximum" - if v := schema.Max; v != nil && !(*v >= value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "maximum", - Reason: fmt.Sprintf("number must be at most %g", *v), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "multipleOf" - if v := schema.MultipleOf; v != nil { - // "A numeric instance is valid only if division by this keyword's - // value results in an integer." - if bigFloat := big.NewFloat(value / *v); !bigFloat.IsInt() { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "multipleOf", - Reason: fmt.Sprintf("number must be a multiple of %g", *v), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - } - - if len(me) > 0 { - return me - } - - return nil -} - -func (schema *Schema) VisitJSONString(value string) error { - settings := newSchemaValidationSettings() - return schema.visitJSONString(settings, value) -} - -func (schema *Schema) visitJSONString(settings *schemaValidationSettings, value string) error { - if !schema.Type.Permits(TypeString) { - return schema.expectedType(settings, value) - } - - var me MultiError - - // "minLength" and "maxLength" - minLength := schema.MinLength - maxLength := schema.MaxLength - if minLength != 0 || maxLength != nil { - // JSON schema string lengths are UTF-16, not UTF-8! - length := int64(0) - for _, r := range value { - if utf16.IsSurrogate(r) { - length += 2 - } else { - length++ - } - } - if minLength != 0 && length < int64(minLength) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "minLength", - Reason: fmt.Sprintf("minimum string length is %d", minLength), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - if maxLength != nil && length > int64(*maxLength) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "maxLength", - Reason: fmt.Sprintf("maximum string length is %d", *maxLength), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - } - - // "pattern" - if !settings.patternValidationDisabled && schema.Pattern != "" { - cpiface, _ := compiledPatterns.Load(schema.Pattern) - cp, _ := cpiface.(RegexMatcher) - if cp == nil { - var err error - if cp, err = schema.compilePattern(settings.regexCompiler); err != nil { - if !settings.multiError { - return err - } - me = append(me, err) - } - } - if !cp.MatchString(value) { - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "pattern", - Reason: fmt.Sprintf(`string doesn't match the regular expression "%s"`, schema.Pattern), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - } - - // "format" - var formatStrErr string - var formatErr error - if format := schema.Format; format != "" { - if f, ok := SchemaStringFormats[format]; ok { - if err := f.Validate(value); err != nil { - var reason string - schemaErr := &SchemaError{} - if errors.As(err, &schemaErr) { - reason = schemaErr.Reason - } else { - reason = err.Error() - } - formatStrErr = fmt.Sprintf(`string doesn't match the format %q (%v)`, format, reason) - formatErr = fmt.Errorf("string doesn't match the format %q: %w", format, err) - } - } - } - if formatStrErr != "" || formatErr != nil { - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "format", - Reason: formatStrErr, - Origin: formatErr, - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - - } - - if len(me) > 0 { - return me - } - - return nil -} - -func (schema *Schema) VisitJSONArray(value []any) error { - settings := newSchemaValidationSettings() - return schema.visitJSONArray(settings, value) -} - -func (schema *Schema) visitJSONArray(settings *schemaValidationSettings, value []any) error { - if !schema.Type.Permits(TypeArray) { - return schema.expectedType(settings, value) - } - - var me MultiError - - lenValue := int64(len(value)) - - // "minItems" - if v := schema.MinItems; v != 0 && lenValue < int64(v) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "minItems", - Reason: fmt.Sprintf("minimum number of items is %d", v), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "maxItems" - if v := schema.MaxItems; v != nil && lenValue > int64(*v) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "maxItems", - Reason: fmt.Sprintf("maximum number of items is %d", *v), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "uniqueItems" - if sliceUniqueItemsChecker == nil { - sliceUniqueItemsChecker = isSliceOfUniqueItems - } - if v := schema.UniqueItems; v && !sliceUniqueItemsChecker(value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "uniqueItems", - Reason: "duplicate items found", - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "items" - if itemSchemaRef := schema.Items; itemSchemaRef != nil { - itemSchema := itemSchemaRef.Value - if itemSchema == nil { - return foundUnresolvedRef(itemSchemaRef.Ref) - } - for i, item := range value { - if err := itemSchema.visitJSON(settings, item); err != nil { - err = markSchemaErrorIndex(err, i) - if !settings.multiError { - return err - } - if itemMe, ok := err.(MultiError); ok { - me = append(me, itemMe...) - } else { - me = append(me, err) - } - } - } - } - - if len(me) > 0 { - return me - } - - return nil -} - -func (schema *Schema) VisitJSONObject(value map[string]any) error { - settings := newSchemaValidationSettings() - return schema.visitJSONObject(settings, value) -} - -func (schema *Schema) visitJSONObject(settings *schemaValidationSettings, value map[string]any) error { - if !schema.Type.Permits(TypeObject) { - return schema.expectedType(settings, value) - } - - var me MultiError - - if settings.asreq || settings.asrep { - properties := make([]string, 0, len(schema.Properties)) - for propName := range schema.Properties { - properties = append(properties, propName) - } - sort.Strings(properties) - for _, propName := range properties { - propSchema := schema.Properties[propName] - reqRO := settings.asreq && propSchema.Value.ReadOnly && !settings.readOnlyValidationDisabled - repWO := settings.asrep && propSchema.Value.WriteOnly && !settings.writeOnlyValidationDisabled - - if f := settings.defaultsSet; f != nil && value[propName] == nil { - if dflt := propSchema.Value.Default; dflt != nil && !reqRO && !repWO { - value[propName] = dflt - settings.onceSettingDefaults.Do(f) - } - } - - if value[propName] != nil { - if reqRO { - me = append(me, fmt.Errorf("readOnly property %q in request", propName)) - } else if repWO { - me = append(me, fmt.Errorf("writeOnly property %q in response", propName)) - } - } - } - } - - // "properties" - properties := schema.Properties - lenValue := int64(len(value)) - - // "minProperties" - if v := schema.MinProps; v != 0 && lenValue < int64(v) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "minProperties", - Reason: fmt.Sprintf("there must be at least %d properties", v), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "maxProperties" - if v := schema.MaxProps; v != nil && lenValue > int64(*v) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "maxProperties", - Reason: fmt.Sprintf("there must be at most %d properties", *v), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "additionalProperties" - var additionalProperties *Schema - if ref := schema.AdditionalProperties.Schema; ref != nil { - additionalProperties = ref.Value - } - keys := make([]string, 0, len(value)) - for k := range value { - keys = append(keys, k) - } - sort.Strings(keys) - for _, k := range keys { - v := value[k] - if properties != nil { - propertyRef := properties[k] - if propertyRef != nil { - p := propertyRef.Value - if p == nil { - return foundUnresolvedRef(propertyRef.Ref) - } - if err := p.visitJSON(settings, v); err != nil { - if settings.failfast { - return errSchema - } - err = markSchemaErrorKey(err, k) - if !settings.multiError { - return err - } - if v, ok := err.(MultiError); ok { - me = append(me, v...) - continue - } - me = append(me, err) - } - continue - } - } - if allowed := schema.AdditionalProperties.Has; allowed == nil || *allowed { - if additionalProperties != nil { - if err := additionalProperties.visitJSON(settings, v); err != nil { - if settings.failfast { - return errSchema - } - err = markSchemaErrorKey(err, k) - if !settings.multiError { - return err - } - if v, ok := err.(MultiError); ok { - me = append(me, v...) - continue - } - me = append(me, err) - } - } - continue - } - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "properties", - Reason: fmt.Sprintf("property %q is unsupported", k), - customizeMessageError: settings.customizeMessageError, - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "required" - for _, k := range schema.Required { - if _, ok := value[k]; !ok { - if s := schema.Properties[k]; s != nil && s.Value.ReadOnly && settings.asreq { - continue - } - if s := schema.Properties[k]; s != nil && s.Value.WriteOnly && settings.asrep { - continue - } - if settings.failfast { - return errSchema - } - err := markSchemaErrorKey(&SchemaError{ - Value: value, - Schema: schema, - SchemaField: "required", - Reason: fmt.Sprintf("property %q is missing", k), - customizeMessageError: settings.customizeMessageError, - }, k) - if !settings.multiError { - return err - } - me = append(me, err) - } - } - - if len(me) > 0 { - return me - } - - return nil -} - -func (schema *Schema) expectedType(settings *schemaValidationSettings, value any) error { - if settings.failfast { - return errSchema - } - - a := "a" - var x string - schemaTypes := (*schema.Type) - if len(schemaTypes) == 1 { - x = schemaTypes[0] - switch x { - case TypeArray, TypeObject, TypeInteger: - a = "an" - } - } else { - a = "one of" - x = strings.Join(schemaTypes, ", ") - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "type", - Reason: fmt.Sprintf("value must be %s %s", a, x), - customizeMessageError: settings.customizeMessageError, - } -} - -// SchemaError is an error that occurs during schema validation. -type SchemaError struct { - // Value is the value that failed validation. - Value any - // reversePath is the path to the value that failed validation. - reversePath []string - // Schema is the schema that failed validation. - Schema *Schema - // SchemaField is the field of the schema that failed validation. - SchemaField string - // Reason is a human-readable message describing the error. - // The message should never include the original value to prevent leakage of potentially sensitive inputs in error messages. - Reason string - // Origin is the original error that caused this error. - Origin error - // customizeMessageError is a function that can be used to customize the error message. - customizeMessageError func(err *SchemaError) string -} - -var _ interface{ Unwrap() error } = SchemaError{} - -func markSchemaErrorKey(err error, key string) error { - - if v, ok := err.(*SchemaError); ok { - v.reversePath = append(v.reversePath, key) - if v.Origin != nil { - if unwrapped := errors.Unwrap(v.Origin); unwrapped != nil { - if me, ok := unwrapped.(multiErrorForOneOf); ok { - _ = markSchemaErrorKey(MultiError(me), key) - } - } - } - return v - } - if v, ok := err.(MultiError); ok { - for _, e := range v { - _ = markSchemaErrorKey(e, key) - } - return v - } - return err -} - -func markSchemaErrorIndex(err error, index int) error { - return markSchemaErrorKey(err, strconv.FormatInt(int64(index), 10)) -} - -func (err *SchemaError) JSONPointer() []string { - reversePath := err.reversePath - path := append([]string(nil), reversePath...) - for left, right := 0, len(path)-1; left < right; left, right = left+1, right-1 { - path[left], path[right] = path[right], path[left] - } - return path -} - -func (err *SchemaError) Error() string { - if err.customizeMessageError != nil { - if msg := err.customizeMessageError(err); msg != "" { - return msg - } - } - - buf := bytes.NewBuffer(make([]byte, 0, 256)) - - if len(err.reversePath) > 0 { - buf.WriteString(`Error at "`) - reversePath := err.reversePath - for i := len(reversePath) - 1; i >= 0; i-- { - buf.WriteByte('/') - buf.WriteString(reversePath[i]) - } - buf.WriteString(`": `) - } - - if err.Origin != nil { - buf.WriteString(err.Origin.Error()) - - return buf.String() - } - - reason := err.Reason - if reason == "" { - buf.WriteString(`Doesn't match schema "`) - buf.WriteString(err.SchemaField) - buf.WriteString(`"`) - } else { - buf.WriteString(reason) - } - - if !SchemaErrorDetailsDisabled { - buf.WriteString("\nSchema:\n ") - encoder := json.NewEncoder(buf) - encoder.SetIndent(" ", " ") - if err := encoder.Encode(err.Schema); err != nil { - panic(err) - } - buf.WriteString("\nValue:\n ") - if err := encoder.Encode(err.Value); err != nil { - panic(err) - } - } - - return buf.String() -} - -func (err SchemaError) Unwrap() error { - return err.Origin -} - -func isSliceOfUniqueItems(xs []any) bool { - s := len(xs) - m := make(map[string]struct{}, s) - for _, x := range xs { - // The input slice is converted from a JSON string, there shall - // have no error when convert it back. - key, _ := json.Marshal(&x) - m[string(key)] = struct{}{} - } - return s == len(m) -} - -// SliceUniqueItemsChecker is an function used to check if an given slice -// have unique items. -type SliceUniqueItemsChecker func(items []any) bool - -// By default using predefined func isSliceOfUniqueItems which make use of -// json.Marshal to generate a key for map used to check if a given slice -// have unique items. -var sliceUniqueItemsChecker SliceUniqueItemsChecker = isSliceOfUniqueItems - -// RegisterArrayUniqueItemsChecker is used to register a customized function -// used to check if JSON array have unique items. -func RegisterArrayUniqueItemsChecker(fn SliceUniqueItemsChecker) { - sliceUniqueItemsChecker = fn -} - -func unsupportedFormat(format string) error { - return fmt.Errorf("unsupported 'format' value %q", format) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/schema_formats.go b/vendor/github.com/getkin/kin-openapi/openapi3/schema_formats.go deleted file mode 100644 index 023c2669e..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/schema_formats.go +++ /dev/null @@ -1,169 +0,0 @@ -package openapi3 - -import ( - "fmt" - "math" - "net/netip" - "regexp" -) - -type ( - // FormatValidator is an interface for custom format validators. - FormatValidator[T any] interface { - Validate(value T) error - } - // StringFormatValidator is a type alias for FormatValidator[string] - StringFormatValidator = FormatValidator[string] - // NumberFormatValidator is a type alias for FormatValidator[float64] - NumberFormatValidator = FormatValidator[float64] - // IntegerFormatValidator is a type alias for FormatValidator[int64] - IntegerFormatValidator = FormatValidator[int64] -) - -var ( - // SchemaStringFormats is a map of custom string format validators. - SchemaStringFormats = make(map[string]StringFormatValidator) - // SchemaNumberFormats is a map of custom number format validators. - SchemaNumberFormats = make(map[string]NumberFormatValidator) - // SchemaIntegerFormats is a map of custom integer format validators. - SchemaIntegerFormats = make(map[string]IntegerFormatValidator) -) - -const ( - // FormatOfStringForUUIDOfRFC4122 is an optional predefined format for UUID v1-v5 as specified by RFC4122 - FormatOfStringForUUIDOfRFC4122 = `^(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$` - - // FormatOfStringForEmail pattern catches only some suspiciously wrong-looking email addresses. - // Use DefineStringFormat(...) if you need something stricter. - FormatOfStringForEmail = `^[^@]+@[^@<>",\s]+$` - - // FormatOfStringByte is a regexp for base64-encoded characters, for example, "U3dhZ2dlciByb2Nrcw==" - FormatOfStringByte = `(^$|^[a-zA-Z0-9+/\-_]*=*$)` - - // FormatOfStringDate is a RFC3339 date format regexp, for example "2017-07-21". - FormatOfStringDate = `^[0-9]{4}-(0[0-9]|10|11|12)-([0-2][0-9]|30|31)$` - - // FormatOfStringDateTime is a RFC3339 date-time format regexp, for example "2017-07-21T17:32:28Z". - FormatOfStringDateTime = `^[0-9]{4}-(0[0-9]|10|11|12)-([0-2][0-9]|30|31)T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?(Z|(\+|-)[0-9]{2}:[0-9]{2})?$` -) - -func init() { - DefineStringFormatValidator("byte", NewRegexpFormatValidator(FormatOfStringByte)) - DefineStringFormatValidator("date", NewRegexpFormatValidator(FormatOfStringDate)) - DefineStringFormatValidator("date-time", NewRegexpFormatValidator(FormatOfStringDateTime)) - DefineIntegerFormatValidator("int32", NewRangeFormatValidator(int64(math.MinInt32), int64(math.MaxInt32))) - DefineIntegerFormatValidator("int64", NewRangeFormatValidator(int64(math.MinInt64), int64(math.MaxInt64))) -} - -// DefineIPv4Format opts in ipv4 format validation on top of OAS 3 spec -func DefineIPv4Format() { - DefineStringFormatValidator("ipv4", NewIPValidator(true)) -} - -// DefineIPv6Format opts in ipv6 format validation on top of OAS 3 spec -func DefineIPv6Format() { - DefineStringFormatValidator("ipv6", NewIPValidator(false)) -} - -type stringRegexpFormatValidator struct { - re *regexp.Regexp -} - -func (s stringRegexpFormatValidator) Validate(value string) error { - if !s.re.MatchString(value) { - return fmt.Errorf(`string doesn't match pattern "%s"`, s.re.String()) - } - return nil -} - -type callbackValidator[T any] struct { - fn func(T) error -} - -func (c callbackValidator[T]) Validate(value T) error { - return c.fn(value) -} - -type rangeFormat[T int64 | float64] struct { - min, max T -} - -func (r rangeFormat[T]) Validate(value T) error { - if value < r.min || value > r.max { - return fmt.Errorf("value should be between %v and %v", r.min, r.max) - } - return nil -} - -// NewRangeFormatValidator creates a new FormatValidator that validates the value is within a given range. -func NewRangeFormatValidator[T int64 | float64](min, max T) FormatValidator[T] { - return rangeFormat[T]{min: min, max: max} -} - -// NewRegexpFormatValidator creates a new FormatValidator that uses a regular expression to validate the value. -func NewRegexpFormatValidator(pattern string) StringFormatValidator { - re, err := regexp.Compile(pattern) - if err != nil { - err := fmt.Errorf("string regexp format has invalid pattern %q: %w", pattern, err) - panic(err) - } - return stringRegexpFormatValidator{re: re} -} - -// NewCallbackValidator creates a new FormatValidator that uses a callback function to validate the value. -func NewCallbackValidator[T any](fn func(T) error) FormatValidator[T] { - return callbackValidator[T]{fn: fn} -} - -// DefineStringFormatValidator defines a custom format validator for a given string format. -func DefineStringFormatValidator(name string, validator StringFormatValidator) { - SchemaStringFormats[name] = validator -} - -// DefineNumberFormatValidator defines a custom format validator for a given number format. -func DefineNumberFormatValidator(name string, validator NumberFormatValidator) { - SchemaNumberFormats[name] = validator -} - -// DefineIntegerFormatValidator defines a custom format validator for a given integer format. -func DefineIntegerFormatValidator(name string, validator IntegerFormatValidator) { - SchemaIntegerFormats[name] = validator -} - -// DefineStringFormat defines a regexp pattern for a given string format -// Deprecated: Use openapi3.DefineStringFormatValidator(name, NewRegexpFormatValidator(pattern)) instead. -func DefineStringFormat(name string, pattern string) { - DefineStringFormatValidator(name, NewRegexpFormatValidator(pattern)) -} - -// DefineStringFormatCallback defines a callback function for a given string format -// Deprecated: Use openapi3.DefineStringFormatValidator(name, NewCallbackValidator(fn)) instead. -func DefineStringFormatCallback(name string, callback func(string) error) { - DefineStringFormatValidator(name, NewCallbackValidator(callback)) -} - -// NewIPValidator creates a new FormatValidator that validates the value is an IP address. -func NewIPValidator(isIPv4 bool) FormatValidator[string] { - return callbackValidator[string]{fn: func(ip string) error { - addr, err := netip.ParseAddr(ip) - if err != nil { - return &SchemaError{ - Value: ip, - Reason: "Not an IP address", - } - } - if isIPv4 && !addr.Is4() { - return &SchemaError{ - Value: ip, - Reason: "Not an IPv4 address (it's IPv6)", - } - } - if !isIPv4 && !addr.Is6() { - return &SchemaError{ - Value: ip, - Reason: "Not an IPv6 address (it's IPv4)", - } - } - return nil - }} -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/schema_pattern.go b/vendor/github.com/getkin/kin-openapi/openapi3/schema_pattern.go deleted file mode 100644 index 581971378..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/schema_pattern.go +++ /dev/null @@ -1,35 +0,0 @@ -package openapi3 - -import ( - "fmt" - "regexp" -) - -var patRewriteCodepoints = regexp.MustCompile(`(?P\\u)(?P[0-9A-F]{4})`) - -// See https://pkg.go.dev/regexp/syntax -func intoGoRegexp(re string) string { - return patRewriteCodepoints.ReplaceAllString(re, `\x{${code}}`) -} - -// NOTE: racey WRT [writes to schema.Pattern] vs [reads schema.Pattern then writes to compiledPatterns] -func (schema *Schema) compilePattern(c RegexCompilerFunc) (cp RegexMatcher, err error) { - pattern := schema.Pattern - if c != nil { - cp, err = c(pattern) - } else { - cp, err = regexp.Compile(intoGoRegexp(pattern)) - } - if err != nil { - err = &SchemaError{ - Schema: schema, - SchemaField: "pattern", - Origin: err, - Reason: fmt.Sprintf("cannot compile pattern %q: %v", pattern, err), - } - return - } - - var _ bool = compiledPatterns.CompareAndSwap(pattern, nil, cp) - return -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/schema_validation_settings.go b/vendor/github.com/getkin/kin-openapi/openapi3/schema_validation_settings.go deleted file mode 100644 index e9c1422bd..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/schema_validation_settings.go +++ /dev/null @@ -1,92 +0,0 @@ -package openapi3 - -import ( - "sync" -) - -// SchemaValidationOption describes options a user has when validating request / response bodies. -type SchemaValidationOption func(*schemaValidationSettings) - -type RegexCompilerFunc func(expr string) (RegexMatcher, error) - -type RegexMatcher interface { - MatchString(s string) bool -} - -type schemaValidationSettings struct { - failfast bool - multiError bool - asreq, asrep bool // exclusive (XOR) fields - formatValidationEnabled bool - patternValidationDisabled bool - readOnlyValidationDisabled bool - writeOnlyValidationDisabled bool - - regexCompiler RegexCompilerFunc - - onceSettingDefaults sync.Once - defaultsSet func() - - customizeMessageError func(err *SchemaError) string -} - -// FailFast returns schema validation errors quicker. -func FailFast() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.failfast = true } -} - -func MultiErrors() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.multiError = true } -} - -func VisitAsRequest() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.asreq, s.asrep = true, false } -} - -func VisitAsResponse() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.asreq, s.asrep = false, true } -} - -// EnableFormatValidation setting makes Validate not return an error when validating documents that mention schema formats that are not defined by the OpenAPIv3 specification. -func EnableFormatValidation() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.formatValidationEnabled = true } -} - -// DisablePatternValidation setting makes Validate not return an error when validating patterns that are not supported by the Go regexp engine. -func DisablePatternValidation() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.patternValidationDisabled = true } -} - -// DisableReadOnlyValidation setting makes Validate not return an error when validating properties marked as read-only -func DisableReadOnlyValidation() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.readOnlyValidationDisabled = true } -} - -// DisableWriteOnlyValidation setting makes Validate not return an error when validating properties marked as write-only -func DisableWriteOnlyValidation() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.writeOnlyValidationDisabled = true } -} - -// DefaultsSet executes the given callback (once) IFF schema validation set default values. -func DefaultsSet(f func()) SchemaValidationOption { - return func(s *schemaValidationSettings) { s.defaultsSet = f } -} - -// SetSchemaErrorMessageCustomizer allows to override the schema error message. -// If the passed function returns an empty string, it returns to the previous Error() implementation. -func SetSchemaErrorMessageCustomizer(f func(err *SchemaError) string) SchemaValidationOption { - return func(s *schemaValidationSettings) { s.customizeMessageError = f } -} - -// SetSchemaRegexCompiler allows to override the regex implementation used to validate field "pattern". -func SetSchemaRegexCompiler(c RegexCompilerFunc) SchemaValidationOption { - return func(s *schemaValidationSettings) { s.regexCompiler = c } -} - -func newSchemaValidationSettings(opts ...SchemaValidationOption) *schemaValidationSettings { - settings := &schemaValidationSettings{} - for _, opt := range opts { - opt(settings) - } - return settings -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/security_requirements.go b/vendor/github.com/getkin/kin-openapi/openapi3/security_requirements.go deleted file mode 100644 index 87891c954..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/security_requirements.go +++ /dev/null @@ -1,51 +0,0 @@ -package openapi3 - -import ( - "context" -) - -type SecurityRequirements []SecurityRequirement - -func NewSecurityRequirements() *SecurityRequirements { - return &SecurityRequirements{} -} - -func (srs *SecurityRequirements) With(securityRequirement SecurityRequirement) *SecurityRequirements { - *srs = append(*srs, securityRequirement) - return srs -} - -// Validate returns an error if SecurityRequirements does not comply with the OpenAPI spec. -func (srs SecurityRequirements) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - for _, security := range srs { - if err := security.Validate(ctx); err != nil { - return err - } - } - return nil -} - -// SecurityRequirement is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object -type SecurityRequirement map[string][]string - -func NewSecurityRequirement() SecurityRequirement { - return make(SecurityRequirement) -} - -func (security SecurityRequirement) Authenticate(provider string, scopes ...string) SecurityRequirement { - if len(scopes) == 0 { - scopes = []string{} // Forces the variable to be encoded as an array instead of null - } - security[provider] = scopes - return security -} - -// Validate returns an error if SecurityRequirement does not comply with the OpenAPI spec. -func (security *SecurityRequirement) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/security_scheme.go b/vendor/github.com/getkin/kin-openapi/openapi3/security_scheme.go deleted file mode 100644 index b5c94b618..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/security_scheme.go +++ /dev/null @@ -1,429 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/url" -) - -// SecurityScheme is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-scheme-object -type SecurityScheme struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Type string `json:"type,omitempty" yaml:"type,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Name string `json:"name,omitempty" yaml:"name,omitempty"` - In string `json:"in,omitempty" yaml:"in,omitempty"` - Scheme string `json:"scheme,omitempty" yaml:"scheme,omitempty"` - BearerFormat string `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"` - Flows *OAuthFlows `json:"flows,omitempty" yaml:"flows,omitempty"` - OpenIdConnectUrl string `json:"openIdConnectUrl,omitempty" yaml:"openIdConnectUrl,omitempty"` -} - -func NewSecurityScheme() *SecurityScheme { - return &SecurityScheme{} -} - -func NewCSRFSecurityScheme() *SecurityScheme { - return &SecurityScheme{ - Type: "apiKey", - In: "header", - Name: "X-XSRF-TOKEN", - } -} - -func NewOIDCSecurityScheme(oidcUrl string) *SecurityScheme { - return &SecurityScheme{ - Type: "openIdConnect", - OpenIdConnectUrl: oidcUrl, - } -} - -func NewJWTSecurityScheme() *SecurityScheme { - return &SecurityScheme{ - Type: "http", - Scheme: "bearer", - BearerFormat: "JWT", - } -} - -// MarshalJSON returns the JSON encoding of SecurityScheme. -func (ss SecurityScheme) MarshalJSON() ([]byte, error) { - x, err := ss.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of SecurityScheme. -func (ss SecurityScheme) MarshalYAML() (any, error) { - m := make(map[string]any, 8+len(ss.Extensions)) - for k, v := range ss.Extensions { - m[k] = v - } - if x := ss.Type; x != "" { - m["type"] = x - } - if x := ss.Description; x != "" { - m["description"] = x - } - if x := ss.Name; x != "" { - m["name"] = x - } - if x := ss.In; x != "" { - m["in"] = x - } - if x := ss.Scheme; x != "" { - m["scheme"] = x - } - if x := ss.BearerFormat; x != "" { - m["bearerFormat"] = x - } - if x := ss.Flows; x != nil { - m["flows"] = x - } - if x := ss.OpenIdConnectUrl; x != "" { - m["openIdConnectUrl"] = x - } - return m, nil -} - -// UnmarshalJSON sets SecurityScheme to a copy of data. -func (ss *SecurityScheme) UnmarshalJSON(data []byte) error { - type SecuritySchemeBis SecurityScheme - var x SecuritySchemeBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "type") - delete(x.Extensions, "description") - delete(x.Extensions, "name") - delete(x.Extensions, "in") - delete(x.Extensions, "scheme") - delete(x.Extensions, "bearerFormat") - delete(x.Extensions, "flows") - delete(x.Extensions, "openIdConnectUrl") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *ss = SecurityScheme(x) - return nil -} - -func (ss *SecurityScheme) WithType(value string) *SecurityScheme { - ss.Type = value - return ss -} - -func (ss *SecurityScheme) WithDescription(value string) *SecurityScheme { - ss.Description = value - return ss -} - -func (ss *SecurityScheme) WithName(value string) *SecurityScheme { - ss.Name = value - return ss -} - -func (ss *SecurityScheme) WithIn(value string) *SecurityScheme { - ss.In = value - return ss -} - -func (ss *SecurityScheme) WithScheme(value string) *SecurityScheme { - ss.Scheme = value - return ss -} - -func (ss *SecurityScheme) WithBearerFormat(value string) *SecurityScheme { - ss.BearerFormat = value - return ss -} - -// Validate returns an error if SecurityScheme does not comply with the OpenAPI spec. -func (ss *SecurityScheme) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - hasIn := false - hasBearerFormat := false - hasFlow := false - switch ss.Type { - case "apiKey": - hasIn = true - case "http": - scheme := ss.Scheme - switch scheme { - case "bearer": - hasBearerFormat = true - case "basic", "negotiate", "digest": - default: - return fmt.Errorf("security scheme of type 'http' has invalid 'scheme' value %q", scheme) - } - case "oauth2": - hasFlow = true - case "openIdConnect": - if ss.OpenIdConnectUrl == "" { - return fmt.Errorf("no OIDC URL found for openIdConnect security scheme %q", ss.Name) - } - default: - return fmt.Errorf("security scheme 'type' can't be %q", ss.Type) - } - - // Validate "in" and "name" - if hasIn { - switch ss.In { - case "query", "header", "cookie": - default: - return fmt.Errorf("security scheme of type 'apiKey' should have 'in'. It can be 'query', 'header' or 'cookie', not %q", ss.In) - } - if ss.Name == "" { - return errors.New("security scheme of type 'apiKey' should have 'name'") - } - } else if len(ss.In) > 0 { - return fmt.Errorf("security scheme of type %q can't have 'in'", ss.Type) - } else if len(ss.Name) > 0 { - return fmt.Errorf("security scheme of type %q can't have 'name'", ss.Type) - } - - // Validate "format" - // "bearerFormat" is an arbitrary string so we only check if the scheme supports it - if !hasBearerFormat && len(ss.BearerFormat) > 0 { - return fmt.Errorf("security scheme of type %q can't have 'bearerFormat'", ss.Type) - } - - // Validate "flow" - if hasFlow { - flow := ss.Flows - if flow == nil { - return fmt.Errorf("security scheme of type %q should have 'flows'", ss.Type) - } - if err := flow.Validate(ctx); err != nil { - return fmt.Errorf("security scheme 'flow' is invalid: %w", err) - } - } else if ss.Flows != nil { - return fmt.Errorf("security scheme of type %q can't have 'flows'", ss.Type) - } - - return validateExtensions(ctx, ss.Extensions) -} - -// OAuthFlows is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oauth-flows-object -type OAuthFlows struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Implicit *OAuthFlow `json:"implicit,omitempty" yaml:"implicit,omitempty"` - Password *OAuthFlow `json:"password,omitempty" yaml:"password,omitempty"` - ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty" yaml:"clientCredentials,omitempty"` - AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty" yaml:"authorizationCode,omitempty"` -} - -type oAuthFlowType int - -const ( - oAuthFlowTypeImplicit oAuthFlowType = iota - oAuthFlowTypePassword - oAuthFlowTypeClientCredentials - oAuthFlowAuthorizationCode -) - -// MarshalJSON returns the JSON encoding of OAuthFlows. -func (flows OAuthFlows) MarshalJSON() ([]byte, error) { - x, err := flows.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of OAuthFlows. -func (flows OAuthFlows) MarshalYAML() (any, error) { - m := make(map[string]any, 4+len(flows.Extensions)) - for k, v := range flows.Extensions { - m[k] = v - } - if x := flows.Implicit; x != nil { - m["implicit"] = x - } - if x := flows.Password; x != nil { - m["password"] = x - } - if x := flows.ClientCredentials; x != nil { - m["clientCredentials"] = x - } - if x := flows.AuthorizationCode; x != nil { - m["authorizationCode"] = x - } - return m, nil -} - -// UnmarshalJSON sets OAuthFlows to a copy of data. -func (flows *OAuthFlows) UnmarshalJSON(data []byte) error { - type OAuthFlowsBis OAuthFlows - var x OAuthFlowsBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "implicit") - delete(x.Extensions, "password") - delete(x.Extensions, "clientCredentials") - delete(x.Extensions, "authorizationCode") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *flows = OAuthFlows(x) - return nil -} - -// Validate returns an error if OAuthFlows does not comply with the OpenAPI spec. -func (flows *OAuthFlows) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if v := flows.Implicit; v != nil { - if err := v.validate(ctx, oAuthFlowTypeImplicit, opts...); err != nil { - return fmt.Errorf("the OAuth flow 'implicit' is invalid: %w", err) - } - } - - if v := flows.Password; v != nil { - if err := v.validate(ctx, oAuthFlowTypePassword, opts...); err != nil { - return fmt.Errorf("the OAuth flow 'password' is invalid: %w", err) - } - } - - if v := flows.ClientCredentials; v != nil { - if err := v.validate(ctx, oAuthFlowTypeClientCredentials, opts...); err != nil { - return fmt.Errorf("the OAuth flow 'clientCredentials' is invalid: %w", err) - } - } - - if v := flows.AuthorizationCode; v != nil { - if err := v.validate(ctx, oAuthFlowAuthorizationCode, opts...); err != nil { - return fmt.Errorf("the OAuth flow 'authorizationCode' is invalid: %w", err) - } - } - - return validateExtensions(ctx, flows.Extensions) -} - -// OAuthFlow is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oauth-flow-object -type OAuthFlow struct { - Extensions map[string]any `json:"-" yaml:"-"` - - AuthorizationURL string `json:"authorizationUrl,omitempty" yaml:"authorizationUrl,omitempty"` - TokenURL string `json:"tokenUrl,omitempty" yaml:"tokenUrl,omitempty"` - RefreshURL string `json:"refreshUrl,omitempty" yaml:"refreshUrl,omitempty"` - Scopes map[string]string `json:"scopes" yaml:"scopes"` // required -} - -// MarshalJSON returns the JSON encoding of OAuthFlow. -func (flow OAuthFlow) MarshalJSON() ([]byte, error) { - x, err := flow.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of OAuthFlow. -func (flow OAuthFlow) MarshalYAML() (any, error) { - m := make(map[string]any, 4+len(flow.Extensions)) - for k, v := range flow.Extensions { - m[k] = v - } - if x := flow.AuthorizationURL; x != "" { - m["authorizationUrl"] = x - } - if x := flow.TokenURL; x != "" { - m["tokenUrl"] = x - } - if x := flow.RefreshURL; x != "" { - m["refreshUrl"] = x - } - m["scopes"] = flow.Scopes - return m, nil -} - -// UnmarshalJSON sets OAuthFlow to a copy of data. -func (flow *OAuthFlow) UnmarshalJSON(data []byte) error { - type OAuthFlowBis OAuthFlow - var x OAuthFlowBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "authorizationUrl") - delete(x.Extensions, "tokenUrl") - delete(x.Extensions, "refreshUrl") - delete(x.Extensions, "scopes") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *flow = OAuthFlow(x) - return nil -} - -// Validate returns an error if OAuthFlows does not comply with the OpenAPI spec. -func (flow *OAuthFlow) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if v := flow.RefreshURL; v != "" { - if _, err := url.Parse(v); err != nil { - return fmt.Errorf("field 'refreshUrl' is invalid: %w", err) - } - } - - if flow.Scopes == nil { - return errors.New("field 'scopes' is missing") - } - - return validateExtensions(ctx, flow.Extensions) -} - -func (flow *OAuthFlow) validate(ctx context.Context, typ oAuthFlowType, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - typeIn := func(types ...oAuthFlowType) bool { - for _, ty := range types { - if ty == typ { - return true - } - } - return false - } - - if in := typeIn(oAuthFlowTypeImplicit, oAuthFlowAuthorizationCode); true { - switch { - case flow.AuthorizationURL == "" && in: - return errors.New("field 'authorizationUrl' is empty or missing") - case flow.AuthorizationURL != "" && !in: - return errors.New("field 'authorizationUrl' should not be set") - case flow.AuthorizationURL != "": - if _, err := url.Parse(flow.AuthorizationURL); err != nil { - return fmt.Errorf("field 'authorizationUrl' is invalid: %w", err) - } - } - } - - if in := typeIn(oAuthFlowTypePassword, oAuthFlowTypeClientCredentials, oAuthFlowAuthorizationCode); true { - switch { - case flow.TokenURL == "" && in: - return errors.New("field 'tokenUrl' is empty or missing") - case flow.TokenURL != "" && !in: - return errors.New("field 'tokenUrl' should not be set") - case flow.TokenURL != "": - if _, err := url.Parse(flow.TokenURL); err != nil { - return fmt.Errorf("field 'tokenUrl' is invalid: %w", err) - } - } - } - - return flow.Validate(ctx, opts...) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/serialization_method.go b/vendor/github.com/getkin/kin-openapi/openapi3/serialization_method.go deleted file mode 100644 index 2ec8bd2db..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/serialization_method.go +++ /dev/null @@ -1,17 +0,0 @@ -package openapi3 - -const ( - SerializationSimple = "simple" - SerializationLabel = "label" - SerializationMatrix = "matrix" - SerializationForm = "form" - SerializationSpaceDelimited = "spaceDelimited" - SerializationPipeDelimited = "pipeDelimited" - SerializationDeepObject = "deepObject" -) - -// SerializationMethod describes a serialization method of HTTP request's parameters and body. -type SerializationMethod struct { - Style string - Explode bool -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/server.go b/vendor/github.com/getkin/kin-openapi/openapi3/server.go deleted file mode 100644 index 7a2007f20..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/server.go +++ /dev/null @@ -1,302 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "math" - "net/url" - "sort" - "strings" -) - -// Servers is specified by OpenAPI/Swagger standard version 3. -type Servers []*Server - -// Validate returns an error if Servers does not comply with the OpenAPI spec. -func (servers Servers) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - for _, v := range servers { - if err := v.Validate(ctx); err != nil { - return err - } - } - return nil -} - -// BasePath returns the base path of the first server in the list, or /. -func (servers Servers) BasePath() (string, error) { - for _, server := range servers { - return server.BasePath() - } - return "/", nil -} - -func (servers Servers) MatchURL(parsedURL *url.URL) (*Server, []string, string) { - rawURL := parsedURL.String() - if i := strings.IndexByte(rawURL, '?'); i >= 0 { - rawURL = rawURL[:i] - } - for _, server := range servers { - pathParams, remaining, ok := server.MatchRawURL(rawURL) - if ok { - return server, pathParams, remaining - } - } - return nil, nil, "" -} - -// Server is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#server-object -type Server struct { - Extensions map[string]any `json:"-" yaml:"-"` - - URL string `json:"url" yaml:"url"` // Required - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Variables map[string]*ServerVariable `json:"variables,omitempty" yaml:"variables,omitempty"` -} - -// BasePath returns the base path extracted from the default values of variables, if any. -// Assumes a valid struct (per Validate()). -func (server *Server) BasePath() (string, error) { - if server == nil { - return "/", nil - } - - uri := server.URL - for name, svar := range server.Variables { - uri = strings.ReplaceAll(uri, "{"+name+"}", svar.Default) - } - - u, err := url.ParseRequestURI(uri) - if err != nil { - return "", err - } - - if bp := u.Path; bp != "" { - return bp, nil - } - - return "/", nil -} - -// MarshalJSON returns the JSON encoding of Server. -func (server Server) MarshalJSON() ([]byte, error) { - x, err := server.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Server. -func (server Server) MarshalYAML() (any, error) { - m := make(map[string]any, 3+len(server.Extensions)) - for k, v := range server.Extensions { - m[k] = v - } - m["url"] = server.URL - if x := server.Description; x != "" { - m["description"] = x - } - if x := server.Variables; len(x) != 0 { - m["variables"] = x - } - return m, nil -} - -// UnmarshalJSON sets Server to a copy of data. -func (server *Server) UnmarshalJSON(data []byte) error { - type ServerBis Server - var x ServerBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "url") - delete(x.Extensions, "description") - delete(x.Extensions, "variables") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *server = Server(x) - return nil -} - -func (server Server) ParameterNames() ([]string, error) { - pattern := server.URL - var params []string - for len(pattern) > 0 { - i := strings.IndexByte(pattern, '{') - if i < 0 { - break - } - pattern = pattern[i+1:] - i = strings.IndexByte(pattern, '}') - if i < 0 { - return nil, errors.New("missing '}'") - } - params = append(params, strings.TrimSpace(pattern[:i])) - pattern = pattern[i+1:] - } - return params, nil -} - -func (server Server) MatchRawURL(input string) ([]string, string, bool) { - pattern := server.URL - var params []string - for len(pattern) > 0 { - c := pattern[0] - if len(pattern) == 1 && c == '/' { - break - } - if c == '{' { - // Find end of pattern - i := strings.IndexByte(pattern, '}') - if i < 0 { - return nil, "", false - } - pattern = pattern[i+1:] - - // Find next matching pattern character or next '/' whichever comes first - np := -1 - if len(pattern) > 0 { - np = strings.IndexByte(input, pattern[0]) - } - ns := strings.IndexByte(input, '/') - - if np < 0 { - i = ns - } else if ns < 0 { - i = np - } else { - i = int(math.Min(float64(np), float64(ns))) - } - if i < 0 { - i = len(input) - } - params = append(params, input[:i]) - input = input[i:] - continue - } - if len(input) == 0 || input[0] != c { - return nil, "", false - } - pattern = pattern[1:] - input = input[1:] - } - if input == "" { - input = "/" - } - if input[0] != '/' { - return nil, "", false - } - return params, input, true -} - -// Validate returns an error if Server does not comply with the OpenAPI spec. -func (server *Server) Validate(ctx context.Context, opts ...ValidationOption) (err error) { - ctx = WithValidationOptions(ctx, opts...) - - if server.URL == "" { - return errors.New("value of url must be a non-empty string") - } - - opening, closing := strings.Count(server.URL, "{"), strings.Count(server.URL, "}") - if opening != closing { - return errors.New("server URL has mismatched { and }") - } - - if opening != len(server.Variables) { - return errors.New("server has undeclared variables") - } - - variables := make([]string, 0, len(server.Variables)) - for name := range server.Variables { - variables = append(variables, name) - } - sort.Strings(variables) - for _, name := range variables { - v := server.Variables[name] - if !strings.Contains(server.URL, "{"+name+"}") { - return errors.New("server has undeclared variables") - } - if err = v.Validate(ctx); err != nil { - return - } - } - - return validateExtensions(ctx, server.Extensions) -} - -// ServerVariable is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#server-variable-object -type ServerVariable struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Enum []string `json:"enum,omitempty" yaml:"enum,omitempty"` - Default string `json:"default,omitempty" yaml:"default,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` -} - -// MarshalJSON returns the JSON encoding of ServerVariable. -func (serverVariable ServerVariable) MarshalJSON() ([]byte, error) { - x, err := serverVariable.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of ServerVariable. -func (serverVariable ServerVariable) MarshalYAML() (any, error) { - m := make(map[string]any, 4+len(serverVariable.Extensions)) - for k, v := range serverVariable.Extensions { - m[k] = v - } - if x := serverVariable.Enum; len(x) != 0 { - m["enum"] = x - } - if x := serverVariable.Default; x != "" { - m["default"] = x - } - if x := serverVariable.Description; x != "" { - m["description"] = x - } - return m, nil -} - -// UnmarshalJSON sets ServerVariable to a copy of data. -func (serverVariable *ServerVariable) UnmarshalJSON(data []byte) error { - type ServerVariableBis ServerVariable - var x ServerVariableBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "enum") - delete(x.Extensions, "default") - delete(x.Extensions, "description") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *serverVariable = ServerVariable(x) - return nil -} - -// Validate returns an error if ServerVariable does not comply with the OpenAPI spec. -func (serverVariable *ServerVariable) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if serverVariable.Default == "" { - data, err := serverVariable.MarshalJSON() - if err != nil { - return err - } - return fmt.Errorf("field default is required in %s", data) - } - - return validateExtensions(ctx, serverVariable.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/tag.go b/vendor/github.com/getkin/kin-openapi/openapi3/tag.go deleted file mode 100644 index 182d0502a..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/tag.go +++ /dev/null @@ -1,99 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "fmt" -) - -// Tags is specified by OpenAPI/Swagger 3.0 standard. -type Tags []*Tag - -func (tags Tags) Get(name string) *Tag { - for _, tag := range tags { - if tag.Name == name { - return tag - } - } - return nil -} - -// Validate returns an error if Tags does not comply with the OpenAPI spec. -func (tags Tags) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - for _, v := range tags { - if err := v.Validate(ctx); err != nil { - return err - } - } - return nil -} - -// Tag is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#tag-object -type Tag struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Name string `json:"name,omitempty" yaml:"name,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"` -} - -// MarshalJSON returns the JSON encoding of Tag. -func (t Tag) MarshalJSON() ([]byte, error) { - x, err := t.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of Tag. -func (t Tag) MarshalYAML() (any, error) { - m := make(map[string]any, 3+len(t.Extensions)) - for k, v := range t.Extensions { - m[k] = v - } - if x := t.Name; x != "" { - m["name"] = x - } - if x := t.Description; x != "" { - m["description"] = x - } - if x := t.ExternalDocs; x != nil { - m["externalDocs"] = x - } - return m, nil -} - -// UnmarshalJSON sets Tag to a copy of data. -func (t *Tag) UnmarshalJSON(data []byte) error { - type TagBis Tag - var x TagBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "name") - delete(x.Extensions, "description") - delete(x.Extensions, "externalDocs") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *t = Tag(x) - return nil -} - -// Validate returns an error if Tag does not comply with the OpenAPI spec. -func (t *Tag) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - if v := t.ExternalDocs; v != nil { - if err := v.Validate(ctx); err != nil { - return fmt.Errorf("invalid external docs: %w", err) - } - } - - return validateExtensions(ctx, t.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/validation_options.go b/vendor/github.com/getkin/kin-openapi/openapi3/validation_options.go deleted file mode 100644 index 1d141d40a..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/validation_options.go +++ /dev/null @@ -1,142 +0,0 @@ -package openapi3 - -import "context" - -// ValidationOption allows the modification of how the OpenAPI document is validated. -type ValidationOption func(options *ValidationOptions) - -// ValidationOptions provides configuration for validating OpenAPI documents. -type ValidationOptions struct { - examplesValidationAsReq, examplesValidationAsRes bool - examplesValidationDisabled bool - schemaDefaultsValidationDisabled bool - schemaFormatValidationEnabled bool - schemaPatternValidationDisabled bool - schemaExtensionsInRefProhibited bool - regexCompilerFunc RegexCompilerFunc - extraSiblingFieldsAllowed map[string]struct{} -} - -type validationOptionsKey struct{} - -// AllowExtraSiblingFields called as AllowExtraSiblingFields("description") makes Validate not return an error when said field appears next to a $ref. -func AllowExtraSiblingFields(fields ...string) ValidationOption { - return func(options *ValidationOptions) { - if options.extraSiblingFieldsAllowed == nil && len(fields) != 0 { - options.extraSiblingFieldsAllowed = make(map[string]struct{}, len(fields)) - } - for _, field := range fields { - options.extraSiblingFieldsAllowed[field] = struct{}{} - } - } -} - -// EnableSchemaFormatValidation makes Validate not return an error when validating documents that mention schema formats that are not defined by the OpenAPIv3 specification. -// By default, schema format validation is disabled. -func EnableSchemaFormatValidation() ValidationOption { - return func(options *ValidationOptions) { - options.schemaFormatValidationEnabled = true - } -} - -// DisableSchemaFormatValidation does the opposite of EnableSchemaFormatValidation. -// By default, schema format validation is disabled. -func DisableSchemaFormatValidation() ValidationOption { - return func(options *ValidationOptions) { - options.schemaFormatValidationEnabled = false - } -} - -// EnableSchemaPatternValidation does the opposite of DisableSchemaPatternValidation. -// By default, schema pattern validation is enabled. -func EnableSchemaPatternValidation() ValidationOption { - return func(options *ValidationOptions) { - options.schemaPatternValidationDisabled = false - } -} - -// DisableSchemaPatternValidation makes Validate not return an error when validating patterns that are not supported by the Go regexp engine. -func DisableSchemaPatternValidation() ValidationOption { - return func(options *ValidationOptions) { - options.schemaPatternValidationDisabled = true - } -} - -// EnableSchemaDefaultsValidation does the opposite of DisableSchemaDefaultsValidation. -// By default, schema default values are validated against their schema. -func EnableSchemaDefaultsValidation() ValidationOption { - return func(options *ValidationOptions) { - options.schemaDefaultsValidationDisabled = false - } -} - -// DisableSchemaDefaultsValidation disables schemas' default field validation. -// By default, schema default values are validated against their schema. -func DisableSchemaDefaultsValidation() ValidationOption { - return func(options *ValidationOptions) { - options.schemaDefaultsValidationDisabled = true - } -} - -// EnableExamplesValidation does the opposite of DisableExamplesValidation. -// By default, all schema examples are validated. -func EnableExamplesValidation() ValidationOption { - return func(options *ValidationOptions) { - options.examplesValidationDisabled = false - } -} - -// DisableExamplesValidation disables all example schema validation. -// By default, all schema examples are validated. -func DisableExamplesValidation() ValidationOption { - return func(options *ValidationOptions) { - options.examplesValidationDisabled = true - } -} - -// AllowExtensionsWithRef allows extensions (fields starting with 'x-') -// as siblings for $ref fields. This is the default. -// Non-extension fields are prohibited unless allowed explicitly with the -// AllowExtraSiblingFields option. -func AllowExtensionsWithRef() ValidationOption { - return func(options *ValidationOptions) { - options.schemaExtensionsInRefProhibited = false - } -} - -// ProhibitExtensionsWithRef causes the validation to return an -// error if extensions (fields starting with 'x-') are found as -// siblings for $ref fields. Non-extension fields are prohibited -// unless allowed explicitly with the AllowExtraSiblingFields option. -func ProhibitExtensionsWithRef() ValidationOption { - return func(options *ValidationOptions) { - options.schemaExtensionsInRefProhibited = true - } -} - -// SetRegexCompiler allows to override the regex implementation used to validate -// field "pattern". -func SetRegexCompiler(c RegexCompilerFunc) ValidationOption { - return func(options *ValidationOptions) { - options.regexCompilerFunc = c - } -} - -// WithValidationOptions allows adding validation options to a context object that can be used when validating any OpenAPI type. -func WithValidationOptions(ctx context.Context, opts ...ValidationOption) context.Context { - if len(opts) == 0 { - return ctx - } - options := &ValidationOptions{} - for _, opt := range opts { - opt(options) - } - return context.WithValue(ctx, validationOptionsKey{}, options) -} - -func getValidationOptions(ctx context.Context) *ValidationOptions { - if options, ok := ctx.Value(validationOptionsKey{}).(*ValidationOptions); ok { - return options - } - return &ValidationOptions{} -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/visited.go b/vendor/github.com/getkin/kin-openapi/openapi3/visited.go deleted file mode 100644 index 67f970e36..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/visited.go +++ /dev/null @@ -1,41 +0,0 @@ -package openapi3 - -func newVisited() visitedComponent { - return visitedComponent{ - header: make(map[*Header]struct{}), - schema: make(map[*Schema]struct{}), - } -} - -type visitedComponent struct { - header map[*Header]struct{} - schema map[*Schema]struct{} -} - -// resetVisited clears visitedComponent map -// should be called before recursion over doc *T -func (doc *T) resetVisited() { - doc.visited = newVisited() -} - -// isVisitedHeader returns `true` if the *Header pointer was already visited -// otherwise it returns `false` -func (doc *T) isVisitedHeader(h *Header) bool { - if _, ok := doc.visited.header[h]; ok { - return true - } - - doc.visited.header[h] = struct{}{} - return false -} - -// isVisitedHeader returns `true` if the *Schema pointer was already visited -// otherwise it returns `false` -func (doc *T) isVisitedSchema(s *Schema) bool { - if _, ok := doc.visited.schema[s]; ok { - return true - } - - doc.visited.schema[s] = struct{}{} - return false -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/xml.go b/vendor/github.com/getkin/kin-openapi/openapi3/xml.go deleted file mode 100644 index 69d1b3483..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/xml.go +++ /dev/null @@ -1,78 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" -) - -// XML is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xml-object -type XML struct { - Extensions map[string]any `json:"-" yaml:"-"` - - Name string `json:"name,omitempty" yaml:"name,omitempty"` - Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"` - Prefix string `json:"prefix,omitempty" yaml:"prefix,omitempty"` - Attribute bool `json:"attribute,omitempty" yaml:"attribute,omitempty"` - Wrapped bool `json:"wrapped,omitempty" yaml:"wrapped,omitempty"` -} - -// MarshalJSON returns the JSON encoding of XML. -func (xml XML) MarshalJSON() ([]byte, error) { - x, err := xml.MarshalYAML() - if err != nil { - return nil, err - } - return json.Marshal(x) -} - -// MarshalYAML returns the YAML encoding of XML. -func (xml XML) MarshalYAML() (any, error) { - m := make(map[string]any, 5+len(xml.Extensions)) - for k, v := range xml.Extensions { - m[k] = v - } - if x := xml.Name; x != "" { - m["name"] = x - } - if x := xml.Namespace; x != "" { - m["namespace"] = x - } - if x := xml.Prefix; x != "" { - m["prefix"] = x - } - if x := xml.Attribute; x { - m["attribute"] = x - } - if x := xml.Wrapped; x { - m["wrapped"] = x - } - return m, nil -} - -// UnmarshalJSON sets XML to a copy of data. -func (xml *XML) UnmarshalJSON(data []byte) error { - type XMLBis XML - var x XMLBis - if err := json.Unmarshal(data, &x); err != nil { - return unmarshalError(err) - } - _ = json.Unmarshal(data, &x.Extensions) - delete(x.Extensions, "name") - delete(x.Extensions, "namespace") - delete(x.Extensions, "prefix") - delete(x.Extensions, "attribute") - delete(x.Extensions, "wrapped") - if len(x.Extensions) == 0 { - x.Extensions = nil - } - *xml = XML(x) - return nil -} - -// Validate returns an error if XML does not comply with the OpenAPI spec. -func (xml *XML) Validate(ctx context.Context, opts ...ValidationOption) error { - ctx = WithValidationOptions(ctx, opts...) - - return validateExtensions(ctx, xml.Extensions) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/authentication_input.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/authentication_input.go deleted file mode 100644 index a53484b99..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/authentication_input.go +++ /dev/null @@ -1,29 +0,0 @@ -package openapi3filter - -import ( - "fmt" - - "github.com/getkin/kin-openapi/openapi3" -) - -type AuthenticationInput struct { - RequestValidationInput *RequestValidationInput - SecuritySchemeName string - SecurityScheme *openapi3.SecurityScheme - Scopes []string -} - -func (input *AuthenticationInput) NewError(err error) error { - if err == nil { - if len(input.Scopes) == 0 { - err = fmt.Errorf("security requirement %q failed", input.SecuritySchemeName) - } else { - err = fmt.Errorf("security requirement %q (scopes: %+v) failed", input.SecuritySchemeName, input.Scopes) - } - } - return &RequestError{ - Input: input.RequestValidationInput, - Reason: "authorization failed", - Err: err, - } -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/errors.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/errors.go deleted file mode 100644 index ea7c7c312..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/errors.go +++ /dev/null @@ -1,97 +0,0 @@ -package openapi3filter - -import ( - "bytes" - "fmt" - - "github.com/getkin/kin-openapi/openapi3" -) - -var _ error = &RequestError{} - -// RequestError is returned by ValidateRequest when request does not match OpenAPI spec -type RequestError struct { - Input *RequestValidationInput - Parameter *openapi3.Parameter - RequestBody *openapi3.RequestBody - Reason string - Err error -} - -var _ interface{ Unwrap() error } = RequestError{} - -func (err *RequestError) Error() string { - reason := err.Reason - if e := err.Err; e != nil { - if len(reason) == 0 || reason == e.Error() { - reason = e.Error() - } else { - reason += ": " + e.Error() - } - } - if v := err.Parameter; v != nil { - return fmt.Sprintf("parameter %q in %s has an error: %s", v.Name, v.In, reason) - } else if v := err.RequestBody; v != nil { - return fmt.Sprintf("request body has an error: %s", reason) - } else { - return reason - } -} - -func (err RequestError) Unwrap() error { - return err.Err -} - -var _ error = &ResponseError{} - -// ResponseError is returned by ValidateResponse when response does not match OpenAPI spec -type ResponseError struct { - Input *ResponseValidationInput - Reason string - Err error -} - -var _ interface{ Unwrap() error } = ResponseError{} - -func (err *ResponseError) Error() string { - reason := err.Reason - if e := err.Err; e != nil { - if len(reason) == 0 { - reason = e.Error() - } else { - reason += ": " + e.Error() - } - } - return reason -} - -func (err ResponseError) Unwrap() error { - return err.Err -} - -var _ error = &SecurityRequirementsError{} - -// SecurityRequirementsError is returned by ValidateSecurityRequirements -// when no requirement is met. -type SecurityRequirementsError struct { - SecurityRequirements openapi3.SecurityRequirements - Errors []error -} - -func (err *SecurityRequirementsError) Error() string { - buff := bytes.NewBufferString("security requirements failed: ") - for i, e := range err.Errors { - buff.WriteString(e.Error()) - if i != len(err.Errors)-1 { - buff.WriteString(" | ") - } - } - - return buff.String() -} - -var _ interface{ Unwrap() []error } = SecurityRequirementsError{} - -func (err SecurityRequirementsError) Unwrap() []error { - return err.Errors -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/internal.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/internal.go deleted file mode 100644 index f807e06f1..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/internal.go +++ /dev/null @@ -1,25 +0,0 @@ -package openapi3filter - -import ( - "reflect" - "strings" -) - -func parseMediaType(contentType string) string { - i := strings.IndexByte(contentType, ';') - if i < 0 { - return contentType - } - return contentType[:i] -} - -func isNilValue(value any) bool { - if value == nil { - return true - } - switch reflect.TypeOf(value).Kind() { - case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice: - return reflect.ValueOf(value).IsNil() - } - return false -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/middleware.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/middleware.go deleted file mode 100644 index d20889ed9..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/middleware.go +++ /dev/null @@ -1,284 +0,0 @@ -package openapi3filter - -import ( - "bytes" - "context" - "io" - "log" - "net/http" - - "github.com/getkin/kin-openapi/routers" -) - -// Validator provides HTTP request and response validation middleware. -type Validator struct { - router routers.Router - errFunc ErrFunc - logFunc LogFunc - strict bool - options Options -} - -// ErrFunc handles errors that may occur during validation. -type ErrFunc func(ctx context.Context, w http.ResponseWriter, status int, code ErrCode, err error) - -// LogFunc handles log messages that may occur during validation. -type LogFunc func(ctx context.Context, message string, err error) - -// ErrCode is used for classification of different types of errors that may -// occur during validation. These may be used to write an appropriate response -// in ErrFunc. -type ErrCode int - -const ( - // ErrCodeOK indicates no error. It is also the default value. - ErrCodeOK = 0 - // ErrCodeCannotFindRoute happens when the validator fails to resolve the - // request to a defined OpenAPI route. - ErrCodeCannotFindRoute = iota - // ErrCodeRequestInvalid happens when the inbound request does not conform - // to the OpenAPI 3 specification. - ErrCodeRequestInvalid = iota - // ErrCodeResponseInvalid happens when the wrapped handler response does - // not conform to the OpenAPI 3 specification. - ErrCodeResponseInvalid = iota -) - -func (e ErrCode) responseText() string { - switch e { - case ErrCodeOK: - return "OK" - case ErrCodeCannotFindRoute: - return "not found" - case ErrCodeRequestInvalid: - return "bad request" - default: - return "server error" - } -} - -// NewValidator returns a new response validation middleware, using the given -// routes from an OpenAPI 3 specification. -func NewValidator(router routers.Router, options ...ValidatorOption) *Validator { - v := &Validator{ - router: router, - errFunc: func(_ context.Context, w http.ResponseWriter, status int, code ErrCode, _ error) { - http.Error(w, code.responseText(), status) - }, - logFunc: func(_ context.Context, message string, err error) { - log.Printf("%s: %v", message, err) - }, - } - for i := range options { - options[i](v) - } - return v -} - -// ValidatorOption defines an option that may be specified when creating a -// Validator. -type ValidatorOption func(*Validator) - -// OnErr provides a callback that handles writing an HTTP response on a -// validation error. This allows customization of error responses without -// prescribing a particular form. This callback is only called on response -// validator errors in Strict mode. -func OnErr(f ErrFunc) ValidatorOption { - return func(v *Validator) { - v.errFunc = f - } -} - -// OnLog provides a callback that handles logging in the Validator. This allows -// the validator to integrate with a services' existing logging system without -// prescribing a particular one. -func OnLog(f LogFunc) ValidatorOption { - return func(v *Validator) { - v.logFunc = f - } -} - -// Strict, if set, causes an internal server error to be sent if the wrapped -// handler response fails response validation. If not set, the response is sent -// and the error is only logged. -func Strict(strict bool) ValidatorOption { - return func(v *Validator) { - v.strict = strict - } -} - -// ValidationOptions sets request/response validation options on the validator. -func ValidationOptions(options Options) ValidatorOption { - return func(v *Validator) { - v.options = options - } -} - -// Middleware returns an http.Handler which wraps the given handler with -// request and response validation. -func (v *Validator) Middleware(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - route, pathParams, err := v.router.FindRoute(r) - if err != nil { - v.logFunc(ctx, "validation error: failed to find route for "+r.URL.String(), err) - v.errFunc(ctx, w, http.StatusNotFound, ErrCodeCannotFindRoute, err) - return - } - requestValidationInput := &RequestValidationInput{ - Request: r, - PathParams: pathParams, - Route: route, - Options: &v.options, - } - if err = ValidateRequest(ctx, requestValidationInput); err != nil { - v.logFunc(ctx, "invalid request", err) - v.errFunc(ctx, w, http.StatusBadRequest, ErrCodeRequestInvalid, err) - return - } - - var wr responseWrapper - if v.strict { - wr = &strictResponseWrapper{w: w} - } else { - wr = newWarnResponseWrapper(w) - } - - h.ServeHTTP(wr, r) - - if err = ValidateResponse(ctx, &ResponseValidationInput{ - RequestValidationInput: requestValidationInput, - Status: wr.statusCode(), - Header: wr.Header(), - Body: io.NopCloser(bytes.NewBuffer(wr.bodyContents())), - Options: &v.options, - }); err != nil { - v.logFunc(ctx, "invalid response", err) - if v.strict { - v.errFunc(ctx, w, http.StatusInternalServerError, ErrCodeResponseInvalid, err) - } - return - } - - if err = wr.flushBodyContents(); err != nil { - v.logFunc(ctx, "failed to write response", err) - } - }) -} - -type responseWrapper interface { - http.ResponseWriter - - // flushBodyContents writes the buffered response to the client, if it has - // not yet been written. - flushBodyContents() error - - // statusCode returns the response status code, 0 if not set yet. - statusCode() int - - // bodyContents returns the buffered - bodyContents() []byte -} - -type warnResponseWrapper struct { - w http.ResponseWriter - headerWritten bool - status int - body bytes.Buffer - tee io.Writer -} - -func newWarnResponseWrapper(w http.ResponseWriter) *warnResponseWrapper { - wr := &warnResponseWrapper{ - w: w, - } - wr.tee = io.MultiWriter(w, &wr.body) - return wr -} - -// Write implements http.ResponseWriter. -func (wr *warnResponseWrapper) Write(b []byte) (int, error) { - if !wr.headerWritten { - wr.WriteHeader(http.StatusOK) - } - return wr.tee.Write(b) -} - -// WriteHeader implements http.ResponseWriter. -func (wr *warnResponseWrapper) WriteHeader(status int) { - if !wr.headerWritten { - // If the header hasn't been written, record the status for response - // validation. - wr.status = status - wr.headerWritten = true - } - wr.w.WriteHeader(wr.status) -} - -// Header implements http.ResponseWriter. -func (wr *warnResponseWrapper) Header() http.Header { - return wr.w.Header() -} - -// Flush implements the optional http.Flusher interface. -func (wr *warnResponseWrapper) Flush() { - // If the wrapped http.ResponseWriter implements optional http.Flusher, - // pass through. - if fl, ok := wr.w.(http.Flusher); ok { - fl.Flush() - } -} - -func (wr *warnResponseWrapper) flushBodyContents() error { - return nil -} - -func (wr *warnResponseWrapper) statusCode() int { - return wr.status -} - -func (wr *warnResponseWrapper) bodyContents() []byte { - return wr.body.Bytes() -} - -type strictResponseWrapper struct { - w http.ResponseWriter - headerWritten bool - status int - body bytes.Buffer -} - -// Write implements http.ResponseWriter. -func (wr *strictResponseWrapper) Write(b []byte) (int, error) { - if !wr.headerWritten { - wr.WriteHeader(http.StatusOK) - } - return wr.body.Write(b) -} - -// WriteHeader implements http.ResponseWriter. -func (wr *strictResponseWrapper) WriteHeader(status int) { - if !wr.headerWritten { - wr.status = status - wr.headerWritten = true - } -} - -// Header implements http.ResponseWriter. -func (wr *strictResponseWrapper) Header() http.Header { - return wr.w.Header() -} - -func (wr *strictResponseWrapper) flushBodyContents() error { - wr.w.WriteHeader(wr.status) - _, err := wr.w.Write(wr.body.Bytes()) - return err -} - -func (wr *strictResponseWrapper) statusCode() int { - return wr.status -} - -func (wr *strictResponseWrapper) bodyContents() []byte { - return wr.body.Bytes() -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/options.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/options.go deleted file mode 100644 index e7fad8321..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/options.go +++ /dev/null @@ -1,50 +0,0 @@ -package openapi3filter - -import "github.com/getkin/kin-openapi/openapi3" - -// Options used by ValidateRequest and ValidateResponse -type Options struct { - // Set ExcludeRequestBody so ValidateRequest skips request body validation - ExcludeRequestBody bool - - // Set ExcludeRequestQueryParams so ValidateRequest skips request query params validation - ExcludeRequestQueryParams bool - - // Set ExcludeResponseBody so ValidateResponse skips response body validation - ExcludeResponseBody bool - - // Set ExcludeReadOnlyValidations so ValidateRequest skips read-only validations - ExcludeReadOnlyValidations bool - - // Set ExcludeWriteOnlyValidations so ValidateResponse skips write-only validations - ExcludeWriteOnlyValidations bool - - // Set IncludeResponseStatus so ValidateResponse fails on response - // status not defined in OpenAPI spec - IncludeResponseStatus bool - - MultiError bool - - // Set RegexCompiler to override the regex implementation - RegexCompiler openapi3.RegexCompilerFunc - - // A document with security schemes defined will not pass validation - // unless an AuthenticationFunc is defined. - // See NoopAuthenticationFunc - AuthenticationFunc AuthenticationFunc - - // Indicates whether default values are set in the - // request. If true, then they are not set - SkipSettingDefaults bool - - customSchemaErrorFunc CustomSchemaErrorFunc -} - -// CustomSchemaErrorFunc allows for custom the schema error message. -type CustomSchemaErrorFunc func(err *openapi3.SchemaError) string - -// WithCustomSchemaErrorFunc sets a function to override the schema error message. -// If the passed function returns an empty string, it returns to the previous Error() implementation. -func (o *Options) WithCustomSchemaErrorFunc(f CustomSchemaErrorFunc) { - o.customSchemaErrorFunc = f -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/req_resp_decoder.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/req_resp_decoder.go deleted file mode 100644 index e151c9ee7..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/req_resp_decoder.go +++ /dev/null @@ -1,1588 +0,0 @@ -package openapi3filter - -import ( - "archive/zip" - "bytes" - "encoding/csv" - "encoding/json" - "errors" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "reflect" - "regexp" - "strconv" - "strings" - - "gopkg.in/yaml.v3" - - "github.com/getkin/kin-openapi/openapi3" -) - -// ParseErrorKind describes a kind of ParseError. -// The type simplifies comparison of errors. -type ParseErrorKind int - -const ( - // KindOther describes an untyped parsing error. - KindOther ParseErrorKind = iota - // KindUnsupportedFormat describes an error that happens when a value has an unsupported format. - KindUnsupportedFormat - // KindInvalidFormat describes an error that happens when a value does not conform a format - // that is required by a serialization method. - KindInvalidFormat -) - -// ParseError describes errors which happens while parse operation's parameters, requestBody, or response. -type ParseError struct { - Kind ParseErrorKind - Value any - Reason string - Cause error - - path []any -} - -var _ interface{ Unwrap() error } = ParseError{} - -func (e *ParseError) Error() string { - var msg []string - if p := e.Path(); len(p) > 0 { - var arr []string - for _, v := range p { - arr = append(arr, fmt.Sprintf("%v", v)) - } - msg = append(msg, fmt.Sprintf("path %v", strings.Join(arr, "."))) - } - msg = append(msg, e.innerError()) - return strings.Join(msg, ": ") -} - -func (e *ParseError) innerError() string { - var msg []string - if e.Value != nil { - msg = append(msg, fmt.Sprintf("value %v", e.Value)) - } - if e.Reason != "" { - msg = append(msg, e.Reason) - } - if e.Cause != nil { - if v, ok := e.Cause.(*ParseError); ok { - msg = append(msg, v.innerError()) - } else { - msg = append(msg, e.Cause.Error()) - } - } - return strings.Join(msg, ": ") -} - -// RootCause returns a root cause of ParseError. -func (e *ParseError) RootCause() error { - if v, ok := e.Cause.(*ParseError); ok { - return v.RootCause() - } - return e.Cause -} - -func (e ParseError) Unwrap() error { - return e.Cause -} - -// Path returns a path to the root cause. -func (e *ParseError) Path() []any { - var path []any - if v, ok := e.Cause.(*ParseError); ok { - p := v.Path() - if len(p) > 0 { - path = append(path, p...) - } - } - if len(e.path) > 0 { - path = append(path, e.path...) - } - return path -} - -func invalidSerializationMethodErr(sm *openapi3.SerializationMethod) error { - return fmt.Errorf("invalid serialization method: style=%q, explode=%v", sm.Style, sm.Explode) -} - -// Decodes a parameter defined via the content property as an object. It uses -// the user specified decoder, or our build-in decoder for application/json -func decodeContentParameter(param *openapi3.Parameter, input *RequestValidationInput) ( - value any, - schema *openapi3.Schema, - found bool, - err error, -) { - var paramValues []string - switch param.In { - case openapi3.ParameterInPath: - var paramValue string - if paramValue, found = input.PathParams[param.Name]; found { - paramValues = []string{paramValue} - } - case openapi3.ParameterInQuery: - paramValues, found = input.GetQueryParams()[param.Name] - case openapi3.ParameterInHeader: - var headerValues []string - if headerValues, found = input.Request.Header[http.CanonicalHeaderKey(param.Name)]; found { - paramValues = headerValues - } - case openapi3.ParameterInCookie: - var cookie *http.Cookie - if cookie, err = input.Request.Cookie(param.Name); err == http.ErrNoCookie { - found = false - } else if err != nil { - return - } else { - paramValues = []string{cookie.Value} - found = true - } - default: - err = fmt.Errorf("unsupported parameter.in: %q", param.In) - return - } - - if !found { - if param.Required { - err = fmt.Errorf("parameter %q is required, but missing", param.Name) - } - return - } - - decoder := input.ParamDecoder - if decoder == nil { - decoder = defaultContentParameterDecoder - } - - value, schema, err = decoder(param, paramValues) - return -} - -func defaultContentParameterDecoder(param *openapi3.Parameter, values []string) ( - outValue any, - outSchema *openapi3.Schema, - err error, -) { - // Only query parameters can have multiple values. - if len(values) > 1 && param.In != openapi3.ParameterInQuery { - err = fmt.Errorf("%s parameter %q cannot have multiple values", param.In, param.Name) - return - } - - content := param.Content - if content == nil { - err = fmt.Errorf("parameter %q expected to have content", param.Name) - return - } - // We only know how to decode a parameter if it has one content, application/json - if len(content) != 1 { - err = fmt.Errorf("multiple content types for parameter %q", param.Name) - return - } - - mt := content.Get("application/json") - if mt == nil { - err = fmt.Errorf("parameter %q has no content schema", param.Name) - return - } - outSchema = mt.Schema.Value - - unmarshal := func(encoded string, paramSchema *openapi3.SchemaRef) (decoded any, err error) { - if err = json.Unmarshal([]byte(encoded), &decoded); err != nil { - if paramSchema != nil && !paramSchema.Value.Type.Is("object") { - decoded, err = encoded, nil - } - } - return - } - - if len(values) == 1 { - if outValue, err = unmarshal(values[0], mt.Schema); err != nil { - err = fmt.Errorf("error unmarshaling parameter %q", param.Name) - return - } - } else { - outArray := make([]any, 0, len(values)) - for _, v := range values { - var item any - if item, err = unmarshal(v, outSchema.Items); err != nil { - err = fmt.Errorf("error unmarshaling parameter %q", param.Name) - return - } - outArray = append(outArray, item) - } - outValue = outArray - } - return -} - -type valueDecoder interface { - DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) - DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) - DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) -} - -// decodeStyledParameter returns a value of an operation's parameter from HTTP request for -// parameters defined using the style format, and whether the parameter is supplied in the input. -// The function returns ParseError when HTTP request contains an invalid value of a parameter. -func decodeStyledParameter(param *openapi3.Parameter, input *RequestValidationInput) (any, bool, error) { - sm, err := param.SerializationMethod() - if err != nil { - return nil, false, err - } - - var dec valueDecoder - switch param.In { - case openapi3.ParameterInPath: - if len(input.PathParams) == 0 { - return nil, false, nil - } - dec = &pathParamDecoder{pathParams: input.PathParams} - case openapi3.ParameterInQuery: - if len(input.GetQueryParams()) == 0 { - return nil, false, nil - } - dec = &urlValuesDecoder{values: input.GetQueryParams()} - case openapi3.ParameterInHeader: - dec = &headerParamDecoder{header: input.Request.Header} - case openapi3.ParameterInCookie: - dec = &cookieParamDecoder{req: input.Request} - default: - return nil, false, fmt.Errorf("unsupported parameter's 'in': %s", param.In) - } - - return decodeValue(dec, param.Name, sm, param.Schema, param.Required) -} - -func decodeValue(dec valueDecoder, param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef, required bool) (any, bool, error) { - var found bool - - if len(schema.Value.AllOf) > 0 { - var value any - var err error - for _, sr := range schema.Value.AllOf { - var f bool - value, f, err = decodeValue(dec, param, sm, sr, required) - found = found || f - if value == nil || err != nil { - break - } - } - return value, found, err - } - - if len(schema.Value.AnyOf) > 0 { - for _, sr := range schema.Value.AnyOf { - value, f, _ := decodeValue(dec, param, sm, sr, required) - found = found || f - if value != nil { - return value, found, nil - } - } - if required { - return nil, found, fmt.Errorf("decoding anyOf for parameter %q failed", param) - } - return nil, found, nil - } - - if len(schema.Value.OneOf) > 0 { - isMatched := 0 - var value any - for _, sr := range schema.Value.OneOf { - v, f, _ := decodeValue(dec, param, sm, sr, required) - found = found || f - if v != nil { - value = v - isMatched++ - } - } - if isMatched >= 1 { - return value, found, nil - } - if required { - return nil, found, fmt.Errorf("decoding oneOf failed: %q is required", param) - } - return nil, found, nil - } - - if schema.Value.Not != nil { - // TODO(decode not): handle decoding "not" JSON Schema - return nil, found, errors.New("not implemented: decoding 'not'") - } - - if schema.Value.Type != nil { - var decodeFn func(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) - switch { - case schema.Value.Type.Is("array"): - decodeFn = func(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) { - res, b, e := dec.DecodeArray(param, sm, schema) - if len(res) == 0 { - return nil, b, e - } - return res, b, e - } - case schema.Value.Type.Is("object"): - decodeFn = func(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) { - return dec.DecodeObject(param, sm, schema) - } - default: - decodeFn = dec.DecodePrimitive - } - return decodeFn(param, sm, schema) - } - switch vDecoder := dec.(type) { - case *pathParamDecoder: - _, found = vDecoder.pathParams[param] - case *urlValuesDecoder: - if schema.Value.Pattern != "" { - return dec.DecodePrimitive(param, sm, schema) - } - _, found = vDecoder.values[param] - case *headerParamDecoder: - _, found = vDecoder.header[http.CanonicalHeaderKey(param)] - case *cookieParamDecoder: - _, err := vDecoder.req.Cookie(param) - found = err != http.ErrNoCookie - default: - return nil, found, errors.New("unsupported decoder") - } - return nil, found, nil -} - -// pathParamDecoder decodes values of path parameters. -type pathParamDecoder struct { - pathParams map[string]string -} - -func (d *pathParamDecoder) DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) { - var prefix string - switch sm.Style { - case "simple": - // A prefix is empty for style "simple". - case "label": - prefix = "." - case "matrix": - prefix = ";" + param + "=" - default: - return nil, false, invalidSerializationMethodErr(sm) - } - - if d.pathParams == nil { - // HTTP request does not contains a value of the target path parameter. - return nil, false, nil - } - raw, ok := d.pathParams[param] - if !ok || raw == "" { - // HTTP request does not contains a value of the target path parameter. - return nil, false, nil - } - src, err := cutPrefix(raw, prefix) - if err != nil { - return nil, ok, err - } - val, err := parsePrimitive(src, schema) - return val, ok, err -} - -func (d *pathParamDecoder) DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) { - var prefix, delim string - switch { - case sm.Style == "simple": - delim = "," - case sm.Style == "label" && !sm.Explode: - prefix = "." - delim = "," - case sm.Style == "label" && sm.Explode: - prefix = "." - delim = "." - case sm.Style == "matrix" && !sm.Explode: - prefix = ";" + param + "=" - delim = "," - case sm.Style == "matrix" && sm.Explode: - prefix = ";" + param + "=" - delim = ";" + param + "=" - default: - return nil, false, invalidSerializationMethodErr(sm) - } - - if d.pathParams == nil { - // HTTP request does not contains a value of the target path parameter. - return nil, false, nil - } - raw, ok := d.pathParams[param] - if !ok || raw == "" { - // HTTP request does not contains a value of the target path parameter. - return nil, false, nil - } - src, err := cutPrefix(raw, prefix) - if err != nil { - return nil, ok, err - } - val, err := parseArray(strings.Split(src, delim), schema) - return val, ok, err -} - -func (d *pathParamDecoder) DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) { - var prefix, propsDelim, valueDelim string - switch { - case sm.Style == "simple" && !sm.Explode: - propsDelim = "," - valueDelim = "," - case sm.Style == "simple" && sm.Explode: - propsDelim = "," - valueDelim = "=" - case sm.Style == "label" && !sm.Explode: - prefix = "." - propsDelim = "," - valueDelim = "," - case sm.Style == "label" && sm.Explode: - prefix = "." - propsDelim = "." - valueDelim = "=" - case sm.Style == "matrix" && !sm.Explode: - prefix = ";" + param + "=" - propsDelim = "," - valueDelim = "," - case sm.Style == "matrix" && sm.Explode: - prefix = ";" - propsDelim = ";" - valueDelim = "=" - default: - return nil, false, invalidSerializationMethodErr(sm) - } - - if d.pathParams == nil { - // HTTP request does not contains a value of the target path parameter. - return nil, false, nil - } - raw, ok := d.pathParams[param] - if !ok || raw == "" { - // HTTP request does not contains a value of the target path parameter. - return nil, false, nil - } - src, err := cutPrefix(raw, prefix) - if err != nil { - return nil, ok, err - } - props, err := propsFromString(src, propsDelim, valueDelim) - if err != nil { - return nil, ok, err - } - - val, err := makeObject(props, schema) - return val, ok, err -} - -// cutPrefix validates that a raw value of a path parameter has the specified prefix, -// and returns a raw value without the prefix. -func cutPrefix(raw, prefix string) (string, error) { - if prefix == "" { - return raw, nil - } - if len(raw) < len(prefix) || raw[:len(prefix)] != prefix { - return "", &ParseError{ - Kind: KindInvalidFormat, - Value: raw, - Reason: fmt.Sprintf("a value must be prefixed with %q", prefix), - } - } - return raw[len(prefix):], nil -} - -// urlValuesDecoder decodes values of query parameters. -type urlValuesDecoder struct { - values url.Values -} - -func (d *urlValuesDecoder) DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) { - if sm.Style != "form" { - return nil, false, invalidSerializationMethodErr(sm) - } - - values, ok := d.values[param] - if len(values) == 0 { - // HTTP request does not contain a value of the target query parameter. - return nil, ok, nil - } - - if schema.Value.Type == nil && schema.Value.Pattern != "" { - return values[0], ok, nil - } - val, err := parsePrimitive(values[0], schema) - return val, ok, err -} - -func (d *urlValuesDecoder) DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) { - if sm.Style == "deepObject" { - return nil, false, invalidSerializationMethodErr(sm) - } - - values, ok := d.values[param] - if len(values) == 0 { - // HTTP request does not contain a value of the target query parameter. - return nil, ok, nil - } - if !sm.Explode { - var delim string - switch sm.Style { - case "form": - delim = "," - case "spaceDelimited": - delim = " " - case "pipeDelimited": - delim = "|" - } - values = strings.Split(values[0], delim) - } - val, err := d.parseArray(values, sm, schema) - return val, ok, err -} - -// parseArray returns an array that contains items from a raw array. -// Every item is parsed as a primitive value. -// The function returns an error when an error happened while parse array's items. -func (d *urlValuesDecoder) parseArray(raw []string, sm *openapi3.SerializationMethod, schemaRef *openapi3.SchemaRef) ([]any, error) { - var value []any - - for i, v := range raw { - item, err := d.parseValue(v, schemaRef.Value.Items) - if err != nil { - if v, ok := err.(*ParseError); ok { - return nil, &ParseError{path: []any{i}, Cause: v} - } - return nil, fmt.Errorf("item %d: %w", i, err) - } - - // If the items are nil, then the array is nil. There shouldn't be case where some values are actual primitive - // values and some are nil values. - if item == nil { - return nil, nil - } - value = append(value, item) - } - return value, nil -} - -func (d *urlValuesDecoder) parseValue(v string, schema *openapi3.SchemaRef) (any, error) { - if len(schema.Value.AllOf) > 0 { - var value any - var err error - for _, sr := range schema.Value.AllOf { - value, err = d.parseValue(v, sr) - if value == nil || err != nil { - break - } - } - return value, err - } - - if len(schema.Value.AnyOf) > 0 { - var value any - var err error - for _, sr := range schema.Value.AnyOf { - if value, err = d.parseValue(v, sr); err == nil { - return value, nil - } - } - - return nil, err - } - - if len(schema.Value.OneOf) > 0 { - isMatched := 0 - var value any - var err error - for _, sr := range schema.Value.OneOf { - result, err := d.parseValue(v, sr) - if err == nil { - value = result - isMatched++ - } - } - if isMatched == 1 { - return value, nil - } else if isMatched > 1 { - return nil, fmt.Errorf("decoding oneOf failed: %d schemas matched", isMatched) - } else if isMatched == 0 { - return nil, fmt.Errorf("decoding oneOf failed: %d schemas matched", isMatched) - } - - return nil, err - } - - if schema.Value.Not != nil { - // TODO(decode not): handle decoding "not" JSON Schema - return nil, errors.New("not implemented: decoding 'not'") - } - - return parsePrimitive(v, schema) -} - -const ( - urlDecoderDelimiter = "\x1F" // should not conflict with URL characters -) - -func (d *urlValuesDecoder) DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) { - var propsFn func(url.Values) (map[string]string, error) - switch sm.Style { - case "form": - propsFn = func(params url.Values) (map[string]string, error) { - if len(params) == 0 { - // HTTP request does not contain query parameters. - return nil, nil - } - if sm.Explode { - props := make(map[string]string) - for key, values := range params { - props[key] = values[0] - } - return props, nil - } - values := params[param] - if len(values) == 0 { - // HTTP request does not contain a value of the target query parameter. - return nil, nil - } - return propsFromString(values[0], ",", ",") - } - case "deepObject": - propsFn = func(params url.Values) (map[string]string, error) { - props := make(map[string]string) - for key, values := range params { - if !regexp.MustCompile(fmt.Sprintf(`^%s\[`, regexp.QuoteMeta(param))).MatchString(key) { - continue - } - - matches := regexp.MustCompile(`\[(.*?)\]`).FindAllStringSubmatch(key, -1) - switch l := len(matches); { - case l == 0: - // A query parameter's name does not match the required format, so skip it. - continue - case l >= 1: - kk := []string{} - for _, m := range matches { - kk = append(kk, m[1]) - } - props[strings.Join(kk, urlDecoderDelimiter)] = strings.Join(values, urlDecoderDelimiter) - } - } - if len(props) == 0 { - // HTTP request does not contain query parameters encoded by rules of style "deepObject". - return nil, nil - } - return props, nil - } - default: - return nil, false, invalidSerializationMethodErr(sm) - } - props, err := propsFn(d.values) - if err != nil { - return nil, false, err - } - if props == nil { - return nil, false, nil - } - val, err := makeObject(props, schema) - if err != nil { - return nil, false, err - } - - found := false - for propName := range schema.Value.Properties { - if _, ok := props[propName]; ok { - found = true - break - } - - if schema.Value.Type.Permits("array") || schema.Value.Type.Permits("object") { - for k := range props { - path := strings.Split(k, urlDecoderDelimiter) - if _, ok := deepGet(val, path...); ok { - found = true - break - } - } - } - } - - return val, found, nil -} - -// headerParamDecoder decodes values of header parameters. -type headerParamDecoder struct { - header http.Header -} - -func (d *headerParamDecoder) DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) { - if sm.Style != "simple" { - return nil, false, invalidSerializationMethodErr(sm) - } - - raw, ok := d.header[http.CanonicalHeaderKey(param)] - if !ok || len(raw) == 0 { - // HTTP request does not contains a corresponding header or has the empty value - return nil, ok, nil - } - - val, err := parsePrimitive(raw[0], schema) - return val, ok, err -} - -func (d *headerParamDecoder) DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) { - if sm.Style != "simple" { - return nil, false, invalidSerializationMethodErr(sm) - } - - raw, ok := d.header[http.CanonicalHeaderKey(param)] - if !ok || len(raw) == 0 { - // HTTP request does not contains a corresponding header - return nil, ok, nil - } - - val, err := parseArray(strings.Split(raw[0], ","), schema) - return val, ok, err -} - -func (d *headerParamDecoder) DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) { - if sm.Style != "simple" { - return nil, false, invalidSerializationMethodErr(sm) - } - valueDelim := "," - if sm.Explode { - valueDelim = "=" - } - - raw, ok := d.header[http.CanonicalHeaderKey(param)] - if !ok || len(raw) == 0 { - // HTTP request does not contain a corresponding header. - return nil, ok, nil - } - props, err := propsFromString(raw[0], ",", valueDelim) - if err != nil { - return nil, ok, err - } - val, err := makeObject(props, schema) - return val, ok, err -} - -// cookieParamDecoder decodes values of cookie parameters. -type cookieParamDecoder struct { - req *http.Request -} - -func (d *cookieParamDecoder) DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) { - if sm.Style != "form" { - return nil, false, invalidSerializationMethodErr(sm) - } - - cookie, err := d.req.Cookie(param) - found := err != http.ErrNoCookie - if !found { - // HTTP request does not contain a corresponding cookie. - return nil, found, nil - } - if err != nil { - return nil, found, fmt.Errorf("decoding param %q: %w", param, err) - } - - val, err := parsePrimitive(cookie.Value, schema) - return val, found, err -} - -func (d *cookieParamDecoder) DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) { - if sm.Style != "form" || sm.Explode { - return nil, false, invalidSerializationMethodErr(sm) - } - - cookie, err := d.req.Cookie(param) - found := err != http.ErrNoCookie - if !found { - // HTTP request does not contain a corresponding cookie. - return nil, found, nil - } - if err != nil { - return nil, found, fmt.Errorf("decoding param %q: %w", param, err) - } - val, err := parseArray(strings.Split(cookie.Value, ","), schema) - return val, found, err -} - -func (d *cookieParamDecoder) DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) { - if sm.Style != "form" || sm.Explode { - return nil, false, invalidSerializationMethodErr(sm) - } - - cookie, err := d.req.Cookie(param) - found := err != http.ErrNoCookie - if !found { - // HTTP request does not contain a corresponding cookie. - return nil, found, nil - } - if err != nil { - return nil, found, fmt.Errorf("decoding param %q: %w", param, err) - } - props, err := propsFromString(cookie.Value, ",", ",") - if err != nil { - return nil, found, err - } - val, err := makeObject(props, schema) - return val, found, err -} - -// propsFromString returns a properties map that is created by splitting a source string by propDelim and valueDelim. -// The source string must have a valid format: pairs separated by . -// The function returns an error when the source string has an invalid format. -func propsFromString(src, propDelim, valueDelim string) (map[string]string, error) { - props := make(map[string]string) - pairs := strings.Split(src, propDelim) - - // When propDelim and valueDelim is equal the source string follow the next rule: - // every even item of pairs is a properties's name, and the subsequent odd item is a property's value. - if propDelim == valueDelim { - // Taking into account the rule above, a valid source string must be splitted by propDelim - // to an array with an even number of items. - if len(pairs)%2 != 0 { - return nil, &ParseError{ - Kind: KindInvalidFormat, - Value: src, - Reason: fmt.Sprintf("a value must be a list of object's properties in format \"name%svalue\" separated by %s", valueDelim, propDelim), - } - } - for i := 0; i < len(pairs)/2; i++ { - props[pairs[i*2]] = pairs[i*2+1] - } - return props, nil - } - - // When propDelim and valueDelim is not equal the source string follow the next rule: - // every item of pairs is a string that follows format . - for _, pair := range pairs { - prop := strings.Split(pair, valueDelim) - if len(prop) != 2 { - return nil, &ParseError{ - Kind: KindInvalidFormat, - Value: src, - Reason: fmt.Sprintf("a value must be a list of object's properties in format \"name%svalue\" separated by %s", valueDelim, propDelim), - } - } - props[prop[0]] = prop[1] - } - return props, nil -} - -func deepGet(m map[string]any, keys ...string) (any, bool) { - for _, key := range keys { - val, ok := m[key] - if !ok { - return nil, false - } - if m, ok = val.(map[string]any); !ok { - return val, true - } - } - return m, true -} - -func deepSet(m map[string]any, keys []string, value any) { - for i := 0; i < len(keys)-1; i++ { - key := keys[i] - if _, ok := m[key]; !ok { - m[key] = make(map[string]any) - } - m = m[key].(map[string]any) - } - m[keys[len(keys)-1]] = value -} - -func findNestedSchema(parentSchema *openapi3.SchemaRef, keys []string) (*openapi3.SchemaRef, error) { - currentSchema := parentSchema - for _, key := range keys { - if currentSchema.Value.Type.Includes(openapi3.TypeArray) { - currentSchema = currentSchema.Value.Items - } else { - propertySchema, ok := currentSchema.Value.Properties[key] - if !ok { - if currentSchema.Value.AdditionalProperties.Schema == nil { - return nil, fmt.Errorf("nested schema for key %q not found", key) - } - currentSchema = currentSchema.Value.AdditionalProperties.Schema - continue - } - currentSchema = propertySchema - } - } - return currentSchema, nil -} - -// makeObject returns an object that contains properties from props. -func makeObject(props map[string]string, schema *openapi3.SchemaRef) (map[string]any, error) { - mobj := make(map[string]any) - - for kk, value := range props { - keys := strings.Split(kk, urlDecoderDelimiter) - if strings.Contains(value, urlDecoderDelimiter) { - // don't support implicit array indexes anymore - p := pathFromKeys(keys) - return nil, &ParseError{path: p, Kind: KindInvalidFormat, Reason: "array items must be set with indexes"} - } - deepSet(mobj, keys, value) - } - r, err := buildResObj(mobj, nil, "", schema) - if err != nil { - return nil, err - } - result, ok := r.(map[string]any) - if !ok { - return nil, &ParseError{Kind: KindOther, Reason: "invalid param object", Value: result} - } - - return result, nil -} - -// example: map[0:map[key:true] 1:map[key:false]] -> [map[key:true] map[key:false]] -func sliceMapToSlice(m map[string]any) ([]any, error) { - var result []any - - keys := make([]int, 0, len(m)) - for k := range m { - key, err := strconv.Atoi(k) - if err != nil { - return nil, fmt.Errorf("array indexes must be integers: %w", err) - } - keys = append(keys, key) - } - max := -1 - for _, k := range keys { - if k > max { - max = k - } - } - for i := 0; i <= max; i++ { - val, ok := m[strconv.Itoa(i)] - if !ok { - result = append(result, nil) - continue - } - result = append(result, val) - } - return result, nil -} - -// buildResObj constructs an object based on a given schema and param values -func buildResObj(params map[string]any, parentKeys []string, key string, schema *openapi3.SchemaRef) (any, error) { - mapKeys := parentKeys - if key != "" { - mapKeys = append(mapKeys, key) - } - - switch { - case schema.Value.Type.Is("array"): - paramArr, ok := deepGet(params, mapKeys...) - if !ok { - return nil, nil - } - t, isMap := paramArr.(map[string]any) - if !isMap { - return nil, &ParseError{path: pathFromKeys(mapKeys), Kind: KindInvalidFormat, Reason: "array items must be set with indexes"} - } - // intermediate arrays have to be instantiated - arr, err := sliceMapToSlice(t) - if err != nil { - return nil, &ParseError{path: pathFromKeys(mapKeys), Kind: KindInvalidFormat, Reason: fmt.Sprintf("could not convert value map to array: %v", err)} - } - resultArr := make([]any /*not 0,*/, len(arr)) - for i := range arr { - r, err := buildResObj(params, mapKeys, strconv.Itoa(i), schema.Value.Items) - if err != nil { - return nil, err - } - if r != nil { - resultArr[i] = r - } - } - return resultArr, nil - case schema.Value.Type.Is("object"): - resultMap := make(map[string]any) - additPropsSchema := schema.Value.AdditionalProperties.Schema - pp, _ := deepGet(params, mapKeys...) - objectParams, ok := pp.(map[string]any) - if !ok { - // not the expected type, but return it either way and leave validation up to ValidateParameter - return pp, nil - } - for k, propSchema := range schema.Value.Properties { - r, err := buildResObj(params, mapKeys, k, propSchema) - if err != nil { - return nil, err - } - if r != nil { - resultMap[k] = r - } - } - if additPropsSchema != nil { - // dynamic creation of possibly nested objects - for k := range objectParams { - r, err := buildResObj(params, mapKeys, k, additPropsSchema) - if err != nil { - return nil, err - } - if r != nil { - resultMap[k] = r - } - } - } - - return resultMap, nil - case len(schema.Value.AnyOf) > 0: - return buildFromSchemas(schema.Value.AnyOf, params, parentKeys, key) - case len(schema.Value.OneOf) > 0: - return buildFromSchemas(schema.Value.OneOf, params, parentKeys, key) - case len(schema.Value.AllOf) > 0: - return buildFromSchemas(schema.Value.AllOf, params, parentKeys, key) - default: - val, ok := deepGet(params, mapKeys...) - if !ok { - // leave validation up to ValidateParameter. here there really is not parameter set - return nil, nil - } - v, ok := val.(string) - if !ok { - return nil, &ParseError{path: pathFromKeys(mapKeys), Kind: KindInvalidFormat, Value: val, Reason: "path is not convertible to primitive"} - } - prim, err := parsePrimitive(v, schema) - if err != nil { - return nil, handlePropParseError(mapKeys, err) - } - - return prim, nil - } -} - -// buildFromSchemas decodes params with anyOf, oneOf, allOf schemas. -func buildFromSchemas(schemas openapi3.SchemaRefs, params map[string]any, mapKeys []string, key string) (any, error) { - resultMap := make(map[string]any) - for _, s := range schemas { - val, err := buildResObj(params, mapKeys, key, s) - if err == nil && val != nil { - - if m, ok := val.(map[string]any); ok { - for k, v := range m { - resultMap[k] = v - } - continue - } - - if a, ok := val.([]any); ok { - if len(a) > 0 { - return a, nil - } - continue - } - - // if its a primitive and not nil just return that and let it be validated - return val, nil - } - } - - if len(resultMap) > 0 { - return resultMap, nil - } - - return nil, nil -} - -func handlePropParseError(path []string, err error) error { - if v, ok := err.(*ParseError); ok { - return &ParseError{path: pathFromKeys(path), Cause: v} - } - return fmt.Errorf("property %q: %w", strings.Join(path, "."), err) -} - -func pathFromKeys(kk []string) []any { - path := make([]any, 0, len(kk)) - for _, v := range kk { - path = append(path, v) - } - return path -} - -// parseArray returns an array that contains items from a raw array. -// Every item is parsed as a primitive value. -// The function returns an error when an error happened while parse array's items. -func parseArray(raw []string, schemaRef *openapi3.SchemaRef) ([]any, error) { - var value []any - for i, v := range raw { - item, err := parsePrimitive(v, schemaRef.Value.Items) - if err != nil { - if v, ok := err.(*ParseError); ok { - return nil, &ParseError{path: []any{i}, Cause: v} - } - return nil, fmt.Errorf("item %d: %w", i, err) - } - - // If the items are nil, then the array is nil. There shouldn't be case where some values are actual primitive - // values and some are nil values. - if item == nil { - return nil, nil - } - value = append(value, item) - } - return value, nil -} - -// parsePrimitive returns a value that is created by parsing a source string to a primitive type -// that is specified by a schema. The function returns nil when the source string is empty. -// The function panics when a schema has a non-primitive type. -func parsePrimitive(raw string, schema *openapi3.SchemaRef) (v any, err error) { - if raw == "" { - return nil, nil - } - for _, typ := range schema.Value.Type.Slice() { - if v, err = parsePrimitiveCase(raw, schema, typ); err == nil { - return - } - } - return -} - -func parsePrimitiveCase(raw string, schema *openapi3.SchemaRef, typ string) (any, error) { - switch typ { - case "integer": - if schema.Value.Format == "int32" { - v, err := strconv.ParseInt(raw, 0, 32) - if err != nil { - return nil, &ParseError{Kind: KindInvalidFormat, Value: raw, Reason: "an invalid " + typ, Cause: err.(*strconv.NumError).Err} - } - return int32(v), nil - } - v, err := strconv.ParseInt(raw, 0, 64) - if err != nil { - return nil, &ParseError{Kind: KindInvalidFormat, Value: raw, Reason: "an invalid " + typ, Cause: err.(*strconv.NumError).Err} - } - return v, nil - case "number": - v, err := strconv.ParseFloat(raw, 64) - if err != nil { - return nil, &ParseError{Kind: KindInvalidFormat, Value: raw, Reason: "an invalid " + typ, Cause: err.(*strconv.NumError).Err} - } - return v, nil - case "boolean": - v, err := strconv.ParseBool(raw) - if err != nil { - return nil, &ParseError{Kind: KindInvalidFormat, Value: raw, Reason: "an invalid " + typ, Cause: err.(*strconv.NumError).Err} - } - return v, nil - case "string": - return raw, nil - default: - return nil, &ParseError{Kind: KindOther, Value: raw, Reason: "schema has non primitive type " + typ} - } -} - -// EncodingFn is a function that returns an encoding of a request body's part. -type EncodingFn func(partName string) *openapi3.Encoding - -// BodyDecoder is an interface to decode a body of a request or response. -// An implementation must return a value that is a primitive, []any, or map[string]any. -type BodyDecoder func(io.Reader, http.Header, *openapi3.SchemaRef, EncodingFn) (any, error) - -// bodyDecoders contains decoders for supported content types of a body. -// By default, there is content type "application/json" is supported only. -var bodyDecoders = make(map[string]BodyDecoder) - -// RegisteredBodyDecoder returns the registered body decoder for the given content type. -// -// If no decoder was registered for the given content type, nil is returned. -// This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines. -func RegisteredBodyDecoder(contentType string) BodyDecoder { - return bodyDecoders[contentType] -} - -// RegisterBodyDecoder registers a request body's decoder for a content type. -// -// If a decoder for the specified content type already exists, the function replaces -// it with the specified decoder. -// This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines. -func RegisterBodyDecoder(contentType string, decoder BodyDecoder) { - if contentType == "" { - panic("contentType is empty") - } - if decoder == nil { - panic("decoder is not defined") - } - bodyDecoders[contentType] = decoder -} - -// UnregisterBodyDecoder dissociates a body decoder from a content type. -// -// Decoding this content type will result in an error. -// This call is not thread-safe: body decoders should not be created/destroyed by multiple goroutines. -func UnregisterBodyDecoder(contentType string) { - if contentType == "" { - panic("contentType is empty") - } - delete(bodyDecoders, contentType) -} - -var headerCT = http.CanonicalHeaderKey("Content-Type") - -const prefixUnsupportedCT = "unsupported content type" - -// decodeBody returns a decoded body. -// The function returns ParseError when a body is invalid. -func decodeBody(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) ( - string, - any, - error, -) { - contentType := header.Get(headerCT) - if contentType == "" { - if _, ok := body.(*multipart.Part); ok { - contentType = "text/plain" - } - } - mediaType := parseMediaType(contentType) - decoder, ok := bodyDecoders[mediaType] - if !ok { - return "", nil, &ParseError{ - Kind: KindUnsupportedFormat, - Reason: fmt.Sprintf("%s %q", prefixUnsupportedCT, mediaType), - } - } - value, err := decoder(body, header, schema, encFn) - if err != nil { - return "", nil, err - } - return mediaType, value, nil -} - -func init() { - RegisterBodyDecoder("application/json", JSONBodyDecoder) - RegisterBodyDecoder("application/json-patch+json", JSONBodyDecoder) - RegisterBodyDecoder("application/octet-stream", FileBodyDecoder) - RegisterBodyDecoder("application/problem+json", JSONBodyDecoder) - RegisterBodyDecoder("application/x-www-form-urlencoded", urlencodedBodyDecoder) - RegisterBodyDecoder("application/x-yaml", yamlBodyDecoder) - RegisterBodyDecoder("application/yaml", yamlBodyDecoder) - RegisterBodyDecoder("application/zip", zipFileBodyDecoder) - RegisterBodyDecoder("multipart/form-data", multipartBodyDecoder) - RegisterBodyDecoder("text/csv", csvBodyDecoder) - RegisterBodyDecoder("text/plain", plainBodyDecoder) -} - -func plainBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (any, error) { - data, err := io.ReadAll(body) - if err != nil { - return nil, &ParseError{Kind: KindInvalidFormat, Cause: err} - } - return string(data), nil -} - -// JSONBodyDecoder decodes a JSON formatted body. It is public so that is easy -// to register additional JSON based formats. -func JSONBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (any, error) { - var value any - dec := json.NewDecoder(body) - dec.UseNumber() - if err := dec.Decode(&value); err != nil { - return nil, &ParseError{Kind: KindInvalidFormat, Cause: err} - } - return value, nil -} - -func yamlBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (any, error) { - var value any - if err := yaml.NewDecoder(body).Decode(&value); err != nil { - return nil, &ParseError{Kind: KindInvalidFormat, Cause: err} - } - return value, nil -} - -func urlencodedBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (any, error) { - // Validate schema of request body. - // By the OpenAPI 3 specification request body's schema must have type "object". - // Properties of the schema describes individual parts of request body. - if !schema.Value.Type.Is("object") { - return nil, errors.New("unsupported schema of request body") - } - for propName, propSchema := range schema.Value.Properties { - propType := propSchema.Value.Type - switch { - case propType.Is("object"): - return nil, fmt.Errorf("unsupported schema of request body's property %q", propName) - case propType.Is("array"): - items := propSchema.Value.Items.Value - if !(items.Type.Is("string") || items.Type.Is("integer") || items.Type.Is("number") || items.Type.Is("boolean")) { - return nil, fmt.Errorf("unsupported schema of request body's property %q", propName) - } - } - } - - // Parse form. - b, err := io.ReadAll(body) - if err != nil { - return nil, err - } - values, err := url.ParseQuery(string(b)) - if err != nil { - return nil, err - } - - // Make an object value from form values. - obj := make(map[string]any) - dec := &urlValuesDecoder{values: values} - - // Decode schema constructs (allOf, anyOf, oneOf) - if err := decodeSchemaConstructs(dec, schema.Value.AllOf, obj, encFn); err != nil { - return nil, err - } - if err := decodeSchemaConstructs(dec, schema.Value.AnyOf, obj, encFn); err != nil { - return nil, err - } - if err := decodeSchemaConstructs(dec, schema.Value.OneOf, obj, encFn); err != nil { - return nil, err - } - - // Decode properties from the main schema - if err := decodeSchemaConstructs(dec, []*openapi3.SchemaRef{schema}, obj, encFn); err != nil { - return nil, err - } - - return obj, nil -} - -// decodeSchemaConstructs tries to decode properties based on provided schemas. -// This function is for decoding purposes only and not for validation. -func decodeSchemaConstructs(dec *urlValuesDecoder, schemas []*openapi3.SchemaRef, obj map[string]any, encFn EncodingFn) error { - for _, schemaRef := range schemas { - for name, prop := range schemaRef.Value.Properties { - value, _, err := decodeProperty(dec, name, prop, encFn) - if err != nil { - continue - } - if existingValue, exists := obj[name]; exists && !isEqual(existingValue, value) { - return fmt.Errorf("conflicting values for property %q", name) - } - obj[name] = value - } - } - - return nil -} - -func isEqual(value1, value2 any) bool { - return reflect.DeepEqual(value1, value2) -} - -func decodeProperty(dec valueDecoder, name string, prop *openapi3.SchemaRef, encFn EncodingFn) (any, bool, error) { - var enc *openapi3.Encoding - if encFn != nil { - enc = encFn(name) - } - sm := enc.SerializationMethod() - return decodeValue(dec, name, sm, prop, false) -} - -func multipartBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (any, error) { - if !schema.Value.Type.Is("object") { - return nil, errors.New("unsupported schema of request body") - } - - // Parse form. - values := make(map[string][]any) - contentType := header.Get(headerCT) - _, params, err := mime.ParseMediaType(contentType) - if err != nil { - return nil, err - } - mr := multipart.NewReader(body, params["boundary"]) - for { - var part *multipart.Part - if part, err = mr.NextPart(); err == io.EOF { - break - } - if err != nil { - return nil, err - } - - var ( - name = part.FormName() - enc *openapi3.Encoding - ) - if encFn != nil { - enc = encFn(name) - } - subEncFn := func(string) *openapi3.Encoding { return enc } - - var valueSchema *openapi3.SchemaRef - if len(schema.Value.AllOf) > 0 { - var exists bool - for _, sr := range schema.Value.AllOf { - if valueSchema, exists = sr.Value.Properties[name]; exists { - break - } - } - if !exists { - return nil, &ParseError{Kind: KindOther, Cause: fmt.Errorf("part %s: undefined", name)} - } - } else { - // If the property's schema has type "array" it is means that the form contains a few parts with the same name. - // Every such part has a type that is defined by an items schema in the property's schema. - var exists bool - if valueSchema, exists = schema.Value.Properties[name]; !exists { - if anyProperties := schema.Value.AdditionalProperties.Has; anyProperties != nil { - switch *anyProperties { - case true: - // additionalProperties: true - continue - default: - // additionalProperties: false - return nil, &ParseError{Kind: KindOther, Cause: fmt.Errorf("part %s: undefined", name)} - } - } - if schema.Value.AdditionalProperties.Schema == nil { - return nil, &ParseError{Kind: KindOther, Cause: fmt.Errorf("part %s: undefined", name)} - } - if valueSchema, exists = schema.Value.AdditionalProperties.Schema.Value.Properties[name]; !exists { - return nil, &ParseError{Kind: KindOther, Cause: fmt.Errorf("part %s: undefined", name)} - } - } - if valueSchema.Value.Type.Is("array") { - valueSchema = valueSchema.Value.Items - } - } - - var value any - if _, value, err = decodeBody(part, http.Header(part.Header), valueSchema, subEncFn); err != nil { - if v, ok := err.(*ParseError); ok { - return nil, &ParseError{path: []any{name}, Cause: v} - } - return nil, fmt.Errorf("part %s: %w", name, err) - } - values[name] = append(values[name], value) - } - - allTheProperties := make(map[string]*openapi3.SchemaRef) - if len(schema.Value.AllOf) > 0 { - for _, sr := range schema.Value.AllOf { - for k, v := range sr.Value.Properties { - allTheProperties[k] = v - } - if addProps := sr.Value.AdditionalProperties.Schema; addProps != nil { - for k, v := range addProps.Value.Properties { - allTheProperties[k] = v - } - } - } - } else { - for k, v := range schema.Value.Properties { - allTheProperties[k] = v - } - if addProps := schema.Value.AdditionalProperties.Schema; addProps != nil { - for k, v := range addProps.Value.Properties { - allTheProperties[k] = v - } - } - } - - // Make an object value from form values. - obj := make(map[string]any) - for name, prop := range allTheProperties { - vv := values[name] - if len(vv) == 0 { - continue - } - if prop.Value.Type.Is("array") { - obj[name] = vv - } else { - obj[name] = vv[0] - } - } - - return obj, nil -} - -// FileBodyDecoder is a body decoder that decodes a file body to a string. -func FileBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (any, error) { - data, err := io.ReadAll(body) - if err != nil { - return nil, err - } - return string(data), nil -} - -// zipFileBodyDecoder is a body decoder that decodes a zip file body to a string. -func zipFileBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (any, error) { - buff := bytes.NewBuffer([]byte{}) - size, err := io.Copy(buff, body) - if err != nil { - return nil, err - } - - zr, err := zip.NewReader(bytes.NewReader(buff.Bytes()), size) - if err != nil { - return nil, err - } - - const bufferSize = 256 - content := make([]byte, 0, bufferSize*len(zr.File)) - buffer := make([]byte /*0,*/, bufferSize) - - for _, f := range zr.File { - err := func() error { - rc, err := f.Open() - if err != nil { - return err - } - defer func() { - _ = rc.Close() - }() - - for { - n, err := rc.Read(buffer) - if 0 < n { - content = append(content, buffer...) - } - if err == io.EOF { - break - } - if err != nil { - return err - } - } - - return nil - }() - if err != nil { - return nil, err - } - } - - return string(content), nil -} - -// csvBodyDecoder is a body decoder that decodes a csv body to a string. -func csvBodyDecoder(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn EncodingFn) (any, error) { - r := csv.NewReader(body) - - var sb strings.Builder - for { - record, err := r.Read() - if err == io.EOF { - break - } - if err != nil { - return nil, err - } - - sb.WriteString(strings.Join(record, ",")) - sb.WriteString("\n") - } - - return sb.String(), nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/req_resp_encoder.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/req_resp_encoder.go deleted file mode 100644 index 5c328c756..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/req_resp_encoder.go +++ /dev/null @@ -1,58 +0,0 @@ -package openapi3filter - -import ( - "encoding/json" - "fmt" - "sync" -) - -func encodeBody(body any, mediaType string) ([]byte, error) { - if encoder := RegisteredBodyEncoder(mediaType); encoder != nil { - return encoder(body) - } - return nil, &ParseError{ - Kind: KindUnsupportedFormat, - Reason: fmt.Sprintf("%s %q", prefixUnsupportedCT, mediaType), - } -} - -// BodyEncoder really is an (encoding/json).Marshaler -type BodyEncoder func(body any) ([]byte, error) - -var bodyEncodersM sync.RWMutex -var bodyEncoders = map[string]BodyEncoder{ - "application/json": json.Marshal, -} - -// RegisterBodyEncoder enables package-wide decoding of contentType values -func RegisterBodyEncoder(contentType string, encoder BodyEncoder) { - if contentType == "" { - panic("contentType is empty") - } - if encoder == nil { - panic("encoder is not defined") - } - bodyEncodersM.Lock() - bodyEncoders[contentType] = encoder - bodyEncodersM.Unlock() -} - -// UnregisterBodyEncoder disables package-wide decoding of contentType values -func UnregisterBodyEncoder(contentType string) { - if contentType == "" { - panic("contentType is empty") - } - bodyEncodersM.Lock() - delete(bodyEncoders, contentType) - bodyEncodersM.Unlock() -} - -// RegisteredBodyEncoder returns the registered body encoder for the given content type. -// -// If no encoder was registered for the given content type, nil is returned. -func RegisteredBodyEncoder(contentType string) BodyEncoder { - bodyEncodersM.RLock() - mayBE := bodyEncoders[contentType] - bodyEncodersM.RUnlock() - return mayBE -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_request.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_request.go deleted file mode 100644 index bf4771a98..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_request.go +++ /dev/null @@ -1,431 +0,0 @@ -package openapi3filter - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "sort" - - "github.com/getkin/kin-openapi/openapi3" -) - -// ErrAuthenticationServiceMissing is returned when no authentication service -// is defined for the request validator -var ErrAuthenticationServiceMissing = errors.New("missing AuthenticationFunc") - -// ErrInvalidRequired is returned when a required value of a parameter or request body is not defined. -var ErrInvalidRequired = errors.New("value is required but missing") - -// ErrInvalidEmptyValue is returned when a value of a parameter or request body is empty while it's not allowed. -var ErrInvalidEmptyValue = errors.New("empty value is not allowed") - -// ValidateRequest is used to validate the given input according to previous -// loaded OpenAPIv3 spec. If the input does not match the OpenAPIv3 spec, a -// non-nil error will be returned. -// -// Note: One can tune the behavior of uniqueItems: true verification -// by registering a custom function with openapi3.RegisterArrayUniqueItemsChecker -func ValidateRequest(ctx context.Context, input *RequestValidationInput) (err error) { - var me openapi3.MultiError - - options := input.Options - if options == nil { - options = &Options{} - } - route := input.Route - operation := route.Operation - operationParameters := operation.Parameters - pathItemParameters := route.PathItem.Parameters - - // Security - security := operation.Security - // If there aren't any security requirements for the operation - if security == nil { - // Use the global security requirements. - security = &route.Spec.Security - } - if security != nil { - if err = ValidateSecurityRequirements(ctx, input, *security); err != nil && !options.MultiError { - return - } - if err != nil { - me = append(me, err) - } - } - - // For each parameter of the PathItem - for _, parameterRef := range pathItemParameters { - parameter := parameterRef.Value - if operationParameters != nil { - if override := operationParameters.GetByInAndName(parameter.In, parameter.Name); override != nil { - continue - } - } - - if err = ValidateParameter(ctx, input, parameter); err != nil && !options.MultiError { - return - } - if err != nil { - me = append(me, err) - } - } - - // For each parameter of the Operation - for _, parameter := range operationParameters { - if options.ExcludeRequestQueryParams && parameter.Value.In == openapi3.ParameterInQuery { - continue - } - if err = ValidateParameter(ctx, input, parameter.Value); err != nil && !options.MultiError { - return - } - if err != nil { - me = append(me, err) - } - } - - // RequestBody - requestBody := operation.RequestBody - if requestBody != nil && !options.ExcludeRequestBody { - if err = ValidateRequestBody(ctx, input, requestBody.Value); err != nil && !options.MultiError { - return - } - if err != nil { - me = append(me, err) - } - } - - if len(me) > 0 { - return me - } - return -} - -// appendToQueryValues adds to query parameters each value in the provided slice -func appendToQueryValues[T any](q url.Values, parameterName string, v []T) { - for _, i := range v { - q.Add(parameterName, fmt.Sprintf("%v", i)) - } -} - -// populateDefaultQueryParameters populates default values inside query parameters, while ensuring types are respected -func populateDefaultQueryParameters(q url.Values, parameterName string, value any) { - switch t := value.(type) { - case []interface{}: - appendToQueryValues(q, parameterName, t) - default: - q.Add(parameterName, fmt.Sprintf("%v", value)) - } - -} - -// ValidateParameter validates a parameter's value by JSON schema. -// The function returns RequestError with a ParseError cause when unable to parse a value. -// The function returns RequestError with ErrInvalidRequired cause when a value of a required parameter is not defined. -// The function returns RequestError with ErrInvalidEmptyValue cause when a value of a required parameter is not defined. -// The function returns RequestError with a openapi3.SchemaError cause when a value is invalid by JSON schema. -func ValidateParameter(ctx context.Context, input *RequestValidationInput, parameter *openapi3.Parameter) error { - if parameter.Schema == nil && parameter.Content == nil { - // We have no schema for the parameter. Assume that everything passes - // a schema-less check, but this could also be an error. The OpenAPI - // validation allows this to happen. - return nil - } - - options := input.Options - if options == nil { - options = &Options{} - } - - var value any - var err error - var found bool - var schema *openapi3.Schema - - // Validation will ensure that we either have content or schema. - if parameter.Content != nil { - if value, schema, found, err = decodeContentParameter(parameter, input); err != nil { - return &RequestError{Input: input, Parameter: parameter, Err: err} - } - } else { - if value, found, err = decodeStyledParameter(parameter, input); err != nil { - return &RequestError{Input: input, Parameter: parameter, Err: err} - } - schema = parameter.Schema.Value - } - - // Set default value if needed - if !options.SkipSettingDefaults && value == nil && schema != nil { - value = schema.Default - for _, subSchema := range schema.AllOf { - if subSchema.Value.Default != nil { - value = subSchema.Value.Default - break // This is not a validation of the schema itself, so use the first default value. - } - } - - if value != nil { - req := input.Request - switch parameter.In { - case openapi3.ParameterInPath: - // Path parameters are required. - // Next check `parameter.Required && !found` will catch this. - case openapi3.ParameterInQuery: - q := req.URL.Query() - populateDefaultQueryParameters(q, parameter.Name, value) - req.URL.RawQuery = q.Encode() - case openapi3.ParameterInHeader: - req.Header.Add(parameter.Name, fmt.Sprintf("%v", value)) - case openapi3.ParameterInCookie: - req.AddCookie(&http.Cookie{ - Name: parameter.Name, - Value: fmt.Sprintf("%v", value), - }) - } - } - } - - // Validate a parameter's value and presence. - if parameter.Required && !found { - return &RequestError{Input: input, Parameter: parameter, Reason: ErrInvalidRequired.Error(), Err: ErrInvalidRequired} - } - - if isNilValue(value) { - if !parameter.AllowEmptyValue && found { - return &RequestError{Input: input, Parameter: parameter, Reason: ErrInvalidEmptyValue.Error(), Err: ErrInvalidEmptyValue} - } - return nil - } - if schema == nil { - // A parameter's schema is not defined so skip validation of a parameter's value. - return nil - } - - var opts []openapi3.SchemaValidationOption - if options.MultiError { - opts = make([]openapi3.SchemaValidationOption, 0, 1) - opts = append(opts, openapi3.MultiErrors()) - } - if options.customSchemaErrorFunc != nil { - opts = append(opts, openapi3.SetSchemaErrorMessageCustomizer(options.customSchemaErrorFunc)) - } - if err = schema.VisitJSON(value, opts...); err != nil { - return &RequestError{Input: input, Parameter: parameter, Err: err} - } - return nil -} - -const prefixInvalidCT = "header Content-Type has unexpected value" - -// ValidateRequestBody validates data of a request's body. -// -// The function returns RequestError with ErrInvalidRequired cause when a value is required but not defined. -// The function returns RequestError with a openapi3.SchemaError cause when a value is invalid by JSON schema. -func ValidateRequestBody(ctx context.Context, input *RequestValidationInput, requestBody *openapi3.RequestBody) error { - var ( - req = input.Request - data []byte - ) - - options := input.Options - if options == nil { - options = &Options{} - } - - if req.Body != http.NoBody && req.Body != nil { - defer req.Body.Close() - var err error - if data, err = io.ReadAll(req.Body); err != nil { - return &RequestError{ - Input: input, - RequestBody: requestBody, - Reason: "reading failed", - Err: err, - } - } - // Put the data back into the input - req.Body = nil - if req.GetBody != nil { - if req.Body, err = req.GetBody(); err != nil { - req.Body = nil - } - } - if req.Body == nil { - req.ContentLength = int64(len(data)) - req.GetBody = func() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewReader(data)), nil - } - req.Body, _ = req.GetBody() // no error return - } - } - - if len(data) == 0 { - if requestBody.Required { - return &RequestError{Input: input, RequestBody: requestBody, Err: ErrInvalidRequired} - } - return nil - } - - content := requestBody.Content - if len(content) == 0 { - // A request's body does not have declared content, so skip validation. - return nil - } - - inputMIME := req.Header.Get(headerCT) - contentType := requestBody.Content.Get(inputMIME) - if contentType == nil { - return &RequestError{ - Input: input, - RequestBody: requestBody, - Reason: fmt.Sprintf("%s %q", prefixInvalidCT, inputMIME), - } - } - - if contentType.Schema == nil { - // A JSON schema that describes the received data is not declared, so skip validation. - return nil - } - - encFn := func(name string) *openapi3.Encoding { return contentType.Encoding[name] } - mediaType, value, err := decodeBody(bytes.NewReader(data), req.Header, contentType.Schema, encFn) - if err != nil { - return &RequestError{ - Input: input, - RequestBody: requestBody, - Reason: "failed to decode request body", - Err: err, - } - } - - defaultsSet := false - opts := make([]openapi3.SchemaValidationOption, 0, 4) // 4 potential opts here - opts = append(opts, openapi3.VisitAsRequest()) - if !options.SkipSettingDefaults { - opts = append(opts, openapi3.DefaultsSet(func() { defaultsSet = true })) - } - if options.MultiError { - opts = append(opts, openapi3.MultiErrors()) - } - if options.customSchemaErrorFunc != nil { - opts = append(opts, openapi3.SetSchemaErrorMessageCustomizer(options.customSchemaErrorFunc)) - } - if options.ExcludeReadOnlyValidations { - opts = append(opts, openapi3.DisableReadOnlyValidation()) - } - if options.RegexCompiler != nil { - opts = append(opts, openapi3.SetSchemaRegexCompiler(options.RegexCompiler)) - } - - // Validate JSON with the schema - if err := contentType.Schema.Value.VisitJSON(value, opts...); err != nil { - schemaId := getSchemaIdentifier(contentType.Schema) - schemaId = prependSpaceIfNeeded(schemaId) - return &RequestError{ - Input: input, - RequestBody: requestBody, - Reason: fmt.Sprintf("doesn't match schema%s", schemaId), - Err: err, - } - } - - if defaultsSet { - var err error - if data, err = encodeBody(value, mediaType); err != nil { - return &RequestError{ - Input: input, - RequestBody: requestBody, - Reason: "rewriting failed", - Err: err, - } - } - // Put the data back into the input - if req.Body != nil { - req.Body.Close() - } - req.ContentLength = int64(len(data)) - req.GetBody = func() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewReader(data)), nil - } - req.Body, _ = req.GetBody() // no error return - } - - return nil -} - -// ValidateSecurityRequirements goes through multiple OpenAPI 3 security -// requirements in order and returns nil on the first valid requirement. -// If no requirement is met, errors are returned in order. -func ValidateSecurityRequirements(ctx context.Context, input *RequestValidationInput, srs openapi3.SecurityRequirements) error { - if len(srs) == 0 { - return nil - } - var errs []error - for _, sr := range srs { - if err := validateSecurityRequirement(ctx, input, sr); err != nil { - if len(errs) == 0 { - errs = make([]error, 0, len(srs)) - } - errs = append(errs, err) - continue - } - return nil - } - return &SecurityRequirementsError{ - SecurityRequirements: srs, - Errors: errs, - } -} - -// validateSecurityRequirement validates a single OpenAPI 3 security requirement -func validateSecurityRequirement(ctx context.Context, input *RequestValidationInput, securityRequirement openapi3.SecurityRequirement) error { - names := make([]string, 0, len(securityRequirement)) - for name := range securityRequirement { - names = append(names, name) - } - sort.Strings(names) - - // Get authentication function - options := input.Options - if options == nil { - options = &Options{} - } - f := options.AuthenticationFunc - if f == nil { - return ErrAuthenticationServiceMissing - } - - var securitySchemes openapi3.SecuritySchemes - if components := input.Route.Spec.Components; components != nil { - securitySchemes = components.SecuritySchemes - } - - // For each scheme for the requirement - for _, name := range names { - var securityScheme *openapi3.SecurityScheme - if securitySchemes != nil { - if ref := securitySchemes[name]; ref != nil { - securityScheme = ref.Value - } - } - if securityScheme == nil { - return &RequestError{ - Input: input, - Err: fmt.Errorf("security scheme %q is not declared", name), - } - } - scopes := securityRequirement[name] - if err := f(ctx, &AuthenticationInput{ - RequestValidationInput: input, - SecuritySchemeName: name, - SecurityScheme: securityScheme, - Scopes: scopes, - }); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_request_input.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_request_input.go deleted file mode 100644 index c7565ebb7..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_request_input.go +++ /dev/null @@ -1,38 +0,0 @@ -package openapi3filter - -import ( - "net/http" - "net/url" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/getkin/kin-openapi/routers" -) - -// A ContentParameterDecoder takes a parameter definition from the OpenAPI spec, -// and the value which we received for it. It is expected to return the -// value unmarshaled into an interface which can be traversed for -// validation, it should also return the schema to be used for validating the -// object, since there can be more than one in the content spec. -// -// If a query parameter appears multiple times, values[] will have more -// than one value, but for all other parameter types it should have just -// one. -type ContentParameterDecoder func(param *openapi3.Parameter, values []string) (any, *openapi3.Schema, error) - -type RequestValidationInput struct { - Request *http.Request - PathParams map[string]string - QueryParams url.Values - Route *routers.Route - Options *Options - ParamDecoder ContentParameterDecoder -} - -func (input *RequestValidationInput) GetQueryParams() url.Values { - q := input.QueryParams - if q == nil { - q = input.Request.URL.Query() - input.QueryParams = q - } - return q -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_response.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_response.go deleted file mode 100644 index 77f127e73..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_response.go +++ /dev/null @@ -1,224 +0,0 @@ -// Package openapi3filter validates that requests and inputs request an OpenAPI 3 specification file. -package openapi3filter - -import ( - "bytes" - "context" - "fmt" - "io" - "net/http" - "sort" - "strings" - - "github.com/getkin/kin-openapi/openapi3" -) - -// ValidateResponse is used to validate the given input according to previous -// loaded OpenAPIv3 spec. If the input does not match the OpenAPIv3 spec, a -// non-nil error will be returned. -// -// Note: One can tune the behavior of uniqueItems: true verification -// by registering a custom function with openapi3.RegisterArrayUniqueItemsChecker -func ValidateResponse(ctx context.Context, input *ResponseValidationInput) error { - req := input.RequestValidationInput.Request - switch req.Method { - case "HEAD": - return nil - } - status := input.Status - - // These status codes will never be validated. - // TODO: The list is probably missing some. - switch status { - case http.StatusNotModified, - http.StatusPermanentRedirect, - http.StatusTemporaryRedirect, - http.StatusMovedPermanently: - return nil - } - route := input.RequestValidationInput.Route - options := input.Options - if options == nil { - options = &Options{} - } - - // Find input for the current status - responses := route.Operation.Responses - if responses.Len() == 0 { - return nil - } - responseRef := responses.Status(status) // Response - if responseRef == nil { - responseRef = responses.Default() // Default input - } - if responseRef == nil { - // By default, status that is not documented is allowed. - if !options.IncludeResponseStatus { - return nil - } - return &ResponseError{Input: input, Reason: "status is not supported"} - } - response := responseRef.Value - if response == nil { - return &ResponseError{Input: input, Reason: "response has not been resolved"} - } - - opts := make([]openapi3.SchemaValidationOption, 0, 3) // 3 potential options here - if options.MultiError { - opts = append(opts, openapi3.MultiErrors()) - } - if options.customSchemaErrorFunc != nil { - opts = append(opts, openapi3.SetSchemaErrorMessageCustomizer(options.customSchemaErrorFunc)) - } - if options.ExcludeWriteOnlyValidations { - opts = append(opts, openapi3.DisableWriteOnlyValidation()) - } - - headers := make([]string, 0, len(response.Headers)) - for k := range response.Headers { - if k != headerCT { - headers = append(headers, k) - } - } - sort.Strings(headers) - for _, headerName := range headers { - headerRef := response.Headers[headerName] - if err := validateResponseHeader(headerName, headerRef, input, opts); err != nil { - return err - } - } - - if options.ExcludeResponseBody { - // A user turned off validation of a response's body. - return nil - } - - content := response.Content - if len(content) == 0 || options.ExcludeResponseBody { - // An operation does not contains a validation schema for responses with this status code. - return nil - } - - inputMIME := input.Header.Get(headerCT) - contentType := content.Get(inputMIME) - if contentType == nil { - return &ResponseError{ - Input: input, - Reason: fmt.Sprintf("response %s: %q", prefixInvalidCT, inputMIME), - } - } - - if contentType.Schema == nil { - // An operation does not contains a validation schema for responses with this status code. - return nil - } - - // Read response's body. - body := input.Body - - // Response would contain partial or empty input body - // after we begin reading. - // Ensure that this doesn't happen. - input.Body = nil - - // Ensure we close the reader - defer body.Close() - - // Read all - data, err := io.ReadAll(body) - if err != nil { - return &ResponseError{ - Input: input, - Reason: "failed to read response body", - Err: err, - } - } - - // Put the data back into the response. - input.SetBodyBytes(data) - - encFn := func(name string) *openapi3.Encoding { return contentType.Encoding[name] } - _, value, err := decodeBody(bytes.NewBuffer(data), input.Header, contentType.Schema, encFn) - if err != nil { - return &ResponseError{ - Input: input, - Reason: "failed to decode response body", - Err: err, - } - } - - // Validate data with the schema. - if err := contentType.Schema.Value.VisitJSON(value, append(opts, openapi3.VisitAsResponse())...); err != nil { - schemaId := getSchemaIdentifier(contentType.Schema) - schemaId = prependSpaceIfNeeded(schemaId) - return &ResponseError{ - Input: input, - Reason: fmt.Sprintf("response body doesn't match schema%s", schemaId), - Err: err, - } - } - return nil -} - -func validateResponseHeader(headerName string, headerRef *openapi3.HeaderRef, input *ResponseValidationInput, opts []openapi3.SchemaValidationOption) error { - var err error - var decodedValue any - var found bool - var sm *openapi3.SerializationMethod - dec := &headerParamDecoder{header: input.Header} - - if sm, err = headerRef.Value.SerializationMethod(); err != nil { - return &ResponseError{ - Input: input, - Reason: fmt.Sprintf("unable to get header %q serialization method", headerName), - Err: err, - } - } - - if decodedValue, found, err = decodeValue(dec, headerName, sm, headerRef.Value.Schema, headerRef.Value.Required); err != nil { - return &ResponseError{ - Input: input, - Reason: fmt.Sprintf("unable to decode header %q value", headerName), - Err: err, - } - } - - if found { - if err = headerRef.Value.Schema.Value.VisitJSON(decodedValue, opts...); err != nil { - return &ResponseError{ - Input: input, - Reason: fmt.Sprintf("response header %q doesn't match schema", headerName), - Err: err, - } - } - } else if headerRef.Value.Required { - return &ResponseError{ - Input: input, - Reason: fmt.Sprintf("response header %q missing", headerName), - } - } - return nil -} - -// getSchemaIdentifier gets something by which a schema could be identified. -// A schema by itself doesn't have a true identity field. This function makes -// a best effort to get a value that can fill that void. -func getSchemaIdentifier(schema *openapi3.SchemaRef) string { - var id string - - if schema != nil { - id = strings.TrimSpace(schema.Ref) - } - if id == "" && schema.Value != nil { - id = strings.TrimSpace(schema.Value.Title) - } - - return id -} - -func prependSpaceIfNeeded(value string) string { - if len(value) > 0 { - value = " " + value - } - return value -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_response_input.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_response_input.go deleted file mode 100644 index 5592fe61d..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/validate_response_input.go +++ /dev/null @@ -1,41 +0,0 @@ -package openapi3filter - -import ( - "bytes" - "io" - "net/http" -) - -type ResponseValidationInput struct { - RequestValidationInput *RequestValidationInput - Status int - Header http.Header - Body io.ReadCloser - Options *Options -} - -func (input *ResponseValidationInput) SetBodyBytes(value []byte) *ResponseValidationInput { - input.Body = io.NopCloser(bytes.NewReader(value)) - return input -} - -var JSONPrefixes = []string{ - ")]}',\n", -} - -// TrimJSONPrefix trims one of the possible prefixes -func TrimJSONPrefix(data []byte) []byte { -search: - for _, prefix := range JSONPrefixes { - if len(data) < len(prefix) { - continue - } - for i, b := range data[:len(prefix)] { - if b != prefix[i] { - continue search - } - } - return data[len(prefix):] - } - return data -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_error.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_error.go deleted file mode 100644 index 4153eef7e..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_error.go +++ /dev/null @@ -1,84 +0,0 @@ -package openapi3filter - -import ( - "bytes" - "strconv" -) - -// ValidationError struct provides granular error information -// useful for communicating issues back to end user and developer. -// Based on https://jsonapi.org/format/#error-objects -type ValidationError struct { - // A unique identifier for this particular occurrence of the problem. - Id string `json:"id,omitempty" yaml:"id,omitempty"` - // The HTTP status code applicable to this problem. - Status int `json:"status,omitempty" yaml:"status,omitempty"` - // An application-specific error code, expressed as a string value. - Code string `json:"code,omitempty" yaml:"code,omitempty"` - // A short, human-readable summary of the problem. It **SHOULD NOT** change from occurrence to occurrence of the problem, except for purposes of localization. - Title string `json:"title,omitempty" yaml:"title,omitempty"` - // A human-readable explanation specific to this occurrence of the problem. - Detail string `json:"detail,omitempty" yaml:"detail,omitempty"` - // An object containing references to the source of the error - Source *ValidationErrorSource `json:"source,omitempty" yaml:"source,omitempty"` -} - -// ValidationErrorSource struct -type ValidationErrorSource struct { - // A JSON Pointer [RFC6901] to the associated entity in the request document [e.g. \"/data\" for a primary data object, or \"/data/attributes/title\" for a specific attribute]. - Pointer string `json:"pointer,omitempty" yaml:"pointer,omitempty"` - // A string indicating which query parameter caused the error. - Parameter string `json:"parameter,omitempty" yaml:"parameter,omitempty"` -} - -var _ error = &ValidationError{} - -// Error implements the error interface. -func (e *ValidationError) Error() string { - b := bytes.NewBufferString("[") - if e.Status != 0 { - b.WriteString(strconv.Itoa(e.Status)) - } - b.WriteString("]") - b.WriteString("[") - if e.Code != "" { - b.WriteString(e.Code) - } - b.WriteString("]") - b.WriteString("[") - if e.Id != "" { - b.WriteString(e.Id) - } - b.WriteString("]") - b.WriteString(" ") - if e.Title != "" { - b.WriteString(e.Title) - b.WriteString(" ") - } - if e.Detail != "" { - b.WriteString("| ") - b.WriteString(e.Detail) - b.WriteString(" ") - } - if e.Source != nil { - b.WriteString("[source ") - if e.Source.Parameter != "" { - b.WriteString("parameter=") - b.WriteString(e.Source.Parameter) - } else if e.Source.Pointer != "" { - b.WriteString("pointer=") - b.WriteString(e.Source.Pointer) - } - b.WriteString("]") - } - - if b.Len() == 0 { - return "no error" - } - return b.String() -} - -// StatusCode implements the StatusCoder interface for DefaultErrorEncoder -func (e *ValidationError) StatusCode() int { - return e.Status -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_error_encoder.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_error_encoder.go deleted file mode 100644 index c03fd1392..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_error_encoder.go +++ /dev/null @@ -1,186 +0,0 @@ -package openapi3filter - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/getkin/kin-openapi/routers" -) - -// ValidationErrorEncoder wraps a base ErrorEncoder to handle ValidationErrors -type ValidationErrorEncoder struct { - Encoder ErrorEncoder -} - -// Encode implements the ErrorEncoder interface for encoding ValidationErrors -func (enc *ValidationErrorEncoder) Encode(ctx context.Context, err error, w http.ResponseWriter) { - enc.Encoder(ctx, ConvertErrors(err), w) -} - -// ConvertErrors converts all errors to the appropriate error format. -func ConvertErrors(err error) error { - if e, ok := err.(*routers.RouteError); ok { - return convertRouteError(e) - } - - e, ok := err.(*RequestError) - if !ok { - return err - } - - var cErr *ValidationError - if e.Err == nil { - cErr = convertBasicRequestError(e) - } else if e.Err == ErrInvalidRequired { - cErr = convertErrInvalidRequired(e) - } else if e.Err == ErrInvalidEmptyValue { - cErr = convertErrInvalidEmptyValue(e) - } else if innerErr, ok := e.Err.(*ParseError); ok { - cErr = convertParseError(e, innerErr) - } else if innerErr, ok := e.Err.(*openapi3.SchemaError); ok { - cErr = convertSchemaError(e, innerErr) - } - - if cErr != nil { - return cErr - } - return err -} - -func convertRouteError(e *routers.RouteError) *ValidationError { - status := http.StatusNotFound - if e.Error() == routers.ErrMethodNotAllowed.Error() { - status = http.StatusMethodNotAllowed - } - return &ValidationError{Status: status, Title: e.Error()} -} - -func convertBasicRequestError(e *RequestError) *ValidationError { - if strings.HasPrefix(e.Reason, prefixInvalidCT) { - if strings.HasSuffix(e.Reason, `""`) { - return &ValidationError{ - Status: http.StatusUnsupportedMediaType, - Title: "header Content-Type is required", - } - } - return &ValidationError{ - Status: http.StatusUnsupportedMediaType, - Title: prefixUnsupportedCT + strings.TrimPrefix(e.Reason, prefixInvalidCT), - } - } - return &ValidationError{ - Status: http.StatusBadRequest, - Title: e.Error(), - } -} - -func convertErrInvalidRequired(e *RequestError) *ValidationError { - if e.Err == ErrInvalidRequired && e.Parameter != nil { - return &ValidationError{ - Status: http.StatusBadRequest, - Title: fmt.Sprintf("parameter %q in %s is required", e.Parameter.Name, e.Parameter.In), - } - } - return &ValidationError{ - Status: http.StatusBadRequest, - Title: e.Error(), - } -} - -func convertErrInvalidEmptyValue(e *RequestError) *ValidationError { - if e.Err == ErrInvalidEmptyValue && e.Parameter != nil { - return &ValidationError{ - Status: http.StatusBadRequest, - Title: fmt.Sprintf("parameter %q in %s is not allowed to be empty", e.Parameter.Name, e.Parameter.In), - } - } - return &ValidationError{ - Status: http.StatusBadRequest, - Title: e.Error(), - } -} - -func convertParseError(e *RequestError, innerErr *ParseError) *ValidationError { - // We treat path params of the wrong type like a 404 instead of a 400 - if innerErr.Kind == KindInvalidFormat && e.Parameter != nil && e.Parameter.In == "path" { - return &ValidationError{ - Status: http.StatusNotFound, - Title: fmt.Sprintf("resource not found with %q value: %v", e.Parameter.Name, innerErr.Value), - } - } else if strings.HasPrefix(innerErr.Reason, prefixUnsupportedCT) { - return &ValidationError{ - Status: http.StatusUnsupportedMediaType, - Title: innerErr.Reason, - } - } else if innerErr.RootCause() != nil { - if rootErr, ok := innerErr.Cause.(*ParseError); ok && - rootErr.Kind == KindInvalidFormat && e.Parameter.In == "query" { - return &ValidationError{ - Status: http.StatusBadRequest, - Title: fmt.Sprintf("parameter %q in %s is invalid: %v is %s", - e.Parameter.Name, e.Parameter.In, rootErr.Value, rootErr.Reason), - } - } - return &ValidationError{ - Status: http.StatusBadRequest, - Title: innerErr.Reason, - } - } - return nil -} - -func convertSchemaError(e *RequestError, innerErr *openapi3.SchemaError) *ValidationError { - cErr := &ValidationError{Title: innerErr.Reason} - - // Handle "Origin" error - if originErr, ok := innerErr.Origin.(*openapi3.SchemaError); ok { - cErr = convertSchemaError(e, originErr) - } - - // Add http status code - if e.Parameter != nil { - cErr.Status = http.StatusBadRequest - } else if e.RequestBody != nil { - cErr.Status = http.StatusUnprocessableEntity - } - - // Add error source - if e.Parameter != nil { - // We have a JSONPointer in the query param too so need to - // make sure 'Parameter' check takes priority over 'Pointer' - cErr.Source = &ValidationErrorSource{Parameter: e.Parameter.Name} - } else if ptr := innerErr.JSONPointer(); ptr != nil { - cErr.Source = &ValidationErrorSource{Pointer: toJSONPointer(ptr)} - } - - // Add details on allowed values for enums - if innerErr.SchemaField == "enum" { - enums := make([]string, 0, len(innerErr.Schema.Enum)) - for _, enum := range innerErr.Schema.Enum { - enums = append(enums, fmt.Sprintf("%v", enum)) - } - cErr.Detail = fmt.Sprintf("value %v at %s must be one of: %s", - innerErr.Value, - toJSONPointer(innerErr.JSONPointer()), - strings.Join(enums, ", ")) - value := fmt.Sprintf("%v", innerErr.Value) - if e.Parameter != nil && - (e.Parameter.Explode == nil || *e.Parameter.Explode) && - (e.Parameter.Style == "" || e.Parameter.Style == "form") && - strings.Contains(value, ",") { - parts := strings.Split(value, ",") - cErr.Detail = fmt.Sprintf("%s; perhaps you intended '?%s=%s'", - cErr.Detail, - e.Parameter.Name, - strings.Join(parts, "&"+e.Parameter.Name+"=")) - } - } - return cErr -} - -func toJSONPointer(reversePath []string) string { - return "/" + strings.Join(reversePath, "/") -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_handler.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_handler.go deleted file mode 100644 index d4bb1efa0..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_handler.go +++ /dev/null @@ -1,107 +0,0 @@ -package openapi3filter - -import ( - "context" - "net/http" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/getkin/kin-openapi/routers" - legacyrouter "github.com/getkin/kin-openapi/routers/legacy" -) - -// AuthenticationFunc allows for custom security requirement validation. -// A non-nil error fails authentication according to https://spec.openapis.org/oas/v3.1.0#security-requirement-object -// See ValidateSecurityRequirements -type AuthenticationFunc func(context.Context, *AuthenticationInput) error - -// NoopAuthenticationFunc is an AuthenticationFunc -func NoopAuthenticationFunc(context.Context, *AuthenticationInput) error { return nil } - -var _ AuthenticationFunc = NoopAuthenticationFunc - -type ValidationHandler struct { - Handler http.Handler - AuthenticationFunc AuthenticationFunc - File string - ErrorEncoder ErrorEncoder - router routers.Router -} - -func (h *ValidationHandler) Load() error { - loader := openapi3.NewLoader() - doc, err := loader.LoadFromFile(h.File) - if err != nil { - return err - } - if err := doc.Validate(loader.Context); err != nil { - return err - } - if h.router, err = legacyrouter.NewRouter(doc); err != nil { - return err - } - - // set defaults - if h.Handler == nil { - h.Handler = http.DefaultServeMux - } - if h.AuthenticationFunc == nil { - h.AuthenticationFunc = NoopAuthenticationFunc - } - if h.ErrorEncoder == nil { - h.ErrorEncoder = DefaultErrorEncoder - } - - return nil -} - -func (h *ValidationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if handled := h.before(w, r); handled { - return - } - // TODO: validateResponse - h.Handler.ServeHTTP(w, r) -} - -// Middleware implements gorilla/mux MiddlewareFunc -func (h *ValidationHandler) Middleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if handled := h.before(w, r); handled { - return - } - // TODO: validateResponse - next.ServeHTTP(w, r) - }) -} - -func (h *ValidationHandler) before(w http.ResponseWriter, r *http.Request) (handled bool) { - if err := h.validateRequest(r); err != nil { - h.ErrorEncoder(r.Context(), err, w) - return true - } - return false -} - -func (h *ValidationHandler) validateRequest(r *http.Request) error { - // Find route - route, pathParams, err := h.router.FindRoute(r) - if err != nil { - return err - } - - options := &Options{ - AuthenticationFunc: h.AuthenticationFunc, - } - - // Validate request - requestValidationInput := &RequestValidationInput{ - Request: r, - PathParams: pathParams, - Route: route, - Options: options, - } - if err = ValidateRequest(r.Context(), requestValidationInput); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_kit.go b/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_kit.go deleted file mode 100644 index 9e11e4fc8..000000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3filter/validation_kit.go +++ /dev/null @@ -1,85 +0,0 @@ -package openapi3filter - -import ( - "context" - "encoding/json" - "net/http" -) - -/////////////////////////////////////////////////////////////////////////////////// -// We didn't want to tie kin-openapi too tightly with go-kit. -// This file contains the ErrorEncoder and DefaultErrorEncoder function -// borrowed from this project. -// -// The MIT License (MIT) -// -// Copyright (c) 2015 Peter Bourgon -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -/////////////////////////////////////////////////////////////////////////////////// - -// ErrorEncoder is responsible for encoding an error to the ResponseWriter. -// Users are encouraged to use custom ErrorEncoders to encode HTTP errors to -// their clients, and will likely want to pass and check for their own error -// types. See the example shipping/handling service. -type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter) - -// StatusCoder is checked by DefaultErrorEncoder. If an error value implements -// StatusCoder, the StatusCode will be used when encoding the error. By default, -// StatusInternalServerError (500) is used. -type StatusCoder interface { - StatusCode() int -} - -// Headerer is checked by DefaultErrorEncoder. If an error value implements -// Headerer, the provided headers will be applied to the response writer, after -// the Content-Type is set. -type Headerer interface { - Headers() http.Header -} - -// DefaultErrorEncoder writes the error to the ResponseWriter, by default a -// content type of text/plain, a body of the plain text of the error, and a -// status code of 500. If the error implements Headerer, the provided headers -// will be applied to the response. If the error implements json.Marshaler, and -// the marshaling succeeds, a content type of application/json and the JSON -// encoded form of the error will be used. If the error implements StatusCoder, -// the provided StatusCode will be used instead of 500. -func DefaultErrorEncoder(_ context.Context, err error, w http.ResponseWriter) { - contentType, body := "text/plain; charset=utf-8", []byte(err.Error()) - if marshaler, ok := err.(json.Marshaler); ok { - if jsonBody, marshalErr := marshaler.MarshalJSON(); marshalErr == nil { - contentType, body = "application/json; charset=utf-8", jsonBody - } - } - w.Header().Set("Content-Type", contentType) - if headerer, ok := err.(Headerer); ok { - for k, values := range headerer.Headers() { - for _, v := range values { - w.Header().Add(k, v) - } - } - } - code := http.StatusInternalServerError - if sc, ok := err.(StatusCoder); ok { - code = sc.StatusCode() - } - w.WriteHeader(code) - w.Write(body) -} diff --git a/vendor/github.com/getkin/kin-openapi/routers/legacy/pathpattern/node.go b/vendor/github.com/getkin/kin-openapi/routers/legacy/pathpattern/node.go deleted file mode 100644 index 75932a26d..000000000 --- a/vendor/github.com/getkin/kin-openapi/routers/legacy/pathpattern/node.go +++ /dev/null @@ -1,328 +0,0 @@ -// Package pathpattern implements path matching. -// -// Examples of supported patterns: -// - "/" -// - "/abc"" -// - "/abc/{variable}" (matches until next '/' or end-of-string) -// - "/abc/{variable*}" (matches everything, including "/abc" if "/abc" has root) -// - "/abc/{ variable | prefix_(.*}_suffix }" (matches regular expressions) -package pathpattern - -import ( - "bytes" - "fmt" - "regexp" - "sort" - "strings" -) - -var DefaultOptions = &Options{ - SupportWildcard: true, -} - -type Options struct { - SupportWildcard bool - SupportRegExp bool -} - -// PathFromHost converts a host pattern to a path pattern. -// -// Examples: -// - PathFromHost("some-subdomain.domain.com", false) -> "com/./domain/./some-subdomain" -// - PathFromHost("some-subdomain.domain.com", true) -> "com/./domain/./subdomain/-/some" -func PathFromHost(host string, specialDashes bool) string { - buf := make([]byte, 0, len(host)) - end := len(host) - - // Go from end to start - for start := end - 1; start >= 0; start-- { - switch host[start] { - case '.': - buf = append(buf, host[start+1:end]...) - buf = append(buf, '/', '.', '/') - end = start - case '-': - if specialDashes { - buf = append(buf, host[start+1:end]...) - buf = append(buf, '/', '-', '/') - end = start - } - } - } - buf = append(buf, host[:end]...) - return string(buf) -} - -type Node struct { - VariableNames []string - Value any - Suffixes SuffixList -} - -func (currentNode *Node) String() string { - buf := bytes.NewBuffer(make([]byte, 0, 255)) - currentNode.toBuffer(buf, "") - return buf.String() -} - -func (currentNode *Node) toBuffer(buf *bytes.Buffer, linePrefix string) { - if value := currentNode.Value; value != nil { - buf.WriteString(linePrefix) - buf.WriteString("VALUE: ") - fmt.Fprint(buf, value) - buf.WriteString("\n") - } - suffixes := currentNode.Suffixes - if len(suffixes) > 0 { - newLinePrefix := linePrefix + " " - for _, suffix := range suffixes { - buf.WriteString(linePrefix) - buf.WriteString("PATTERN: ") - buf.WriteString(suffix.String()) - buf.WriteString("\n") - suffix.Node.toBuffer(buf, newLinePrefix) - } - } -} - -type SuffixKind int - -// Note that order is important! -const ( - // SuffixKindConstant matches a constant string - SuffixKindConstant = SuffixKind(iota) - - // SuffixKindRegExp matches a regular expression - SuffixKindRegExp - - // SuffixKindVariable matches everything until '/' - SuffixKindVariable - - // SuffixKindEverything matches everything (until end-of-string) - SuffixKindEverything -) - -// Suffix describes condition that -type Suffix struct { - Kind SuffixKind - Pattern string - - // compiled regular expression - regExp *regexp.Regexp - - // Next node - Node *Node -} - -func EqualSuffix(a, b Suffix) bool { - return a.Kind == b.Kind && a.Pattern == b.Pattern -} - -func (suffix Suffix) String() string { - switch suffix.Kind { - case SuffixKindConstant: - return suffix.Pattern - case SuffixKindVariable: - return "{_}" - case SuffixKindEverything: - return "{_*}" - default: - return "{_|" + suffix.Pattern + "}" - } -} - -type SuffixList []Suffix - -func (list SuffixList) Less(i, j int) bool { - a, b := list[i], list[j] - ak, bk := a.Kind, b.Kind - if ak < bk { - return true - } else if bk < ak { - return false - } - return a.Pattern > b.Pattern -} - -func (list SuffixList) Len() int { - return len(list) -} - -func (list SuffixList) Swap(i, j int) { - a, b := list[i], list[j] - list[i], list[j] = b, a -} - -func (currentNode *Node) MustAdd(path string, value any, options *Options) { - node, err := currentNode.CreateNode(path, options) - if err != nil { - panic(err) - } - node.Value = value -} - -func (currentNode *Node) Add(path string, value any, options *Options) error { - node, err := currentNode.CreateNode(path, options) - if err != nil { - return err - } - node.Value = value - return nil -} - -func (currentNode *Node) CreateNode(path string, options *Options) (*Node, error) { - if options == nil { - options = DefaultOptions - } - for strings.HasSuffix(path, "/") { - path = path[:len(path)-1] - } - remaining := path - var variableNames []string -loop: - for { - //remaining = strings.TrimPrefix(remaining, "/") - if len(remaining) == 0 { - // This node is the right one - // Check whether another route already leads to this node - currentNode.VariableNames = variableNames - return currentNode, nil - } - - suffix := Suffix{} - var i int - if strings.HasPrefix(remaining, "/") { - remaining = remaining[1:] - suffix.Kind = SuffixKindConstant - suffix.Pattern = "/" - } else { - i = strings.IndexAny(remaining, "/{") - if i < 0 { - i = len(remaining) - } - if i > 0 { - // Constant string pattern - suffix.Kind = SuffixKindConstant - suffix.Pattern = remaining[:i] - remaining = remaining[i:] - } else if remaining[0] == '{' { - // This is probably a variable - suffix.Kind = SuffixKindVariable - - // Find variable name - i := strings.IndexByte(remaining, '}') - if i < 0 { - return nil, fmt.Errorf("missing '}' in: %s", path) - } - variableName := strings.TrimSpace(remaining[1:i]) - remaining = remaining[i+1:] - - if options.SupportRegExp { - // See if it has regular expression - i = strings.IndexByte(variableName, '|') - if i >= 0 { - suffix.Kind = SuffixKindRegExp - suffix.Pattern = strings.TrimSpace(variableName[i+1:]) - variableName = strings.TrimSpace(variableName[:i]) - } - } - if suffix.Kind == SuffixKindVariable && options.SupportWildcard { - if strings.HasSuffix(variableName, "*") { - suffix.Kind = SuffixKindEverything - } - } - variableNames = append(variableNames, variableName) - } - } - - // Find existing matcher - for _, existing := range currentNode.Suffixes { - if EqualSuffix(existing, suffix) { - currentNode = existing.Node - continue loop - } - } - - // Compile regular expression - if suffix.Kind == SuffixKindRegExp { - regExp, err := regexp.Compile(suffix.Pattern) - if err != nil { - return nil, fmt.Errorf("invalid regular expression in: %s", path) - } - suffix.regExp = regExp - } - - // Create new node - newNode := &Node{} - suffix.Node = newNode - currentNode.Suffixes = append(currentNode.Suffixes, suffix) - sort.Sort(currentNode.Suffixes) - currentNode = newNode - continue loop - } -} - -func (currentNode *Node) Match(path string) (*Node, []string) { - for strings.HasSuffix(path, "/") { - path = path[:len(path)-1] - } - variableValues := make([]string, 0, 8) - return currentNode.matchRemaining(path, variableValues) -} - -func (currentNode *Node) matchRemaining(remaining string, paramValues []string) (*Node, []string) { - // Check if this node matches - if len(remaining) == 0 && currentNode.Value != nil { - return currentNode, paramValues - } - - // See if any suffix matches - for _, suffix := range currentNode.Suffixes { - var resultNode *Node - var resultValues []string - switch suffix.Kind { - case SuffixKindConstant: - pattern := suffix.Pattern - if strings.HasPrefix(remaining, pattern) { - newRemaining := remaining[len(pattern):] - resultNode, resultValues = suffix.Node.matchRemaining(newRemaining, paramValues) - } else if len(remaining) == 0 && pattern == "/" { - resultNode, resultValues = suffix.Node.matchRemaining(remaining, paramValues) - } - case SuffixKindVariable: - i := strings.IndexByte(remaining, '/') - if i < 0 { - i = len(remaining) - } - newParamValues := append(paramValues, remaining[:i]) - newRemaining := remaining[i:] - resultNode, resultValues = suffix.Node.matchRemaining(newRemaining, newParamValues) - case SuffixKindEverything: - newParamValues := append(paramValues, remaining) - resultNode, resultValues = suffix.Node, newParamValues - case SuffixKindRegExp: - i := strings.IndexByte(remaining, '/') - if i < 0 { - i = len(remaining) - } - paramValue := remaining[:i] - regExp := suffix.regExp - if regExp.MatchString(paramValue) { - matches := regExp.FindStringSubmatch(paramValue) - if len(matches) > 1 { - paramValue = matches[1] - } - newParamValues := append(paramValues, paramValue) - newRemaining := remaining[i:] - resultNode, resultValues = suffix.Node.matchRemaining(newRemaining, newParamValues) - } - } - if resultNode != nil && resultNode.Value != nil { - // This suffix matched - return resultNode, resultValues - } - } - - // No suffix matched - return nil, nil -} diff --git a/vendor/github.com/getkin/kin-openapi/routers/legacy/router.go b/vendor/github.com/getkin/kin-openapi/routers/legacy/router.go deleted file mode 100644 index 306449d3c..000000000 --- a/vendor/github.com/getkin/kin-openapi/routers/legacy/router.go +++ /dev/null @@ -1,164 +0,0 @@ -// Package legacy implements a router. -// -// It differs from the gorilla/mux router: -// * it provides granular errors: "path not found", "method not allowed", "variable missing from path" -// * it does not handle matching routes with extensions (e.g. /books/{id}.json) -// * it handles path patterns with a different syntax (e.g. /params/{x}/{y}/{z.*}) -package legacy - -import ( - "context" - "errors" - "fmt" - "net/http" - "strings" - - "github.com/getkin/kin-openapi/openapi3" - "github.com/getkin/kin-openapi/routers" - "github.com/getkin/kin-openapi/routers/legacy/pathpattern" -) - -// Routers maps a HTTP request to a Router. -type Routers []*Router - -// FindRoute extracts the route and parameters of an http.Request -func (rs Routers) FindRoute(req *http.Request) (routers.Router, *routers.Route, map[string]string, error) { - for _, router := range rs { - // Skip routers that have DO NOT have servers - if len(router.doc.Servers) == 0 { - continue - } - route, pathParams, err := router.FindRoute(req) - if err == nil { - return router, route, pathParams, nil - } - } - for _, router := range rs { - // Skip routers that DO have servers - if len(router.doc.Servers) > 0 { - continue - } - route, pathParams, err := router.FindRoute(req) - if err == nil { - return router, route, pathParams, nil - } - } - return nil, nil, nil, &routers.RouteError{ - Reason: "none of the routers match", - } -} - -// Router maps a HTTP request to an OpenAPI operation. -type Router struct { - doc *openapi3.T - pathNode *pathpattern.Node -} - -// NewRouter creates a new router. -// -// If the given OpenAPIv3 document has servers, router will use them. -// All operations of the document will be added to the router. -func NewRouter(doc *openapi3.T, opts ...openapi3.ValidationOption) (routers.Router, error) { - if err := doc.Validate(context.Background(), opts...); err != nil { - return nil, fmt.Errorf("validating OpenAPI failed: %w", err) - } - router := &Router{doc: doc} - root := router.node() - for path, pathItem := range doc.Paths.Map() { - for method, operation := range pathItem.Operations() { - method = strings.ToUpper(method) - if err := root.Add(method+" "+path, &routers.Route{ - Spec: doc, - Path: path, - PathItem: pathItem, - Method: method, - Operation: operation, - }, nil); err != nil { - return nil, err - } - } - } - return router, nil -} - -// AddRoute adds a route in the router. -func (router *Router) AddRoute(route *routers.Route) error { - method := route.Method - if method == "" { - return errors.New("route is missing method") - } - method = strings.ToUpper(method) - path := route.Path - if path == "" { - return errors.New("route is missing path") - } - return router.node().Add(method+" "+path, router, nil) -} - -func (router *Router) node() *pathpattern.Node { - root := router.pathNode - if root == nil { - root = &pathpattern.Node{} - router.pathNode = root - } - return root -} - -// FindRoute extracts the route and parameters of an http.Request -func (router *Router) FindRoute(req *http.Request) (*routers.Route, map[string]string, error) { - method, url := req.Method, req.URL - doc := router.doc - - // Get server - servers := doc.Servers - var server *openapi3.Server - var remainingPath string - var pathParams map[string]string - if len(servers) == 0 { - remainingPath = url.Path - } else { - var paramValues []string - server, paramValues, remainingPath = servers.MatchURL(url) - if server == nil { - return nil, nil, &routers.RouteError{ - Reason: routers.ErrPathNotFound.Error(), - } - } - pathParams = make(map[string]string) - paramNames, err := server.ParameterNames() - if err != nil { - return nil, nil, err - } - for i, value := range paramValues { - name := paramNames[i] - pathParams[name] = value - } - } - - // Get PathItem - root := router.node() - var route *routers.Route - node, paramValues := root.Match(method + " " + remainingPath) - if node != nil { - route, _ = node.Value.(*routers.Route) - } - if route == nil { - pathItem := doc.Paths.Value(remainingPath) - if pathItem == nil { - return nil, nil, &routers.RouteError{Reason: routers.ErrPathNotFound.Error()} - } - if pathItem.GetOperation(method) == nil { - return nil, nil, &routers.RouteError{Reason: routers.ErrMethodNotAllowed.Error()} - } - } - - if pathParams == nil { - pathParams = make(map[string]string, len(paramValues)) - } - paramKeys := node.VariableNames - for i, value := range paramValues { - key := strings.TrimSuffix(paramKeys[i], "*") - pathParams[key] = value - } - return route, pathParams, nil -} diff --git a/vendor/github.com/getkin/kin-openapi/routers/types.go b/vendor/github.com/getkin/kin-openapi/routers/types.go deleted file mode 100644 index 93746cfe9..000000000 --- a/vendor/github.com/getkin/kin-openapi/routers/types.go +++ /dev/null @@ -1,42 +0,0 @@ -package routers - -import ( - "net/http" - - "github.com/getkin/kin-openapi/openapi3" -) - -// Router helps link http.Request.s and an OpenAPIv3 spec -type Router interface { - // FindRoute matches an HTTP request with the operation it resolves to. - // Hosts are matched from the OpenAPIv3 servers key. - // - // If you experience ErrPathNotFound and have localhost hosts specified as your servers, - // turning these server URLs as relative (leaving only the path) should resolve this. - // - // See openapi3filter for example uses with request and response validation. - FindRoute(req *http.Request) (route *Route, pathParams map[string]string, err error) -} - -// Route describes the operation an http.Request can match -type Route struct { - Spec *openapi3.T - Server *openapi3.Server - Path string - PathItem *openapi3.PathItem - Method string - Operation *openapi3.Operation -} - -// ErrPathNotFound is returned when no route match is found -var ErrPathNotFound error = &RouteError{"no matching operation was found"} - -// ErrMethodNotAllowed is returned when no method of the matched route matches -var ErrMethodNotAllowed error = &RouteError{"method not allowed"} - -// RouteError describes Router errors -type RouteError struct { - Reason string -} - -func (e *RouteError) Error() string { return e.Reason } diff --git a/vendor/github.com/getsentry/sentry-go/.codecov.yml b/vendor/github.com/getsentry/sentry-go/.codecov.yml deleted file mode 100644 index df0b26811..000000000 --- a/vendor/github.com/getsentry/sentry-go/.codecov.yml +++ /dev/null @@ -1,13 +0,0 @@ -codecov: - # across - notify: - # Do not notify until at least this number of reports have been uploaded - # from the CI pipeline. We normally have more than that number, but 6 - # should be enough to get a first notification. - after_n_builds: 6 -coverage: - status: - project: - default: - # Do not fail the commit status if the coverage was reduced up to this value - threshold: 0.5% diff --git a/vendor/github.com/getsentry/sentry-go/.craft.yml b/vendor/github.com/getsentry/sentry-go/.craft.yml deleted file mode 100644 index 5786bba22..000000000 --- a/vendor/github.com/getsentry/sentry-go/.craft.yml +++ /dev/null @@ -1,40 +0,0 @@ -minVersion: 0.35.0 -changelogPolicy: simple -artifactProvider: - name: none -targets: - - name: github - tagPrefix: v - - name: github - tagPrefix: otel/v - tagOnly: true - - name: github - tagPrefix: echo/v - tagOnly: true - - name: github - tagPrefix: fasthttp/v - tagOnly: true - - name: github - tagPrefix: fiber/v - tagOnly: true - - name: github - tagPrefix: gin/v - tagOnly: true - - name: github - tagPrefix: iris/v - tagOnly: true - - name: github - tagPrefix: negroni/v - tagOnly: true - - name: github - tagPrefix: logrus/v - tagOnly: true - - name: github - tagPrefix: slog/v - tagOnly: true - - name: github - tagPrefix: zerolog/v - tagOnly: true - - name: registry - sdks: - github:getsentry/sentry-go: diff --git a/vendor/github.com/getsentry/sentry-go/.gitattributes b/vendor/github.com/getsentry/sentry-go/.gitattributes deleted file mode 100644 index bccfeeab0..000000000 --- a/vendor/github.com/getsentry/sentry-go/.gitattributes +++ /dev/null @@ -1,5 +0,0 @@ -# Tell Git to use LF for line endings on all platforms. -# Required to have correct test data on Windows. -# https://github.com/mvdan/github-actions-golang#caveats -# https://github.com/actions/checkout/issues/135#issuecomment-613361104 -* text eol=lf diff --git a/vendor/github.com/getsentry/sentry-go/.gitignore b/vendor/github.com/getsentry/sentry-go/.gitignore deleted file mode 100644 index b1249ba55..000000000 --- a/vendor/github.com/getsentry/sentry-go/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# Code coverage artifacts -coverage.txt -coverage.out -coverage.html -.coverage/ - -# Just my personal way of tracking stuff — Kamil -FIXME.md -TODO.md -!NOTES.md - -# IDE system files -.idea -.vscode diff --git a/vendor/github.com/getsentry/sentry-go/.golangci.yml b/vendor/github.com/getsentry/sentry-go/.golangci.yml deleted file mode 100644 index 285e5870e..000000000 --- a/vendor/github.com/getsentry/sentry-go/.golangci.yml +++ /dev/null @@ -1,46 +0,0 @@ -linters: - disable-all: true - enable: - - bodyclose - - dogsled - - dupl - - errcheck - - exportloopref - - gochecknoinits - - goconst - - gocritic - - gocyclo - - godot - - gofmt - - goimports - - gosec - - gosimple - - govet - - ineffassign - - misspell - - nakedret - - prealloc - - revive - - staticcheck - - typecheck - - unconvert - - unparam - - unused - - whitespace -issues: - exclude-rules: - - path: _test\.go - linters: - - goconst - - prealloc - - path: _test\.go - text: "G306:" - linters: - - gosec - - path: errors_test\.go - linters: - - unused - - path: http/example_test\.go - linters: - - errcheck - - bodyclose diff --git a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md deleted file mode 100644 index 94a99acd9..000000000 --- a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md +++ /dev/null @@ -1,960 +0,0 @@ -# Changelog - -## 0.31.1 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.31.1. - -### Bug Fixes - -- Correct wrong module name for `sentry-go/logrus` ([#950](https://github.com/getsentry/sentry-go/pull/950)) - -## 0.31.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.31.0. - -### Breaking Changes - -- Remove support for metrics. Read more about the end of the Metrics beta [here](https://sentry.zendesk.com/hc/en-us/articles/26369339769883-Metrics-Beta-Ended-on-October-7th). ([#914](https://github.com/getsentry/sentry-go/pull/914)) - -- Remove support for profiling. ([#915](https://github.com/getsentry/sentry-go/pull/915)) - -- Remove `Segment` field from the `User` struct. This field is no longer used in the Sentry product. ([#928](https://github.com/getsentry/sentry-go/pull/928)) - -- Every integration is now a separate module, reducing the binary size and number of dependencies. Once you update `sentry-go` to latest version, you'll need to `go get` the integration you want to use. For example, if you want to use the `echo` integration, you'll need to run `go get github.com/getsentry/sentry-go/echo` ([#919](github.com/getsentry/sentry-go/pull/919)). - -### Features - -Add the ability to override `hub` in `context` for integrations that use custom context. ([#931](https://github.com/getsentry/sentry-go/pull/931)) - -- Add `HubProvider` Hook for `sentrylogrus`, enabling dynamic Sentry hub allocation for each log entry or goroutine. ([#936](https://github.com/getsentry/sentry-go/pull/936)) - -This change enhances compatibility with Sentry's recommendation of using separate hubs per goroutine. To ensure a separate Sentry hub for each goroutine, configure the `HubProvider` like this: - -```go -hook, err := sentrylogrus.New(nil, sentry.ClientOptions{}) -if err != nil { - log.Fatalf("Failed to initialize Sentry hook: %v", err) -} - -// Set a custom HubProvider to generate a new hub for each goroutine or log entry -hook.SetHubProvider(func() *sentry.Hub { - client, _ := sentry.NewClient(sentry.ClientOptions{}) - return sentry.NewHub(client, sentry.NewScope()) -}) - -logrus.AddHook(hook) -``` - -### Bug Fixes - -- Add support for closing worker goroutines started by the `HTTPTranport` to prevent goroutine leaks. ([#894](https://github.com/getsentry/sentry-go/pull/894)) - -```go -client, _ := sentry.NewClient() -defer client.Close() -``` - -Worker can be also closed by calling `Close()` method on the `HTTPTransport` instance. `Close` should be called after `Flush` and before terminating the program otherwise some events may be lost. - -```go -transport := sentry.NewHTTPTransport() -defer transport.Close() -``` - -### Misc - -- Bump [gin-gonic/gin](https://github.com/gin-gonic/gin) to v1.9.1. ([#946](https://github.com/getsentry/sentry-go/pull/946)) - -## 0.30.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.30.0. - -### Features - -- Add `sentryzerolog` integration ([#857](https://github.com/getsentry/sentry-go/pull/857)) -- Add `sentryslog` integration ([#865](https://github.com/getsentry/sentry-go/pull/865)) -- Always set Mechanism Type to generic ([#896](https://github.com/getsentry/sentry-go/pull/897)) - -### Bug Fixes - -- Prevent panic in `fasthttp` and `fiber` integration in case a malformed URL has to be parsed ([#912](https://github.com/getsentry/sentry-go/pull/912)) - -### Misc - -Drop support for Go 1.18, 1.19 and 1.20. The currently supported Go versions are the last 3 stable releases: 1.23, 1.22 and 1.21. - -## 0.29.1 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.29.1. - -### Bug Fixes - -- Correlate errors to the current trace ([#886](https://github.com/getsentry/sentry-go/pull/886)) -- Set the trace context when the transaction finishes ([#888](https://github.com/getsentry/sentry-go/pull/888)) - -### Misc - -- Update the `sentrynegroni` integration to use the latest (v3.1.1) version of Negroni ([#885](https://github.com/getsentry/sentry-go/pull/885)) - -## 0.29.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.29.0. - -### Breaking Changes - -- Remove the `sentrymartini` integration ([#861](https://github.com/getsentry/sentry-go/pull/861)) -- The `WrapResponseWriter` has been moved from the `sentryhttp` package to the `internal/httputils` package. If you've imported it previosuly, you'll need to copy the implementation in your project. ([#871](https://github.com/getsentry/sentry-go/pull/871)) - -### Features - -- Add new convenience methods to continue a trace and propagate tracing headers for error-only use cases. ([#862](https://github.com/getsentry/sentry-go/pull/862)) - - If you are not using one of our integrations, you can manually continue an incoming trace by using `sentry.ContinueTrace()` by providing the `sentry-trace` and `baggage` header received from a downstream SDK. - - ```go - hub := sentry.CurrentHub() - sentry.ContinueTrace(hub, r.Header.Get(sentry.SentryTraceHeader), r.Header.Get(sentry.SentryBaggageHeader)), - ``` - - You can use `hub.GetTraceparent()` and `hub.GetBaggage()` to fetch the necessary header values for outgoing HTTP requests. - - ```go - hub := sentry.GetHubFromContext(ctx) - req, _ := http.NewRequest("GET", "http://localhost:3000", nil) - req.Header.Add(sentry.SentryTraceHeader, hub.GetTraceparent()) - req.Header.Add(sentry.SentryBaggageHeader, hub.GetBaggage()) - ``` - -### Bug Fixes - -- Initialize `HTTPTransport.limit` if `nil` ([#844](https://github.com/getsentry/sentry-go/pull/844)) -- Fix `sentry.StartTransaction()` returning a transaction with an outdated context on existing transactions ([#854](https://github.com/getsentry/sentry-go/pull/854)) -- Treat `Proxy-Authorization` as a sensitive header ([#859](https://github.com/getsentry/sentry-go/pull/859)) -- Add support for the `http.Hijacker` interface to the `sentrynegroni` package ([#871](https://github.com/getsentry/sentry-go/pull/871)) -- Go version >= 1.23: Use value from `http.Request.Pattern` for HTTP transaction names when using `sentryhttp` & `sentrynegroni` ([#875](https://github.com/getsentry/sentry-go/pull/875)) -- Go version >= 1.21: Fix closure functions name grouping ([#877](https://github.com/getsentry/sentry-go/pull/877)) - -### Misc - -- Collect `span` origins ([#849](https://github.com/getsentry/sentry-go/pull/849)) - -## 0.28.1 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.28.1. - -### Bug Fixes - -- Implement `http.ResponseWriter` to hook into various parts of the response process ([#837](https://github.com/getsentry/sentry-go/pull/837)) - -## 0.28.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.28.0. - -### Features - -- Add a `Fiber` performance tracing & error reporting integration ([#795](https://github.com/getsentry/sentry-go/pull/795)) -- Add performance tracing to the `Echo` integration ([#722](https://github.com/getsentry/sentry-go/pull/722)) -- Add performance tracing to the `FastHTTP` integration ([#732](https://github.com/getsentry/sentry-go/pull/723)) -- Add performance tracing to the `Iris` integration ([#809](https://github.com/getsentry/sentry-go/pull/809)) -- Add performance tracing to the `Negroni` integration ([#808](https://github.com/getsentry/sentry-go/pull/808)) -- Add `FailureIssueThreshold` & `RecoveryThreshold` to `MonitorConfig` ([#775](https://github.com/getsentry/sentry-go/pull/775)) -- Use `errors.Unwrap()` to create exception groups ([#792](https://github.com/getsentry/sentry-go/pull/792)) -- Add support for matching on strings for `ClientOptions.IgnoreErrors` & `ClientOptions.IgnoreTransactions` ([#819](https://github.com/getsentry/sentry-go/pull/819)) -- Add `http.request.method` attribute for performance span data ([#786](https://github.com/getsentry/sentry-go/pull/786)) -- Accept `interface{}` for span data values ([#784](https://github.com/getsentry/sentry-go/pull/784)) - -### Bug Fixes - -- Fix missing stack trace for parsing error in `logrusentry` ([#689](https://github.com/getsentry/sentry-go/pull/689)) - -## 0.27.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.27.0. - -### Breaking Changes - -- `Exception.ThreadId` is now typed as `uint64`. It was wrongly typed as `string` before. ([#770](https://github.com/getsentry/sentry-go/pull/770)) - -### Misc - -- Export `Event.Attachments` ([#771](https://github.com/getsentry/sentry-go/pull/771)) - -## 0.26.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.26.0. - -### Breaking Changes - -As previously announced, this release removes some methods from the SDK. - -- `sentry.TransactionName()` use `sentry.WithTransactionName()` instead. -- `sentry.OpName()` use `sentry.WithOpName()` instead. -- `sentry.TransctionSource()` use `sentry.WithTransactionSource()` instead. -- `sentry.SpanSampled()` use `sentry.WithSpanSampled()` instead. - -### Features - -- Add `WithDescription` span option ([#751](https://github.com/getsentry/sentry-go/pull/751)) - - ```go - span := sentry.StartSpan(ctx, "http.client", WithDescription("GET /api/users")) - ``` -- Add support for package name parsing in Go 1.20 and higher ([#730](https://github.com/getsentry/sentry-go/pull/730)) - -### Bug Fixes - -- Apply `ClientOptions.SampleRate` only to errors & messages ([#754](https://github.com/getsentry/sentry-go/pull/754)) -- Check if git is available before executing any git commands ([#737](https://github.com/getsentry/sentry-go/pull/737)) - -## 0.25.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.25.0. - -### Breaking Changes - -As previously announced, this release removes two global constants from the SDK. - -- `sentry.Version` was removed. Use `sentry.SDKVersion` instead ([#727](https://github.com/getsentry/sentry-go/pull/727)) -- `sentry.SDKIdentifier` was removed. Use `Client.GetSDKIdentifier()` instead ([#727](https://github.com/getsentry/sentry-go/pull/727)) - -### Features - -- Add `ClientOptions.IgnoreTransactions`, which allows you to ignore specific transactions based on their name ([#717](https://github.com/getsentry/sentry-go/pull/717)) -- Add `ClientOptions.Tags`, which allows you to set global tags that are applied to all events. You can also define tags by setting `SENTRY_TAGS_` environment variables ([#718](https://github.com/getsentry/sentry-go/pull/718)) - -### Bug fixes - -- Fix an issue in the profiler that would cause an infinite loop if the duration of a transaction is longer than 30 seconds ([#724](https://github.com/getsentry/sentry-go/issues/724)) - -### Misc - -- `dsn.RequestHeaders()` is not to be removed, though it is still considered deprecated and should only be used when using a custom transport that sends events to the `/store` endpoint ([#720](https://github.com/getsentry/sentry-go/pull/720)) - -## 0.24.1 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.24.1. - -### Bug fixes - -- Prevent a panic in `sentryotel.flushSpanProcessor()` ([(#711)](https://github.com/getsentry/sentry-go/pull/711)) -- Prevent a panic when setting the SDK identifier ([#715](https://github.com/getsentry/sentry-go/pull/715)) - -## 0.24.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.24.0. - -### Deprecations - -- `sentry.Version` to be removed in 0.25.0. Use `sentry.SDKVersion` instead. -- `sentry.SDKIdentifier` to be removed in 0.25.0. Use `Client.GetSDKIdentifier()` instead. -- `dsn.RequestHeaders()` to be removed after 0.25.0, but no earlier than December 1, 2023. Requests to the `/envelope` endpoint are authenticated using the DSN in the envelope header. - -### Features - -- Run a single instance of the profiler instead of multiple ones for each Go routine ([#655](https://github.com/getsentry/sentry-go/pull/655)) -- Use the route path as the transaction names when using the Gin integration ([#675](https://github.com/getsentry/sentry-go/pull/675)) -- Set the SDK name accordingly when a framework integration is used ([#694](https://github.com/getsentry/sentry-go/pull/694)) -- Read release information (VCS revision) from `debug.ReadBuildInfo` ([#704](https://github.com/getsentry/sentry-go/pull/704)) - -### Bug fixes - -- [otel] Fix incorrect usage of `attributes.Value.AsString` ([#684](https://github.com/getsentry/sentry-go/pull/684)) -- Fix trace function name parsing in profiler on go1.21+ ([#695](https://github.com/getsentry/sentry-go/pull/695)) - -### Misc - -- Test against Go 1.21 ([#695](https://github.com/getsentry/sentry-go/pull/695)) -- Make tests more robust ([#698](https://github.com/getsentry/sentry-go/pull/698), [#699](https://github.com/getsentry/sentry-go/pull/699), [#700](https://github.com/getsentry/sentry-go/pull/700), [#702](https://github.com/getsentry/sentry-go/pull/702)) - -## 0.23.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.23.0. - -### Features - -- Initial support for [Cron Monitoring](https://docs.sentry.io/product/crons/) ([#661](https://github.com/getsentry/sentry-go/pull/661)) - - This is how the basic usage of the feature looks like: - - ```go - // 🟡 Notify Sentry your job is running: - checkinId := sentry.CaptureCheckIn( - &sentry.CheckIn{ - MonitorSlug: "", - Status: sentry.CheckInStatusInProgress, - }, - nil, - ) - - // Execute your scheduled task here... - - // 🟢 Notify Sentry your job has completed successfully: - sentry.CaptureCheckIn( - &sentry.CheckIn{ - ID: *checkinId, - MonitorSlug: "", - Status: sentry.CheckInStatusOK, - }, - nil, - ) - ``` - - A full example of using Crons Monitoring is available [here](https://github.com/getsentry/sentry-go/blob/dde4d360660838f3c2e0ced8205bc8f7a8d312d9/_examples/crons/main.go). - - More documentation on configuring and using Crons [can be found here](https://docs.sentry.io/platforms/go/crons/). - -- Add support for [Event Attachments](https://docs.sentry.io/platforms/go/enriching-events/attachments/) ([#670](https://github.com/getsentry/sentry-go/pull/670)) - - It's now possible to add file/binary payloads to Sentry events: - - ```go - sentry.ConfigureScope(func(scope *sentry.Scope) { - scope.AddAttachment(&Attachment{ - Filename: "report.html", - ContentType: "text/html", - Payload: []byte("

Look, HTML

"), - }) - }) - ``` - - The attachment will then be accessible on the Issue Details page. - -- Add sampling decision to trace envelope header ([#666](https://github.com/getsentry/sentry-go/pull/666)) -- Expose SpanFromContext function ([#672](https://github.com/getsentry/sentry-go/pull/672)) - -### Bug fixes - -- Make `Span.Finish` a no-op when the span is already finished ([#660](https://github.com/getsentry/sentry-go/pull/660)) - -## 0.22.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.22.0. - -This release contains initial [profiling](https://docs.sentry.io/product/profiling/) support, as well as a few bug fixes and improvements. - -### Features - -- Initial (alpha) support for [profiling](https://docs.sentry.io/product/profiling/) ([#626](https://github.com/getsentry/sentry-go/pull/626)) - - Profiling is disabled by default. To enable it, configure both `TracesSampleRate` and `ProfilesSampleRate` when initializing the SDK: - - ```go - err := sentry.Init(sentry.ClientOptions{ - Dsn: "__DSN__", - EnableTracing: true, - TracesSampleRate: 1.0, - // The sampling rate for profiling is relative to TracesSampleRate. In this case, we'll capture profiles for 100% of transactions. - ProfilesSampleRate: 1.0, - }) - ``` - - More documentation on profiling and current limitations [can be found here](https://docs.sentry.io/platforms/go/profiling/). - -- Add transactions/tracing support go the Gin integration ([#644](https://github.com/getsentry/sentry-go/pull/644)) - -### Bug fixes - -- Always set a valid source on transactions ([#637](https://github.com/getsentry/sentry-go/pull/637)) -- Clone scope.Context in more places to avoid panics on concurrent reads and writes ([#638](https://github.com/getsentry/sentry-go/pull/638)) - - Fixes [#570](https://github.com/getsentry/sentry-go/issues/570) -- Fix frames recognized as not being in-app still showing as in-app ([#647](https://github.com/getsentry/sentry-go/pull/647)) - -## 0.21.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.21.0. - -Note: this release includes one **breaking change** and some **deprecations**, which are listed below. - -### Breaking Changes - -**This change does not apply if you use [https://sentry.io](https://sentry.io)** - -- Remove support for the `/store` endpoint ([#631](https://github.com/getsentry/sentry-go/pull/631)) - - This change requires a self-hosted version of Sentry 20.6.0 or higher. If you are using a version of [self-hosted Sentry](https://develop.sentry.dev/self-hosted/) (aka *on-premise*) older than 20.6.0, then you will need to [upgrade](https://develop.sentry.dev/self-hosted/releases/) your instance. - -### Features - -- Rename four span option functions ([#611](https://github.com/getsentry/sentry-go/pull/611), [#624](https://github.com/getsentry/sentry-go/pull/624)) - - `TransctionSource` -> `WithTransactionSource` - - `SpanSampled` -> `WithSpanSampled` - - `OpName` -> `WithOpName` - - `TransactionName` -> `WithTransactionName` - - Old functions `TransctionSource`, `SpanSampled`, `OpName`, and `TransactionName` are still available but are now **deprecated** and will be removed in a future release. -- Make `client.EventFromMessage` and `client.EventFromException` methods public ([#607](https://github.com/getsentry/sentry-go/pull/607)) -- Add `client.SetException` method ([#607](https://github.com/getsentry/sentry-go/pull/607)) - - This allows to set or add errors to an existing `Event`. - -### Bug Fixes - -- Protect from panics while doing concurrent reads/writes to Span data fields ([#609](https://github.com/getsentry/sentry-go/pull/609)) -- [otel] Improve detection of Sentry-related spans ([#632](https://github.com/getsentry/sentry-go/pull/632), [#636](https://github.com/getsentry/sentry-go/pull/636)) - - Fixes cases when HTTP spans containing requests to Sentry were captured by Sentry ([#627](https://github.com/getsentry/sentry-go/issues/627)) - -### Misc - -- Drop testing in (legacy) GOPATH mode ([#618](https://github.com/getsentry/sentry-go/pull/618)) -- Remove outdated documentation from https://pkg.go.dev/github.com/getsentry/sentry-go ([#623](https://github.com/getsentry/sentry-go/pull/623)) - -## 0.20.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.20.0. - -Note: this release has some **breaking changes**, which are listed below. - -### Breaking Changes - -- Remove the following methods: `Scope.SetTransaction()`, `Scope.Transaction()` ([#605](https://github.com/getsentry/sentry-go/pull/605)) - - Span.Name should be used instead to access the transaction's name. - - For example, the following [`TracesSampler`](https://docs.sentry.io/platforms/go/configuration/sampling/#setting-a-sampling-function) function should be now written as follows: - - **Before:** - ```go - TracesSampler: func(ctx sentry.SamplingContext) float64 { - hub := sentry.GetHubFromContext(ctx.Span.Context()) - if hub.Scope().Transaction() == "GET /health" { - return 0 - } - return 1 - }, - ``` - - **After:** - ```go - TracesSampler: func(ctx sentry.SamplingContext) float64 { - if ctx.Span.Name == "GET /health" { - return 0 - } - return 1 - }, - ``` - -### Features - -- Add `Span.SetContext()` method ([#599](https://github.com/getsentry/sentry-go/pull/599/)) - - It is recommended to use it instead of `hub.Scope().SetContext` when setting or updating context on transactions. -- Add `DebugMeta` interface to `Event` and extend `Frame` structure with more fields ([#606](https://github.com/getsentry/sentry-go/pull/606)) - - More about DebugMeta interface [here](https://develop.sentry.dev/sdk/event-payloads/debugmeta/). - -### Bug Fixes - -- [otel] Fix missing OpenTelemetry context on some events ([#599](https://github.com/getsentry/sentry-go/pull/599), [#605](https://github.com/getsentry/sentry-go/pull/605)) - - Fixes ([#596](https://github.com/getsentry/sentry-go/issues/596)). -- [otel] Better handling for HTTP span attributes ([#610](https://github.com/getsentry/sentry-go/pull/610)) - -### Misc - -- Bump minimum versions: `github.com/kataras/iris/v12` to 12.2.0, `github.com/labstack/echo/v4` to v4.10.0 ([#595](https://github.com/getsentry/sentry-go/pull/595)) - - Resolves [GO-2022-1144 / CVE-2022-41717](https://deps.dev/advisory/osv/GO-2022-1144), [GO-2023-1495 / CVE-2022-41721](https://deps.dev/advisory/osv/GO-2023-1495), [GO-2022-1059 / CVE-2022-32149](https://deps.dev/advisory/osv/GO-2022-1059). -- Bump `google.golang.org/protobuf` minimum required version to 1.29.1 ([#604](https://github.com/getsentry/sentry-go/pull/604)) - - This fixes a potential denial of service issue ([CVE-2023-24535](https://github.com/advisories/GHSA-hw7c-3rfg-p46j)). -- Exclude the `otel` module when building in GOPATH mode ([#615](https://github.com/getsentry/sentry-go/pull/615)) - -## 0.19.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.19.0. - -### Features - -- Add support for exception mechanism metadata ([#564](https://github.com/getsentry/sentry-go/pull/564/)) - - More about exception mechanisms [here](https://develop.sentry.dev/sdk/event-payloads/exception/#exception-mechanism). - -### Bug Fixes -- [otel] Use the correct "trace" context when sending a Sentry error ([#580](https://github.com/getsentry/sentry-go/pull/580/)) - - -### Misc -- Drop support for Go 1.17, add support for Go 1.20 ([#563](https://github.com/getsentry/sentry-go/pull/563/)) - - According to our policy, we're officially supporting the last three minor releases of Go. -- Switch repository license to MIT ([#583](https://github.com/getsentry/sentry-go/pull/583/)) - - More about Sentry licensing [here](https://open.sentry.io/licensing/). -- Bump `golang.org/x/text` minimum required version to 0.3.8 ([#586](https://github.com/getsentry/sentry-go/pull/586)) - - This fixes [CVE-2022-32149](https://github.com/advisories/GHSA-69ch-w2m2-3vjp) vulnerability. - -## 0.18.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.18.0. -This release contains initial support for [OpenTelemetry](https://opentelemetry.io/) and various other bug fixes and improvements. - -**Note**: This is the last release supporting Go 1.17. - -### Features - -- Initial support for [OpenTelemetry](https://opentelemetry.io/). - You can now send all your OpenTelemetry spans to Sentry. - - Install the `otel` module - - ```bash - go get github.com/getsentry/sentry-go \ - github.com/getsentry/sentry-go/otel - ``` - - Configure the Sentry and OpenTelemetry SDKs - - ```go - import ( - "go.opentelemetry.io/otel" - sdktrace "go.opentelemetry.io/otel/sdk/trace" - "github.com/getsentry/sentry-go" - "github.com/getsentry/sentry-go/otel" - // ... - ) - - // Initlaize the Sentry SDK - sentry.Init(sentry.ClientOptions{ - Dsn: "__DSN__", - EnableTracing: true, - TracesSampleRate: 1.0, - }) - - // Set up the Sentry span processor - tp := sdktrace.NewTracerProvider( - sdktrace.WithSpanProcessor(sentryotel.NewSentrySpanProcessor()), - // ... - ) - otel.SetTracerProvider(tp) - - // Set up the Sentry propagator - otel.SetTextMapPropagator(sentryotel.NewSentryPropagator()) - ``` - - You can read more about using OpenTelemetry with Sentry in our [docs](https://docs.sentry.io/platforms/go/performance/instrumentation/opentelemetry/). - -### Bug Fixes - -- Do not freeze the Dynamic Sampling Context when no Sentry values are present in the baggage header ([#532](https://github.com/getsentry/sentry-go/pull/532)) -- Create a frozen Dynamic Sampling Context when calling `span.ToBaggage()` ([#566](https://github.com/getsentry/sentry-go/pull/566)) -- Fix baggage parsing and encoding in vendored otel package ([#568](https://github.com/getsentry/sentry-go/pull/568)) - -### Misc - -- Add `Span.SetDynamicSamplingContext()` ([#539](https://github.com/getsentry/sentry-go/pull/539/)) -- Add various getters for `Dsn` ([#540](https://github.com/getsentry/sentry-go/pull/540)) -- Add `SpanOption::SpanSampled` ([#546](https://github.com/getsentry/sentry-go/pull/546)) -- Add `Span.SetData()` ([#542](https://github.com/getsentry/sentry-go/pull/542)) -- Add `Span.IsTransaction()` ([#543](https://github.com/getsentry/sentry-go/pull/543)) -- Add `Span.GetTransaction()` method ([#558](https://github.com/getsentry/sentry-go/pull/558)) - -## 0.17.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.17.0. -This release contains a new `BeforeSendTransaction` hook option and corrects two regressions introduced in `0.16.0`. - -### Features - -- Add `BeforeSendTransaction` hook to `ClientOptions` ([#517](https://github.com/getsentry/sentry-go/pull/517)) - - Here's [an example](https://github.com/getsentry/sentry-go/blob/master/_examples/http/main.go#L56-L66) of how BeforeSendTransaction can be used to modify or drop transaction events. - -### Bug Fixes - -- Do not crash in Span.Finish() when the Client is empty [#520](https://github.com/getsentry/sentry-go/pull/520) - - Fixes [#518](https://github.com/getsentry/sentry-go/issues/518) -- Attach non-PII/non-sensitive request headers to events when `ClientOptions.SendDefaultPii` is set to `false` ([#524](https://github.com/getsentry/sentry-go/pull/524)) - - Fixes [#523](https://github.com/getsentry/sentry-go/issues/523) - -### Misc - -- Clarify how to handle logrus.Fatalf events ([#501](https://github.com/getsentry/sentry-go/pull/501/)) -- Rename the `examples` directory to `_examples` ([#521](https://github.com/getsentry/sentry-go/pull/521)) - - This removes an indirect dependency to `github.com/golang-jwt/jwt` - -## 0.16.0 - -The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.16.0. -Due to ongoing work towards a stable API for `v1.0.0`, we sadly had to include **two breaking changes** in this release. - -### Breaking Changes - -- Add `EnableTracing`, a boolean option flag to enable performance monitoring (`false` by default). - - If you're using `TracesSampleRate` or `TracesSampler`, this option is **required** to enable performance monitoring. - - ```go - sentry.Init(sentry.ClientOptions{ - EnableTracing: true, - TracesSampleRate: 1.0, - }) - ``` -- Unify TracesSampler [#498](https://github.com/getsentry/sentry-go/pull/498) - - `TracesSampler` was changed to a callback that must return a `float64` between `0.0` and `1.0`. - - For example, you can apply a sample rate of `1.0` (100%) to all `/api` transactions, and a sample rate of `0.5` (50%) to all other transactions. - You can read more about this in our [SDK docs](https://docs.sentry.io/platforms/go/configuration/filtering/#using-sampling-to-filter-transaction-events). - - ```go - sentry.Init(sentry.ClientOptions{ - TracesSampler: sentry.TracesSampler(func(ctx sentry.SamplingContext) float64 { - hub := sentry.GetHubFromContext(ctx.Span.Context()) - name := hub.Scope().Transaction() - - if strings.HasPrefix(name, "GET /api") { - return 1.0 - } - - return 0.5 - }), - } - ``` - -### Features - -- Send errors logged with [Logrus](https://github.com/sirupsen/logrus) to Sentry. - - Have a look at our [logrus examples](https://github.com/getsentry/sentry-go/blob/master/_examples/logrus/main.go) on how to use the integration. -- Add support for Dynamic Sampling [#491](https://github.com/getsentry/sentry-go/pull/491) - - You can read more about Dynamic Sampling in our [product docs](https://docs.sentry.io/product/data-management-settings/dynamic-sampling/). -- Add detailed logging about the reason transactions are being dropped. - - You can enable SDK logging via `sentry.ClientOptions.Debug: true`. - -### Bug Fixes - -- Do not clone the hub when calling `StartTransaction` [#505](https://github.com/getsentry/sentry-go/pull/505) - - Fixes [#502](https://github.com/getsentry/sentry-go/issues/502) - -## 0.15.0 - -- fix: Scope values should not override Event values (#446) -- feat: Make maximum amount of spans configurable (#460) -- feat: Add a method to start a transaction (#482) -- feat: Extend User interface by adding Data, Name and Segment (#483) -- feat: Add ClientOptions.SendDefaultPII (#485) - -## 0.14.0 - -- feat: Add function to continue from trace string (#434) -- feat: Add `max-depth` options (#428) -- *[breaking]* ref: Use a `Context` type mapping to a `map[string]interface{}` for all event contexts (#444) -- *[breaking]* ref: Replace deprecated `ioutil` pkg with `os` & `io` (#454) -- ref: Optimize `stacktrace.go` from size and speed (#467) -- ci: Test against `go1.19` and `go1.18`, drop `go1.16` and `go1.15` support (#432, #477) -- deps: Dependency update to fix CVEs (#462, #464, #477) - -_NOTE:_ This version drops support for Go 1.16 and Go 1.15. The currently supported Go versions are the last 3 stable releases: 1.19, 1.18 and 1.17. - -## v0.13.0 - -- ref: Change DSN ProjectID to be a string (#420) -- fix: When extracting PCs from stack frames, try the `PC` field (#393) -- build: Bump gin-gonic/gin from v1.4.0 to v1.7.7 (#412) -- build: Bump Go version in go.mod (#410) -- ci: Bump golangci-lint version in GH workflow (#419) -- ci: Update GraphQL config with appropriate permissions (#417) -- ci: ci: Add craft release automation (#422) - -## v0.12.0 - -- feat: Automatic Release detection (#363, #369, #386, #400) -- fix: Do not change Hub.lastEventID for transactions (#379) -- fix: Do not clear LastEventID when events are dropped (#382) -- Updates to documentation (#366, #385) - -_NOTE:_ -This version drops support for Go 1.14, however no changes have been made that would make the SDK not work with Go 1.14. The currently supported Go versions are the last 3 stable releases: 1.15, 1.16 and 1.17. -There are two behavior changes related to `LastEventID`, both of which were intended to align the behavior of the Sentry Go SDK with other Sentry SDKs. -The new [automatic release detection feature](https://github.com/getsentry/sentry-go/issues/335) makes it easier to use Sentry and separate events per release without requiring extra work from users. We intend to improve this functionality in a future release by utilizing information that will be available in runtime starting with Go 1.18. The tracking issue is [#401](https://github.com/getsentry/sentry-go/issues/401). - -## v0.11.0 - -- feat(transports): Category-based Rate Limiting ([#354](https://github.com/getsentry/sentry-go/pull/354)) -- feat(transports): Report User-Agent identifying SDK ([#357](https://github.com/getsentry/sentry-go/pull/357)) -- fix(scope): Include event processors in clone ([#349](https://github.com/getsentry/sentry-go/pull/349)) -- Improvements to `go doc` documentation ([#344](https://github.com/getsentry/sentry-go/pull/344), [#350](https://github.com/getsentry/sentry-go/pull/350), [#351](https://github.com/getsentry/sentry-go/pull/351)) -- Miscellaneous changes to our testing infrastructure with GitHub Actions - ([57123a40](https://github.com/getsentry/sentry-go/commit/57123a409be55f61b1d5a6da93c176c55a399ad0), [#128](https://github.com/getsentry/sentry-go/pull/128), [#338](https://github.com/getsentry/sentry-go/pull/338), [#345](https://github.com/getsentry/sentry-go/pull/345), [#346](https://github.com/getsentry/sentry-go/pull/346), [#352](https://github.com/getsentry/sentry-go/pull/352), [#353](https://github.com/getsentry/sentry-go/pull/353), [#355](https://github.com/getsentry/sentry-go/pull/355)) - -_NOTE:_ -This version drops support for Go 1.13. The currently supported Go versions are the last 3 stable releases: 1.14, 1.15 and 1.16. -Users of the tracing functionality (`StartSpan`, etc) should upgrade to this version to benefit from separate rate limits for errors and transactions. -There are no breaking changes and upgrading should be a smooth experience for all users. - -## v0.10.0 - -- feat: Debug connection reuse (#323) -- fix: Send root span data as `Event.Extra` (#329) -- fix: Do not double sample transactions (#328) -- fix: Do not override trace context of transactions (#327) -- fix: Drain and close API response bodies (#322) -- ci: Run tests against Go tip (#319) -- ci: Move away from Travis in favor of GitHub Actions (#314) (#321) - -## v0.9.0 - -- feat: Initial tracing and performance monitoring support (#285) -- doc: Revamp sentryhttp documentation (#304) -- fix: Hub.PopScope never empties the scope stack (#300) -- ref: Report Event.Timestamp in local time (#299) -- ref: Report Breadcrumb.Timestamp in local time (#299) - -_NOTE:_ -This version introduces support for [Sentry's Performance Monitoring](https://docs.sentry.io/platforms/go/performance/). -The new tracing capabilities are beta, and we plan to expand them on future versions. Feedback is welcome, please open new issues on GitHub. -The `sentryhttp` package got better API docs, an [updated usage example](https://github.com/getsentry/sentry-go/tree/master/_examples/http) and support for creating automatic transactions as part of Performance Monitoring. - -## v0.8.0 - -- build: Bump required version of Iris (#296) -- fix: avoid unnecessary allocation in Client.processEvent (#293) -- doc: Remove deprecation of sentryhttp.HandleFunc (#284) -- ref: Update sentryhttp example (#283) -- doc: Improve documentation of sentryhttp package (#282) -- doc: Clarify SampleRate documentation (#279) -- fix: Remove RawStacktrace (#278) -- docs: Add example of custom HTTP transport -- ci: Test against go1.15, drop go1.12 support (#271) - -_NOTE:_ -This version comes with a few updates. Some examples and documentation have been -improved. We've bumped the supported version of the Iris framework to avoid -LGPL-licensed modules in the module dependency graph. -The `Exception.RawStacktrace` and `Thread.RawStacktrace` fields have been -removed to conform to Sentry's ingestion protocol, only `Exception.Stacktrace` -and `Thread.Stacktrace` should appear in user code. - -## v0.7.0 - -- feat: Include original error when event cannot be encoded as JSON (#258) -- feat: Use Hub from request context when available (#217, #259) -- feat: Extract stack frames from golang.org/x/xerrors (#262) -- feat: Make Environment Integration preserve existing context data (#261) -- feat: Recover and RecoverWithContext with arbitrary types (#268) -- feat: Report bad usage of CaptureMessage and CaptureEvent (#269) -- feat: Send debug logging to stderr by default (#266) -- feat: Several improvements to documentation (#223, #245, #250, #265) -- feat: Example of Recover followed by panic (#241, #247) -- feat: Add Transactions and Spans (to support OpenTelemetry Sentry Exporter) (#235, #243, #254) -- fix: Set either Frame.Filename or Frame.AbsPath (#233) -- fix: Clone requestBody to new Scope (#244) -- fix: Synchronize access and mutation of Hub.lastEventID (#264) -- fix: Avoid repeated syscalls in prepareEvent (#256) -- fix: Do not allocate new RNG for every event (#256) -- fix: Remove stale replace directive in go.mod (#255) -- fix(http): Deprecate HandleFunc, remove duplication (#260) - -_NOTE:_ -This version comes packed with several fixes and improvements and no breaking -changes. -Notably, there is a change in how the SDK reports file names in stack traces -that should resolve any ambiguity when looking at stack traces and using the -Suspect Commits feature. -We recommend all users to upgrade. - -## v0.6.1 - -- fix: Use NewEvent to init Event struct (#220) - -_NOTE:_ -A change introduced in v0.6.0 with the intent of avoiding allocations made a -pattern used in official examples break in certain circumstances (attempting -to write to a nil map). -This release reverts the change such that maps in the Event struct are always -allocated. - -## v0.6.0 - -- feat: Read module dependencies from runtime/debug (#199) -- feat: Support chained errors using Unwrap (#206) -- feat: Report chain of errors when available (#185) -- **[breaking]** fix: Accept http.RoundTripper to customize transport (#205) - Before the SDK accepted a concrete value of type `*http.Transport` in - `ClientOptions`, now it accepts any value implementing the `http.RoundTripper` - interface. Note that `*http.Transport` implements `http.RoundTripper`, so most - code bases will continue to work unchanged. - Users of custom transport gain the ability to pass in other implementations of - `http.RoundTripper` and may be able to simplify their code bases. -- fix: Do not panic when scope event processor drops event (#192) -- **[breaking]** fix: Use time.Time for timestamps (#191) - Users of sentry-go typically do not need to manipulate timestamps manually. - For those who do, the field type changed from `int64` to `time.Time`, which - should be more convenient to use. The recommended way to get the current time - is `time.Now().UTC()`. -- fix: Report usage error including stack trace (#189) -- feat: Add Exception.ThreadID field (#183) -- ci: Test against Go 1.14, drop 1.11 (#170) -- feat: Limit reading bytes from request bodies (#168) -- **[breaking]** fix: Rename fasthttp integration package sentryhttp => sentryfasthttp - The current recommendation is to use a named import, in which case existing - code should not require any change: - ```go - package main - - import ( - "fmt" - - "github.com/getsentry/sentry-go" - sentryfasthttp "github.com/getsentry/sentry-go/fasthttp" - "github.com/valyala/fasthttp" - ) - ``` - -_NOTE:_ -This version includes some new features and a few breaking changes, none of -which should pose troubles with upgrading. Most code bases should be able to -upgrade without any changes. - -## v0.5.1 - -- fix: Ignore err.Cause() when it is nil (#160) - -## v0.5.0 - -- fix: Synchronize access to HTTPTransport.disabledUntil (#158) -- docs: Update Flush documentation (#153) -- fix: HTTPTransport.Flush panic and data race (#140) - -_NOTE:_ -This version changes the implementation of the default transport, modifying the -behavior of `sentry.Flush`. The previous behavior was to wait until there were -no buffered events; new concurrent events kept `Flush` from returning. The new -behavior is to wait until the last event prior to the call to `Flush` has been -sent or the timeout; new concurrent events have no effect. The new behavior is -inline with the [Unified API -Guidelines](https://docs.sentry.io/development/sdk-dev/unified-api/). - -We have updated the documentation and examples to clarify that `Flush` is meant -to be called typically only once before program termination, to wait for -in-flight events to be sent to Sentry. Calling `Flush` after every event is not -recommended, as it introduces unnecessary latency to the surrounding function. -Please verify the usage of `sentry.Flush` in your code base. - -## v0.4.0 - -- fix(stacktrace): Correctly report package names (#127) -- fix(stacktrace): Do not rely on AbsPath of files (#123) -- build: Require github.com/ugorji/go@v1.1.7 (#110) -- fix: Correctly store last event id (#99) -- fix: Include request body in event payload (#94) -- build: Reset go.mod version to 1.11 (#109) -- fix: Eliminate data race in modules integration (#105) -- feat: Add support for path prefixes in the DSN (#102) -- feat: Add HTTPClient option (#86) -- feat: Extract correct type and value from top-most error (#85) -- feat: Check for broken pipe errors in Gin integration (#82) -- fix: Client.CaptureMessage accept nil EventModifier (#72) - -## v0.3.1 - -- feat: Send extra information exposed by the Go runtime (#76) -- fix: Handle new lines in module integration (#65) -- fix: Make sure that cache is locked when updating for contextifyFramesIntegration -- ref: Update Iris integration and example to version 12 -- misc: Remove indirect dependencies in order to move them to separate go.mod files - -## v0.3.0 - -- feat: Retry event marshaling without contextual data if the first pass fails -- fix: Include `url.Parse` error in `DsnParseError` -- fix: Make more `Scope` methods safe for concurrency -- fix: Synchronize concurrent access to `Hub.client` -- ref: Remove mutex from `Scope` exported API -- ref: Remove mutex from `Hub` exported API -- ref: Compile regexps for `filterFrames` only once -- ref: Change `SampleRate` type to `float64` -- doc: `Scope.Clear` not safe for concurrent use -- ci: Test sentry-go with `go1.13`, drop `go1.10` - -_NOTE:_ -This version removes some of the internal APIs that landed publicly (namely `Hub/Scope` mutex structs) and may require (but shouldn't) some changes to your code. -It's not done through major version update, as we are still in `0.x` stage. - -## v0.2.1 - -- fix: Run `Contextify` integration on `Threads` as well - -## v0.2.0 - -- feat: Add `SetTransaction()` method on the `Scope` -- feat: `fasthttp` framework support with `sentryfasthttp` package -- fix: Add `RWMutex` locks to internal `Hub` and `Scope` changes - -## v0.1.3 - -- feat: Move frames context reading into `contextifyFramesIntegration` (#28) - -_NOTE:_ -In case of any performance issues due to source contexts IO, you can let us know and turn off the integration in the meantime with: - -```go -sentry.Init(sentry.ClientOptions{ - Integrations: func(integrations []sentry.Integration) []sentry.Integration { - var filteredIntegrations []sentry.Integration - for _, integration := range integrations { - if integration.Name() == "ContextifyFrames" { - continue - } - filteredIntegrations = append(filteredIntegrations, integration) - } - return filteredIntegrations - }, -}) -``` - -## v0.1.2 - -- feat: Better source code location resolution and more useful inapp frames (#26) -- feat: Use `noopTransport` when no `Dsn` provided (#27) -- ref: Allow empty `Dsn` instead of returning an error (#22) -- fix: Use `NewScope` instead of literal struct inside a `scope.Clear` call (#24) -- fix: Add to `WaitGroup` before the request is put inside a buffer (#25) - -## v0.1.1 - -- fix: Check for initialized `Client` in `AddBreadcrumbs` (#20) -- build: Bump version when releasing with Craft (#19) - -## v0.1.0 - -- First stable release! \o/ - -## v0.0.1-beta.5 - -- feat: **[breaking]** Add `NewHTTPTransport` and `NewHTTPSyncTransport` which accepts all transport options -- feat: New `HTTPSyncTransport` that blocks after each call -- feat: New `Echo` integration -- ref: **[breaking]** Remove `BufferSize` option from `ClientOptions` and move it to `HTTPTransport` instead -- ref: Export default `HTTPTransport` -- ref: Export `net/http` integration handler -- ref: Set `Request` instantly in the package handlers, not in `recoverWithSentry` so it can be accessed later on -- ci: Add craft config - -## v0.0.1-beta.4 - -- feat: `IgnoreErrors` client option and corresponding integration -- ref: Reworked `net/http` integration, wrote better example and complete readme -- ref: Reworked `Gin` integration, wrote better example and complete readme -- ref: Reworked `Iris` integration, wrote better example and complete readme -- ref: Reworked `Negroni` integration, wrote better example and complete readme -- ref: Reworked `Martini` integration, wrote better example and complete readme -- ref: Remove `Handle()` from frameworks handlers and return it directly from New - -## v0.0.1-beta.3 - -- feat: `Iris` framework support with `sentryiris` package -- feat: `Gin` framework support with `sentrygin` package -- feat: `Martini` framework support with `sentrymartini` package -- feat: `Negroni` framework support with `sentrynegroni` package -- feat: Add `Hub.Clone()` for easier frameworks integration -- feat: Return `EventID` from `Recovery` methods -- feat: Add `NewScope` and `NewEvent` functions and use them in the whole codebase -- feat: Add `AddEventProcessor` to the `Client` -- fix: Operate on requests body copy instead of the original -- ref: Try to read source files from the root directory, based on the filename as well, to make it work on AWS Lambda -- ref: Remove `gocertifi` dependence and document how to provide your own certificates -- ref: **[breaking]** Remove `Decorate` and `DecorateFunc` methods in favor of `sentryhttp` package -- ref: **[breaking]** Allow for integrations to live on the client, by passing client instance in `SetupOnce` method -- ref: **[breaking]** Remove `GetIntegration` from the `Hub` -- ref: **[breaking]** Remove `GlobalEventProcessors` getter from the public API - -## v0.0.1-beta.2 - -- feat: Add `AttachStacktrace` client option to include stacktrace for messages -- feat: Add `BufferSize` client option to configure transport buffer size -- feat: Add `SetRequest` method on a `Scope` to control `Request` context data -- feat: Add `FromHTTPRequest` for `Request` type for easier extraction -- ref: Extract `Request` information more accurately -- fix: Attach `ServerName`, `Release`, `Dist`, `Environment` options to the event -- fix: Don't log events dropped due to full transport buffer as sent -- fix: Don't panic and create an appropriate event when called `CaptureException` or `Recover` with `nil` value - -## v0.0.1-beta - -- Initial release diff --git a/vendor/github.com/getsentry/sentry-go/CONTRIBUTING.md b/vendor/github.com/getsentry/sentry-go/CONTRIBUTING.md deleted file mode 100644 index 9808f1862..000000000 --- a/vendor/github.com/getsentry/sentry-go/CONTRIBUTING.md +++ /dev/null @@ -1,98 +0,0 @@ -# Contributing to sentry-go - -Hey, thank you if you're reading this, we welcome your contribution! - -## Sending a Pull Request - -Please help us save time when reviewing your PR by following this simple -process: - -1. Is your PR a simple typo fix? Read no further, **click that green "Create - pull request" button**! - -2. For more complex PRs that involve behavior changes or new APIs, please - consider [opening an **issue**][new-issue] describing the problem you're - trying to solve if there's not one already. - - A PR is often one specific solution to a problem and sometimes talking about - the problem unfolds new possible solutions. Remember we will be responsible - for maintaining the changes later. - -3. Fixing a bug and changing a behavior? Please add automated tests to prevent - future regression. - -4. Practice writing good commit messages. We have [commit - guidelines][commit-guide]. - -5. We have [guidelines for PR submitters][pr-guide]. A short summary: - - - Good PR descriptions are very helpful and most of the time they include - **why** something is done and why done in this particular way. Also list - other possible solutions that were considered and discarded. - - Be your own first reviewer. Make sure your code compiles and passes the - existing tests. - -[new-issue]: https://github.com/getsentry/sentry-go/issues/new/choose -[commit-guide]: https://develop.sentry.dev/code-review/#commit-guidelines -[pr-guide]: https://develop.sentry.dev/code-review/#guidelines-for-submitters - -Please also read through our [SDK Development docs](https://develop.sentry.dev/sdk/). -It contains information about SDK features, expected payloads and best practices for -contributing to Sentry SDKs. - -## Community - -The public-facing channels for support and development of Sentry SDKs can be found on [Discord](https://discord.gg/Ww9hbqr). - -## Testing - -```console -$ go test -``` - -### Watch mode - -Use: https://github.com/cespare/reflex - -```console -$ reflex -g '*.go' -d "none" -- sh -c 'printf "\n"; go test' -``` - -### With data race detection - -```console -$ go test -race -``` - -### Coverage - -```console -$ go test -race -coverprofile=coverage.txt -covermode=atomic && go tool cover -html coverage.txt -``` - -## Linting - -Lint with [`golangci-lint`](https://github.com/golangci/golangci-lint): - -```console -$ golangci-lint run -``` - -## Release - -1. Update `CHANGELOG.md` with new version in `vX.X.X` format title and list of changes. - - The command below can be used to get a list of changes since the last tag, with the format used in `CHANGELOG.md`: - - ```console - $ git log --no-merges --format=%s $(git describe --abbrev=0).. | sed 's/^/- /' - ``` - -2. Commit with `misc: vX.X.X changelog` commit message and push to `master`. - -3. Let [`craft`](https://github.com/getsentry/craft) do the rest: - - ```console - $ craft prepare X.X.X - $ craft publish X.X.X - ``` diff --git a/vendor/github.com/getsentry/sentry-go/LICENSE b/vendor/github.com/getsentry/sentry-go/LICENSE deleted file mode 100644 index b1b358e41..000000000 --- a/vendor/github.com/getsentry/sentry-go/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Functional Software, Inc. dba Sentry - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/getsentry/sentry-go/MIGRATION.md b/vendor/github.com/getsentry/sentry-go/MIGRATION.md deleted file mode 100644 index 2c30d6288..000000000 --- a/vendor/github.com/getsentry/sentry-go/MIGRATION.md +++ /dev/null @@ -1,3 +0,0 @@ -# `raven-go` to `sentry-go` Migration Guide - -A [`raven-go` to `sentry-go` migration guide](https://docs.sentry.io/platforms/go/migration/) is available at the official Sentry documentation site. diff --git a/vendor/github.com/getsentry/sentry-go/Makefile b/vendor/github.com/getsentry/sentry-go/Makefile deleted file mode 100644 index 9cc0959fd..000000000 --- a/vendor/github.com/getsentry/sentry-go/Makefile +++ /dev/null @@ -1,82 +0,0 @@ -.DEFAULT_GOAL := help - -MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST))) -MKFILE_DIR := $(dir $(MKFILE_PATH)) -ALL_GO_MOD_DIRS := $(shell find . -type f -name 'go.mod' -exec dirname {} \; | sort) -GO = go -TIMEOUT = 300 - -# Parse Makefile and display the help -help: ## Show help - @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' -.PHONY: help - -build: ## Build everything - for dir in $(ALL_GO_MOD_DIRS); do \ - cd "$${dir}"; \ - echo ">>> Running 'go build' for module: $${dir}"; \ - go build ./...; \ - done; -.PHONY: build - -### Tests (inspired by https://github.com/open-telemetry/opentelemetry-go/blob/main/Makefile) -TEST_TARGETS := test-short test-verbose test-race -test-race: ARGS=-race -test-short: ARGS=-short -test-verbose: ARGS=-v -race -$(TEST_TARGETS): test -test: $(ALL_GO_MOD_DIRS:%=test/%) ## Run tests -test/%: DIR=$* -test/%: - @echo ">>> Running tests for module: $(DIR)" - @# We use '-count=1' to disable test caching. - (cd $(DIR) && $(GO) test -count=1 -timeout $(TIMEOUT)s $(ARGS) ./...) -.PHONY: $(TEST_TARGETS) test - -# Coverage -COVERAGE_MODE = atomic -COVERAGE_PROFILE = coverage.out -COVERAGE_REPORT_DIR = .coverage -COVERAGE_REPORT_DIR_ABS = "$(MKFILE_DIR)/$(COVERAGE_REPORT_DIR)" -$(COVERAGE_REPORT_DIR): - mkdir -p $(COVERAGE_REPORT_DIR) -clean-report-dir: $(COVERAGE_REPORT_DIR) - test $(COVERAGE_REPORT_DIR) && rm -f $(COVERAGE_REPORT_DIR)/* -test-coverage: $(COVERAGE_REPORT_DIR) clean-report-dir ## Test with coverage enabled - set -e ; \ - for dir in $(ALL_GO_MOD_DIRS); do \ - echo ">>> Running tests with coverage for module: $${dir}"; \ - DIR_ABS=$$(python -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' $${dir}) ; \ - REPORT_NAME=$$(basename $${DIR_ABS}); \ - (cd "$${dir}" && \ - $(GO) test -count=1 -timeout $(TIMEOUT)s -coverpkg=./... -covermode=$(COVERAGE_MODE) -coverprofile="$(COVERAGE_PROFILE)" ./... && \ - cp $(COVERAGE_PROFILE) "$(COVERAGE_REPORT_DIR_ABS)/$${REPORT_NAME}_$(COVERAGE_PROFILE)" && \ - $(GO) tool cover -html=$(COVERAGE_PROFILE) -o coverage.html); \ - done; -.PHONY: test-coverage clean-report-dir - -mod-tidy: ## Check go.mod tidiness - set -e ; \ - for dir in $(ALL_GO_MOD_DIRS); do \ - echo ">>> Running 'go mod tidy' for module: $${dir}"; \ - (cd "$${dir}" && go mod tidy -go=1.21 -compat=1.21); \ - done; \ - git diff --exit-code; -.PHONY: mod-tidy - -vet: ## Run "go vet" - set -e ; \ - for dir in $(ALL_GO_MOD_DIRS); do \ - echo ">>> Running 'go vet' for module: $${dir}"; \ - (cd "$${dir}" && go vet ./...); \ - done; -.PHONY: vet - - -lint: ## Lint (using "golangci-lint") - golangci-lint run -.PHONY: lint - -fmt: ## Format all Go files - gofmt -l -w -s . -.PHONY: fmt diff --git a/vendor/github.com/getsentry/sentry-go/README.md b/vendor/github.com/getsentry/sentry-go/README.md deleted file mode 100644 index 59a989d8d..000000000 --- a/vendor/github.com/getsentry/sentry-go/README.md +++ /dev/null @@ -1,106 +0,0 @@ -

- - - - - Sentry - - -

- -# Official Sentry SDK for Go - -[![Build Status](https://github.com/getsentry/sentry-go/actions/workflows/test.yml/badge.svg)](https://github.com/getsentry/sentry-go/actions/workflows/test.yml) -[![Go Report Card](https://goreportcard.com/badge/github.com/getsentry/sentry-go)](https://goreportcard.com/report/github.com/getsentry/sentry-go) -[![Discord](https://img.shields.io/discord/621778831602221064)](https://discord.gg/Ww9hbqr) -[![go.dev](https://img.shields.io/badge/go.dev-pkg-007d9c.svg?style=flat)](https://pkg.go.dev/github.com/getsentry/sentry-go) - -`sentry-go` provides a Sentry client implementation for the Go programming -language. This is the next generation of the Go SDK for [Sentry](https://sentry.io/), -intended to replace the `raven-go` package. - -> Looking for the old `raven-go` SDK documentation? See the Legacy client section [here](https://docs.sentry.io/clients/go/). -> If you want to start using `sentry-go` instead, check out the [migration guide](https://docs.sentry.io/platforms/go/migration/). - -## Requirements - -The only requirement is a Go compiler. - -We verify this package against the 3 most recent releases of Go. Those are the -supported versions. The exact versions are defined in -[`GitHub workflow`](.github/workflows/test.yml). - -In addition, we run tests against the current master branch of the Go toolchain, -though support for this configuration is best-effort. - -## Installation - -`sentry-go` can be installed like any other Go library through `go get`: - -```console -$ go get github.com/getsentry/sentry-go@latest -``` - -Check out the [list of released versions](https://github.com/getsentry/sentry-go/releases). - -## Configuration - -To use `sentry-go`, you’ll need to import the `sentry-go` package and initialize -it with your DSN and other [options](https://pkg.go.dev/github.com/getsentry/sentry-go#ClientOptions). - -If not specified in the SDK initialization, the -[DSN](https://docs.sentry.io/product/sentry-basics/dsn-explainer/), -[Release](https://docs.sentry.io/product/releases/) and -[Environment](https://docs.sentry.io/product/sentry-basics/environments/) -are read from the environment variables `SENTRY_DSN`, `SENTRY_RELEASE` and -`SENTRY_ENVIRONMENT`, respectively. - -More on this in the [Configuration section of the official Sentry Go SDK documentation](https://docs.sentry.io/platforms/go/configuration/). - -## Usage - -The SDK supports reporting errors and tracking application performance. - -To get started, have a look at one of our [examples](_examples/): -- [Basic error instrumentation](_examples/basic/main.go) -- [Error and tracing for HTTP servers](_examples/http/main.go) - -We also provide a [complete API reference](https://pkg.go.dev/github.com/getsentry/sentry-go). - -For more detailed information about how to get the most out of `sentry-go`, -check out the official documentation: - -- [Sentry Go SDK documentation](https://docs.sentry.io/platforms/go/) -- Guides: - - [net/http](https://docs.sentry.io/platforms/go/guides/http/) - - [echo](https://docs.sentry.io/platforms/go/guides/echo/) - - [fasthttp](https://docs.sentry.io/platforms/go/guides/fasthttp/) - - [fiber](https://docs.sentry.io/platforms/go/guides/fiber/) - - [gin](https://docs.sentry.io/platforms/go/guides/gin/) - - [iris](https://docs.sentry.io/platforms/go/guides/iris/) - - [logrus](https://docs.sentry.io/platforms/go/guides/logrus/) - - [negroni](https://docs.sentry.io/platforms/go/guides/negroni/) - - [slog](https://docs.sentry.io/platforms/go/guides/slog/) - - [zerolog](https://docs.sentry.io/platforms/go/guides/zerolog/) - -## Resources - -- [Bug Tracker](https://github.com/getsentry/sentry-go/issues) -- [GitHub Project](https://github.com/getsentry/sentry-go) -- [![go.dev](https://img.shields.io/badge/go.dev-pkg-007d9c.svg?style=flat)](https://pkg.go.dev/github.com/getsentry/sentry-go) -- [![Documentation](https://img.shields.io/badge/documentation-sentry.io-green.svg)](https://docs.sentry.io/platforms/go/) -- [![Discussions](https://img.shields.io/github/discussions/getsentry/sentry-go.svg)](https://github.com/getsentry/sentry-go/discussions) -- [![Discord](https://img.shields.io/discord/621778831602221064)](https://discord.gg/Ww9hbqr) -- [![Stack Overflow](https://img.shields.io/badge/stack%20overflow-sentry-green.svg)](http://stackoverflow.com/questions/tagged/sentry) -- [![Twitter Follow](https://img.shields.io/twitter/follow/getsentry?label=getsentry&style=social)](https://twitter.com/intent/follow?screen_name=getsentry) - -## License - -Licensed under -[The MIT License](https://opensource.org/licenses/mit/), see -[`LICENSE`](LICENSE). - -## Community - -Join Sentry's [`#go` channel on Discord](https://discord.gg/Ww9hbqr) to get -involved and help us improve the SDK! diff --git a/vendor/github.com/getsentry/sentry-go/check_in.go b/vendor/github.com/getsentry/sentry-go/check_in.go deleted file mode 100644 index de6d0adb6..000000000 --- a/vendor/github.com/getsentry/sentry-go/check_in.go +++ /dev/null @@ -1,121 +0,0 @@ -package sentry - -import "time" - -type CheckInStatus string - -const ( - CheckInStatusInProgress CheckInStatus = "in_progress" - CheckInStatusOK CheckInStatus = "ok" - CheckInStatusError CheckInStatus = "error" -) - -type checkInScheduleType string - -const ( - checkInScheduleTypeCrontab checkInScheduleType = "crontab" - checkInScheduleTypeInterval checkInScheduleType = "interval" -) - -type MonitorSchedule interface { - // scheduleType is a private method that must be implemented for monitor schedule - // implementation. It should never be called. This method is made for having - // specific private implementation of MonitorSchedule interface. - scheduleType() checkInScheduleType -} - -type crontabSchedule struct { - Type string `json:"type"` - Value string `json:"value"` -} - -func (c crontabSchedule) scheduleType() checkInScheduleType { - return checkInScheduleTypeCrontab -} - -// CrontabSchedule defines the MonitorSchedule with a cron format. -// Example: "8 * * * *". -func CrontabSchedule(scheduleString string) MonitorSchedule { - return crontabSchedule{ - Type: string(checkInScheduleTypeCrontab), - Value: scheduleString, - } -} - -type intervalSchedule struct { - Type string `json:"type"` - Value int64 `json:"value"` - Unit string `json:"unit"` -} - -func (i intervalSchedule) scheduleType() checkInScheduleType { - return checkInScheduleTypeInterval -} - -type MonitorScheduleUnit string - -const ( - MonitorScheduleUnitMinute MonitorScheduleUnit = "minute" - MonitorScheduleUnitHour MonitorScheduleUnit = "hour" - MonitorScheduleUnitDay MonitorScheduleUnit = "day" - MonitorScheduleUnitWeek MonitorScheduleUnit = "week" - MonitorScheduleUnitMonth MonitorScheduleUnit = "month" - MonitorScheduleUnitYear MonitorScheduleUnit = "year" -) - -// IntervalSchedule defines the MonitorSchedule with an interval format. -// -// Example: -// -// IntervalSchedule(1, sentry.MonitorScheduleUnitDay) -func IntervalSchedule(value int64, unit MonitorScheduleUnit) MonitorSchedule { - return intervalSchedule{ - Type: string(checkInScheduleTypeInterval), - Value: value, - Unit: string(unit), - } -} - -type MonitorConfig struct { //nolint: maligned // prefer readability over optimal memory layout - Schedule MonitorSchedule `json:"schedule,omitempty"` - // The allowed margin of minutes after the expected check-in time that - // the monitor will not be considered missed for. - CheckInMargin int64 `json:"checkin_margin,omitempty"` - // The allowed duration in minutes that the monitor may be `in_progress` - // for before being considered failed due to timeout. - MaxRuntime int64 `json:"max_runtime,omitempty"` - // A tz database string representing the timezone which the monitor's execution schedule is in. - // See: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones - Timezone string `json:"timezone,omitempty"` - // The number of consecutive failed check-ins it takes before an issue is created. - FailureIssueThreshold int64 `json:"failure_issue_threshold,omitempty"` - // The number of consecutive OK check-ins it takes before an issue is resolved. - RecoveryThreshold int64 `json:"recovery_threshold,omitempty"` -} - -type CheckIn struct { //nolint: maligned // prefer readability over optimal memory layout - // Check-In ID (unique and client generated) - ID EventID `json:"check_in_id"` - // The distinct slug of the monitor. - MonitorSlug string `json:"monitor_slug"` - // The status of the check-in. - Status CheckInStatus `json:"status"` - // The duration of the check-in. Will only take effect if the status is ok or error. - Duration time.Duration `json:"duration,omitempty"` -} - -// serializedCheckIn is used by checkInMarshalJSON method on Event struct. -// See https://develop.sentry.dev/sdk/check-ins/ -type serializedCheckIn struct { //nolint: maligned - // Check-In ID (unique and client generated). - CheckInID string `json:"check_in_id"` - // The distinct slug of the monitor. - MonitorSlug string `json:"monitor_slug"` - // The status of the check-in. - Status CheckInStatus `json:"status"` - // The duration of the check-in in seconds. Will only take effect if the status is ok or error. - Duration float64 `json:"duration,omitempty"` - Release string `json:"release,omitempty"` - Environment string `json:"environment,omitempty"` - MonitorConfig *MonitorConfig `json:"monitor_config,omitempty"` -} diff --git a/vendor/github.com/getsentry/sentry-go/client.go b/vendor/github.com/getsentry/sentry-go/client.go deleted file mode 100644 index 0d0869020..000000000 --- a/vendor/github.com/getsentry/sentry-go/client.go +++ /dev/null @@ -1,733 +0,0 @@ -package sentry - -import ( - "context" - "crypto/x509" - "fmt" - "io" - "log" - "math/rand" - "net/http" - "os" - "sort" - "strings" - "sync" - "time" - - "github.com/getsentry/sentry-go/internal/debug" -) - -// The identifier of the SDK. -const sdkIdentifier = "sentry.go" - -// maxErrorDepth is the maximum number of errors reported in a chain of errors. -// This protects the SDK from an arbitrarily long chain of wrapped errors. -// -// An additional consideration is that arguably reporting a long chain of errors -// is of little use when debugging production errors with Sentry. The Sentry UI -// is not optimized for long chains either. The top-level error together with a -// stack trace is often the most useful information. -const maxErrorDepth = 10 - -// defaultMaxSpans limits the default number of recorded spans per transaction. The limit is -// meant to bound memory usage and prevent too large transaction events that -// would be rejected by Sentry. -const defaultMaxSpans = 1000 - -// hostname is the host name reported by the kernel. It is precomputed once to -// avoid syscalls when capturing events. -// -// The error is ignored because retrieving the host name is best-effort. If the -// error is non-nil, there is nothing to do other than retrying. We choose not -// to retry for now. -var hostname, _ = os.Hostname() - -// lockedRand is a random number generator safe for concurrent use. Its API is -// intentionally limited and it is not meant as a full replacement for a -// rand.Rand. -type lockedRand struct { - mu sync.Mutex - r *rand.Rand -} - -// Float64 returns a pseudo-random number in [0.0,1.0). -func (r *lockedRand) Float64() float64 { - r.mu.Lock() - defer r.mu.Unlock() - return r.r.Float64() -} - -// rng is the internal random number generator. -// -// We do not use the global functions from math/rand because, while they are -// safe for concurrent use, any package in a build could change the seed and -// affect the generated numbers, for instance making them deterministic. On the -// other hand, the source returned from rand.NewSource is not safe for -// concurrent use, so we need to couple its use with a sync.Mutex. -var rng = &lockedRand{ - // #nosec G404 -- We are fine using transparent, non-secure value here. - r: rand.New(rand.NewSource(time.Now().UnixNano())), -} - -// usageError is used to report to Sentry an SDK usage error. -// -// It is not exported because it is never returned by any function or method in -// the exported API. -type usageError struct { - error -} - -// Logger is an instance of log.Logger that is use to provide debug information about running Sentry Client -// can be enabled by either using Logger.SetOutput directly or with Debug client option. -var Logger = log.New(io.Discard, "[Sentry] ", log.LstdFlags) - -// EventProcessor is a function that processes an event. -// Event processors are used to change an event before it is sent to Sentry. -type EventProcessor func(event *Event, hint *EventHint) *Event - -// EventModifier is the interface that wraps the ApplyToEvent method. -// -// ApplyToEvent changes an event based on external data and/or -// an event hint. -type EventModifier interface { - ApplyToEvent(event *Event, hint *EventHint, client *Client) *Event -} - -var globalEventProcessors []EventProcessor - -// AddGlobalEventProcessor adds processor to the global list of event -// processors. Global event processors apply to all events. -// -// AddGlobalEventProcessor is deprecated. Most users will prefer to initialize -// the SDK with Init and provide a ClientOptions.BeforeSend function or use -// Scope.AddEventProcessor instead. -func AddGlobalEventProcessor(processor EventProcessor) { - globalEventProcessors = append(globalEventProcessors, processor) -} - -// Integration allows for registering a functions that modify or discard captured events. -type Integration interface { - Name() string - SetupOnce(client *Client) -} - -// ClientOptions that configures a SDK Client. -type ClientOptions struct { - // The DSN to use. If the DSN is not set, the client is effectively - // disabled. - Dsn string - // In debug mode, the debug information is printed to stdout to help you - // understand what sentry is doing. - Debug bool - // Configures whether SDK should generate and attach stacktraces to pure - // capture message calls. - AttachStacktrace bool - // The sample rate for event submission in the range [0.0, 1.0]. By default, - // all events are sent. Thus, as a historical special case, the sample rate - // 0.0 is treated as if it was 1.0. To drop all events, set the DSN to the - // empty string. - SampleRate float64 - // Enable performance tracing. - EnableTracing bool - // The sample rate for sampling traces in the range [0.0, 1.0]. - TracesSampleRate float64 - // Used to customize the sampling of traces, overrides TracesSampleRate. - TracesSampler TracesSampler - // List of regexp strings that will be used to match against event's message - // and if applicable, caught errors type and value. - // If the match is found, then a whole event will be dropped. - IgnoreErrors []string - // List of regexp strings that will be used to match against a transaction's - // name. If a match is found, then the transaction will be dropped. - IgnoreTransactions []string - // If this flag is enabled, certain personally identifiable information (PII) is added by active integrations. - // By default, no such data is sent. - SendDefaultPII bool - // BeforeSend is called before error events are sent to Sentry. - // Use it to mutate the event or return nil to discard the event. - BeforeSend func(event *Event, hint *EventHint) *Event - // BeforeSendTransaction is called before transaction events are sent to Sentry. - // Use it to mutate the transaction or return nil to discard the transaction. - BeforeSendTransaction func(event *Event, hint *EventHint) *Event - // Before breadcrumb add callback. - BeforeBreadcrumb func(breadcrumb *Breadcrumb, hint *BreadcrumbHint) *Breadcrumb - // Integrations to be installed on the current Client, receives default - // integrations. - Integrations func([]Integration) []Integration - // io.Writer implementation that should be used with the Debug mode. - DebugWriter io.Writer - // The transport to use. Defaults to HTTPTransport. - Transport Transport - // The server name to be reported. - ServerName string - // The release to be sent with events. - // - // Some Sentry features are built around releases, and, thus, reporting - // events with a non-empty release improves the product experience. See - // https://docs.sentry.io/product/releases/. - // - // If Release is not set, the SDK will try to derive a default value - // from environment variables or the Git repository in the working - // directory. - // - // If you distribute a compiled binary, it is recommended to set the - // Release value explicitly at build time. As an example, you can use: - // - // go build -ldflags='-X main.release=VALUE' - // - // That will set the value of a predeclared variable 'release' in the - // 'main' package to 'VALUE'. Then, use that variable when initializing - // the SDK: - // - // sentry.Init(ClientOptions{Release: release}) - // - // See https://golang.org/cmd/go/ and https://golang.org/cmd/link/ for - // the official documentation of -ldflags and -X, respectively. - Release string - // The dist to be sent with events. - Dist string - // The environment to be sent with events. - Environment string - // Maximum number of breadcrumbs - // when MaxBreadcrumbs is negative then ignore breadcrumbs. - MaxBreadcrumbs int - // Maximum number of spans. - // - // See https://develop.sentry.dev/sdk/envelopes/#size-limits for size limits - // applied during event ingestion. Events that exceed these limits might get dropped. - MaxSpans int - // An optional pointer to http.Client that will be used with a default - // HTTPTransport. Using your own client will make HTTPTransport, HTTPProxy, - // HTTPSProxy and CaCerts options ignored. - HTTPClient *http.Client - // An optional pointer to http.Transport that will be used with a default - // HTTPTransport. Using your own transport will make HTTPProxy, HTTPSProxy - // and CaCerts options ignored. - HTTPTransport http.RoundTripper - // An optional HTTP proxy to use. - // This will default to the HTTP_PROXY environment variable. - HTTPProxy string - // An optional HTTPS proxy to use. - // This will default to the HTTPS_PROXY environment variable. - // HTTPS_PROXY takes precedence over HTTP_PROXY for https requests. - HTTPSProxy string - // An optional set of SSL certificates to use. - CaCerts *x509.CertPool - // MaxErrorDepth is the maximum number of errors reported in a chain of errors. - // This protects the SDK from an arbitrarily long chain of wrapped errors. - // - // An additional consideration is that arguably reporting a long chain of errors - // is of little use when debugging production errors with Sentry. The Sentry UI - // is not optimized for long chains either. The top-level error together with a - // stack trace is often the most useful information. - MaxErrorDepth int - // Default event tags. These are overridden by tags set on a scope. - Tags map[string]string -} - -// Client is the underlying processor that is used by the main API and Hub -// instances. It must be created with NewClient. -type Client struct { - mu sync.RWMutex - options ClientOptions - dsn *Dsn - eventProcessors []EventProcessor - integrations []Integration - sdkIdentifier string - sdkVersion string - // Transport is read-only. Replacing the transport of an existing client is - // not supported, create a new client instead. - Transport Transport -} - -// NewClient creates and returns an instance of Client configured using -// ClientOptions. -// -// Most users will not create clients directly. Instead, initialize the SDK with -// Init and use the package-level functions (for simple programs that run on a -// single goroutine) or hub methods (for concurrent programs, for example web -// servers). -func NewClient(options ClientOptions) (*Client, error) { - // The default error event sample rate for all SDKs is 1.0 (send all). - // - // In Go, the zero value (default) for float64 is 0.0, which means that - // constructing a client with NewClient(ClientOptions{}), or, equivalently, - // initializing the SDK with Init(ClientOptions{}) without an explicit - // SampleRate would drop all events. - // - // To retain the desired default behavior, we exceptionally flip SampleRate - // from 0.0 to 1.0 here. Setting the sample rate to 0.0 is not very useful - // anyway, and the same end result can be achieved in many other ways like - // not initializing the SDK, setting the DSN to the empty string or using an - // event processor that always returns nil. - // - // An alternative API could be such that default options don't need to be - // the same as Go's zero values, for example using the Functional Options - // pattern. That would either require a breaking change if we want to reuse - // the obvious NewClient name, or a new function as an alternative - // constructor. - if options.SampleRate == 0.0 { - options.SampleRate = 1.0 - } - - if options.Debug { - debugWriter := options.DebugWriter - if debugWriter == nil { - debugWriter = os.Stderr - } - Logger.SetOutput(debugWriter) - } - - if options.Dsn == "" { - options.Dsn = os.Getenv("SENTRY_DSN") - } - - if options.Release == "" { - options.Release = defaultRelease() - } - - if options.Environment == "" { - options.Environment = os.Getenv("SENTRY_ENVIRONMENT") - } - - if options.MaxErrorDepth == 0 { - options.MaxErrorDepth = maxErrorDepth - } - - if options.MaxSpans == 0 { - options.MaxSpans = defaultMaxSpans - } - - // SENTRYGODEBUG is a comma-separated list of key=value pairs (similar - // to GODEBUG). It is not a supported feature: recognized debug options - // may change any time. - // - // The intended public is SDK developers. It is orthogonal to - // options.Debug, which is also available for SDK users. - dbg := strings.Split(os.Getenv("SENTRYGODEBUG"), ",") - sort.Strings(dbg) - // dbgOpt returns true when the given debug option is enabled, for - // example SENTRYGODEBUG=someopt=1. - dbgOpt := func(opt string) bool { - s := opt + "=1" - return dbg[sort.SearchStrings(dbg, s)%len(dbg)] == s - } - if dbgOpt("httpdump") || dbgOpt("httptrace") { - options.HTTPTransport = &debug.Transport{ - RoundTripper: http.DefaultTransport, - Output: os.Stderr, - Dump: dbgOpt("httpdump"), - Trace: dbgOpt("httptrace"), - } - } - - var dsn *Dsn - if options.Dsn != "" { - var err error - dsn, err = NewDsn(options.Dsn) - if err != nil { - return nil, err - } - } - - client := Client{ - options: options, - dsn: dsn, - sdkIdentifier: sdkIdentifier, - sdkVersion: SDKVersion, - } - - client.setupTransport() - client.setupIntegrations() - - return &client, nil -} - -func (client *Client) setupTransport() { - opts := client.options - transport := opts.Transport - - if transport == nil { - if opts.Dsn == "" { - transport = new(noopTransport) - } else { - httpTransport := NewHTTPTransport() - // When tracing is enabled, use larger buffer to - // accommodate more concurrent events. - // TODO(tracing): consider using separate buffers per - // event type. - if opts.EnableTracing { - httpTransport.BufferSize = 1000 - } - transport = httpTransport - } - } - - transport.Configure(opts) - client.Transport = transport -} - -func (client *Client) setupIntegrations() { - integrations := []Integration{ - new(contextifyFramesIntegration), - new(environmentIntegration), - new(modulesIntegration), - new(ignoreErrorsIntegration), - new(ignoreTransactionsIntegration), - new(globalTagsIntegration), - } - - if client.options.Integrations != nil { - integrations = client.options.Integrations(integrations) - } - - for _, integration := range integrations { - if client.integrationAlreadyInstalled(integration.Name()) { - Logger.Printf("Integration %s is already installed\n", integration.Name()) - continue - } - client.integrations = append(client.integrations, integration) - integration.SetupOnce(client) - Logger.Printf("Integration installed: %s\n", integration.Name()) - } - - sort.Slice(client.integrations, func(i, j int) bool { - return client.integrations[i].Name() < client.integrations[j].Name() - }) -} - -// AddEventProcessor adds an event processor to the client. It must not be -// called from concurrent goroutines. Most users will prefer to use -// ClientOptions.BeforeSend or Scope.AddEventProcessor instead. -// -// Note that typical programs have only a single client created by Init and the -// client is shared among multiple hubs, one per goroutine, such that adding an -// event processor to the client affects all hubs that share the client. -func (client *Client) AddEventProcessor(processor EventProcessor) { - client.eventProcessors = append(client.eventProcessors, processor) -} - -// Options return ClientOptions for the current Client. -func (client *Client) Options() ClientOptions { - // Note: internally, consider using `client.options` instead of `client.Options()` to avoid copying the object each time. - return client.options -} - -// CaptureMessage captures an arbitrary message. -func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID { - event := client.EventFromMessage(message, LevelInfo) - return client.CaptureEvent(event, hint, scope) -} - -// CaptureException captures an error. -func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID { - event := client.EventFromException(exception, LevelError) - return client.CaptureEvent(event, hint, scope) -} - -// CaptureCheckIn captures a check in. -func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig, scope EventModifier) *EventID { - event := client.EventFromCheckIn(checkIn, monitorConfig) - if event != nil && event.CheckIn != nil { - client.CaptureEvent(event, nil, scope) - return &event.CheckIn.ID - } - return nil -} - -// CaptureEvent captures an event on the currently active client if any. -// -// The event must already be assembled. Typically code would instead use -// the utility methods like CaptureException. The return value is the -// event ID. In case Sentry is disabled or event was dropped, the return value will be nil. -func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID { - return client.processEvent(event, hint, scope) -} - -// Recover captures a panic. -// Returns EventID if successfully, or nil if there's no error to recover from. -func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModifier) *EventID { - if err == nil { - err = recover() - } - - // Normally we would not pass a nil Context, but RecoverWithContext doesn't - // use the Context for communicating deadline nor cancelation. All it does - // is store the Context in the EventHint and there nil means the Context is - // not available. - // nolint: staticcheck - return client.RecoverWithContext(nil, err, hint, scope) -} - -// RecoverWithContext captures a panic and passes relevant context object. -// Returns EventID if successfully, or nil if there's no error to recover from. -func (client *Client) RecoverWithContext( - ctx context.Context, - err interface{}, - hint *EventHint, - scope EventModifier, -) *EventID { - if err == nil { - err = recover() - } - if err == nil { - return nil - } - - if ctx != nil { - if hint == nil { - hint = &EventHint{} - } - if hint.Context == nil { - hint.Context = ctx - } - } - - var event *Event - switch err := err.(type) { - case error: - event = client.EventFromException(err, LevelFatal) - case string: - event = client.EventFromMessage(err, LevelFatal) - default: - event = client.EventFromMessage(fmt.Sprintf("%#v", err), LevelFatal) - } - return client.CaptureEvent(event, hint, scope) -} - -// Flush waits until the underlying Transport sends any buffered events to the -// Sentry server, blocking for at most the given timeout. It returns false if -// the timeout was reached. In that case, some events may not have been sent. -// -// Flush should be called before terminating the program to avoid -// unintentionally dropping events. -// -// Do not call Flush indiscriminately after every call to CaptureEvent, -// CaptureException or CaptureMessage. Instead, to have the SDK send events over -// the network synchronously, configure it to use the HTTPSyncTransport in the -// call to Init. -func (client *Client) Flush(timeout time.Duration) bool { - return client.Transport.Flush(timeout) -} - -// Close clean up underlying Transport resources. -// -// Close should be called after Flush and before terminating the program -// otherwise some events may be lost. -func (client *Client) Close() { - client.Transport.Close() -} - -// EventFromMessage creates an event from the given message string. -func (client *Client) EventFromMessage(message string, level Level) *Event { - if message == "" { - err := usageError{fmt.Errorf("%s called with empty message", callerFunctionName())} - return client.EventFromException(err, level) - } - event := NewEvent() - event.Level = level - event.Message = message - - if client.options.AttachStacktrace { - event.Threads = []Thread{{ - Stacktrace: NewStacktrace(), - Crashed: false, - Current: true, - }} - } - - return event -} - -// EventFromException creates a new Sentry event from the given `error` instance. -func (client *Client) EventFromException(exception error, level Level) *Event { - event := NewEvent() - event.Level = level - - err := exception - if err == nil { - err = usageError{fmt.Errorf("%s called with nil error", callerFunctionName())} - } - - event.SetException(err, client.options.MaxErrorDepth) - - return event -} - -// EventFromCheckIn creates a new Sentry event from the given `check_in` instance. -func (client *Client) EventFromCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *Event { - if checkIn == nil { - return nil - } - - event := NewEvent() - event.Type = checkInType - - var checkInID EventID - if checkIn.ID == "" { - checkInID = EventID(uuid()) - } else { - checkInID = checkIn.ID - } - - event.CheckIn = &CheckIn{ - ID: checkInID, - MonitorSlug: checkIn.MonitorSlug, - Status: checkIn.Status, - Duration: checkIn.Duration, - } - event.MonitorConfig = monitorConfig - - return event -} - -func (client *Client) SetSDKIdentifier(identifier string) { - client.mu.Lock() - defer client.mu.Unlock() - - client.sdkIdentifier = identifier -} - -func (client *Client) GetSDKIdentifier() string { - client.mu.RLock() - defer client.mu.RUnlock() - - return client.sdkIdentifier -} - -func (client *Client) processEvent(event *Event, hint *EventHint, scope EventModifier) *EventID { - if event == nil { - err := usageError{fmt.Errorf("%s called with nil event", callerFunctionName())} - return client.CaptureException(err, hint, scope) - } - - // Transactions are sampled by options.TracesSampleRate or - // options.TracesSampler when they are started. Other events - // (errors, messages) are sampled here. Does not apply to check-ins. - if event.Type != transactionType && event.Type != checkInType && !sample(client.options.SampleRate) { - Logger.Println("Event dropped due to SampleRate hit.") - return nil - } - - if event = client.prepareEvent(event, hint, scope); event == nil { - return nil - } - - // Apply beforeSend* processors - if hint == nil { - hint = &EventHint{} - } - if event.Type == transactionType && client.options.BeforeSendTransaction != nil { - // Transaction events - if event = client.options.BeforeSendTransaction(event, hint); event == nil { - Logger.Println("Transaction dropped due to BeforeSendTransaction callback.") - return nil - } - } else if event.Type != transactionType && event.Type != checkInType && client.options.BeforeSend != nil { - // All other events - if event = client.options.BeforeSend(event, hint); event == nil { - Logger.Println("Event dropped due to BeforeSend callback.") - return nil - } - } - - client.Transport.SendEvent(event) - - return &event.EventID -} - -func (client *Client) prepareEvent(event *Event, hint *EventHint, scope EventModifier) *Event { - if event.EventID == "" { - // TODO set EventID when the event is created, same as in other SDKs. It's necessary for profileTransaction.ID. - event.EventID = EventID(uuid()) - } - - if event.Timestamp.IsZero() { - event.Timestamp = time.Now() - } - - if event.Level == "" { - event.Level = LevelInfo - } - - if event.ServerName == "" { - event.ServerName = client.options.ServerName - - if event.ServerName == "" { - event.ServerName = hostname - } - } - - if event.Release == "" { - event.Release = client.options.Release - } - - if event.Dist == "" { - event.Dist = client.options.Dist - } - - if event.Environment == "" { - event.Environment = client.options.Environment - } - - event.Platform = "go" - event.Sdk = SdkInfo{ - Name: client.GetSDKIdentifier(), - Version: SDKVersion, - Integrations: client.listIntegrations(), - Packages: []SdkPackage{{ - Name: "sentry-go", - Version: SDKVersion, - }}, - } - - if scope != nil { - event = scope.ApplyToEvent(event, hint, client) - if event == nil { - return nil - } - } - - for _, processor := range client.eventProcessors { - id := event.EventID - event = processor(event, hint) - if event == nil { - Logger.Printf("Event dropped by one of the Client EventProcessors: %s\n", id) - return nil - } - } - - for _, processor := range globalEventProcessors { - id := event.EventID - event = processor(event, hint) - if event == nil { - Logger.Printf("Event dropped by one of the Global EventProcessors: %s\n", id) - return nil - } - } - - return event -} - -func (client *Client) listIntegrations() []string { - integrations := make([]string, len(client.integrations)) - for i, integration := range client.integrations { - integrations[i] = integration.Name() - } - return integrations -} - -func (client *Client) integrationAlreadyInstalled(name string) bool { - for _, integration := range client.integrations { - if integration.Name() == name { - return true - } - } - return false -} - -// sample returns true with the given probability, which must be in the range -// [0.0, 1.0]. -func sample(probability float64) bool { - return rng.Float64() < probability -} diff --git a/vendor/github.com/getsentry/sentry-go/doc.go b/vendor/github.com/getsentry/sentry-go/doc.go deleted file mode 100644 index 973020ae8..000000000 --- a/vendor/github.com/getsentry/sentry-go/doc.go +++ /dev/null @@ -1,6 +0,0 @@ -/* -Package repository: https://github.com/getsentry/sentry-go/ - -For more information about Sentry and SDK features, please have a look at the official documentation site: https://docs.sentry.io/platforms/go/ -*/ -package sentry diff --git a/vendor/github.com/getsentry/sentry-go/dsn.go b/vendor/github.com/getsentry/sentry-go/dsn.go deleted file mode 100644 index 36b9925a1..000000000 --- a/vendor/github.com/getsentry/sentry-go/dsn.go +++ /dev/null @@ -1,233 +0,0 @@ -package sentry - -import ( - "encoding/json" - "fmt" - "net/url" - "strconv" - "strings" - "time" -) - -type scheme string - -const ( - schemeHTTP scheme = "http" - schemeHTTPS scheme = "https" -) - -func (scheme scheme) defaultPort() int { - switch scheme { - case schemeHTTPS: - return 443 - case schemeHTTP: - return 80 - default: - return 80 - } -} - -// DsnParseError represents an error that occurs if a Sentry -// DSN cannot be parsed. -type DsnParseError struct { - Message string -} - -func (e DsnParseError) Error() string { - return "[Sentry] DsnParseError: " + e.Message -} - -// Dsn is used as the remote address source to client transport. -type Dsn struct { - scheme scheme - publicKey string - secretKey string - host string - port int - path string - projectID string -} - -// NewDsn creates a Dsn by parsing rawURL. Most users will never call this -// function directly. It is provided for use in custom Transport -// implementations. -func NewDsn(rawURL string) (*Dsn, error) { - // Parse - parsedURL, err := url.Parse(rawURL) - if err != nil { - return nil, &DsnParseError{fmt.Sprintf("invalid url: %v", err)} - } - - // Scheme - var scheme scheme - switch parsedURL.Scheme { - case "http": - scheme = schemeHTTP - case "https": - scheme = schemeHTTPS - default: - return nil, &DsnParseError{"invalid scheme"} - } - - // PublicKey - publicKey := parsedURL.User.Username() - if publicKey == "" { - return nil, &DsnParseError{"empty username"} - } - - // SecretKey - var secretKey string - if parsedSecretKey, ok := parsedURL.User.Password(); ok { - secretKey = parsedSecretKey - } - - // Host - host := parsedURL.Hostname() - if host == "" { - return nil, &DsnParseError{"empty host"} - } - - // Port - var port int - if p := parsedURL.Port(); p != "" { - port, err = strconv.Atoi(p) - if err != nil { - return nil, &DsnParseError{"invalid port"} - } - } else { - port = scheme.defaultPort() - } - - // ProjectID - if parsedURL.Path == "" || parsedURL.Path == "/" { - return nil, &DsnParseError{"empty project id"} - } - pathSegments := strings.Split(parsedURL.Path[1:], "/") - projectID := pathSegments[len(pathSegments)-1] - - if projectID == "" { - return nil, &DsnParseError{"empty project id"} - } - - // Path - var path string - if len(pathSegments) > 1 { - path = "/" + strings.Join(pathSegments[0:len(pathSegments)-1], "/") - } - - return &Dsn{ - scheme: scheme, - publicKey: publicKey, - secretKey: secretKey, - host: host, - port: port, - path: path, - projectID: projectID, - }, nil -} - -// String formats Dsn struct into a valid string url. -func (dsn Dsn) String() string { - var url string - url += fmt.Sprintf("%s://%s", dsn.scheme, dsn.publicKey) - if dsn.secretKey != "" { - url += fmt.Sprintf(":%s", dsn.secretKey) - } - url += fmt.Sprintf("@%s", dsn.host) - if dsn.port != dsn.scheme.defaultPort() { - url += fmt.Sprintf(":%d", dsn.port) - } - if dsn.path != "" { - url += dsn.path - } - url += fmt.Sprintf("/%s", dsn.projectID) - return url -} - -// Get the scheme of the DSN. -func (dsn Dsn) GetScheme() string { - return string(dsn.scheme) -} - -// Get the public key of the DSN. -func (dsn Dsn) GetPublicKey() string { - return dsn.publicKey -} - -// Get the secret key of the DSN. -func (dsn Dsn) GetSecretKey() string { - return dsn.secretKey -} - -// Get the host of the DSN. -func (dsn Dsn) GetHost() string { - return dsn.host -} - -// Get the port of the DSN. -func (dsn Dsn) GetPort() int { - return dsn.port -} - -// Get the path of the DSN. -func (dsn Dsn) GetPath() string { - return dsn.path -} - -// Get the project ID of the DSN. -func (dsn Dsn) GetProjectID() string { - return dsn.projectID -} - -// GetAPIURL returns the URL of the envelope endpoint of the project -// associated with the DSN. -func (dsn Dsn) GetAPIURL() *url.URL { - var rawURL string - rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host) - if dsn.port != dsn.scheme.defaultPort() { - rawURL += fmt.Sprintf(":%d", dsn.port) - } - if dsn.path != "" { - rawURL += dsn.path - } - rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope") - parsedURL, _ := url.Parse(rawURL) - return parsedURL -} - -// RequestHeaders returns all the necessary headers that have to be used in the transport when seinding events -// to the /store endpoint. -// -// Deprecated: This method shall only be used if you want to implement your own transport that sends events to -// the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate -// against the /envelope endpoint are added automatically. -func (dsn Dsn) RequestHeaders() map[string]string { - auth := fmt.Sprintf("Sentry sentry_version=%s, sentry_timestamp=%d, "+ - "sentry_client=sentry.go/%s, sentry_key=%s", apiVersion, time.Now().Unix(), SDKVersion, dsn.publicKey) - - if dsn.secretKey != "" { - auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey) - } - - return map[string]string{ - "Content-Type": "application/json", - "X-Sentry-Auth": auth, - } -} - -// MarshalJSON converts the Dsn struct to JSON. -func (dsn Dsn) MarshalJSON() ([]byte, error) { - return json.Marshal(dsn.String()) -} - -// UnmarshalJSON converts JSON data to the Dsn struct. -func (dsn *Dsn) UnmarshalJSON(data []byte) error { - var str string - _ = json.Unmarshal(data, &str) - newDsn, err := NewDsn(str) - if err != nil { - return err - } - *dsn = *newDsn - return nil -} diff --git a/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go b/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go deleted file mode 100644 index 8dae0838b..000000000 --- a/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go +++ /dev/null @@ -1,154 +0,0 @@ -package sentry - -import ( - "strconv" - "strings" - - "github.com/getsentry/sentry-go/internal/otel/baggage" -) - -const ( - sentryPrefix = "sentry-" -) - -// DynamicSamplingContext holds information about the current event that can be used to make dynamic sampling decisions. -type DynamicSamplingContext struct { - Entries map[string]string - Frozen bool -} - -func DynamicSamplingContextFromHeader(header []byte) (DynamicSamplingContext, error) { - bag, err := baggage.Parse(string(header)) - if err != nil { - return DynamicSamplingContext{}, err - } - - entries := map[string]string{} - for _, member := range bag.Members() { - // We only store baggage members if their key starts with "sentry-". - if k, v := member.Key(), member.Value(); strings.HasPrefix(k, sentryPrefix) { - entries[strings.TrimPrefix(k, sentryPrefix)] = v - } - } - - return DynamicSamplingContext{ - Entries: entries, - // If there's at least one Sentry value, we consider the DSC frozen - Frozen: len(entries) > 0, - }, nil -} - -func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext { - hub := hubFromContext(span.Context()) - scope := hub.Scope() - client := hub.Client() - - if client == nil || scope == nil { - return DynamicSamplingContext{ - Entries: map[string]string{}, - Frozen: false, - } - } - - entries := make(map[string]string) - - if traceID := span.TraceID.String(); traceID != "" { - entries["trace_id"] = traceID - } - if sampleRate := span.sampleRate; sampleRate != 0 { - entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) - } - - if dsn := client.dsn; dsn != nil { - if publicKey := dsn.publicKey; publicKey != "" { - entries["public_key"] = publicKey - } - } - if release := client.options.Release; release != "" { - entries["release"] = release - } - if environment := client.options.Environment; environment != "" { - entries["environment"] = environment - } - - // Only include the transaction name if it's of good quality (not empty and not SourceURL) - if span.Source != "" && span.Source != SourceURL { - if span.IsTransaction() { - entries["transaction"] = span.Name - } - } - - entries["sampled"] = strconv.FormatBool(span.Sampled.Bool()) - - return DynamicSamplingContext{Entries: entries, Frozen: true} -} - -func (d DynamicSamplingContext) HasEntries() bool { - return len(d.Entries) > 0 -} - -func (d DynamicSamplingContext) IsFrozen() bool { - return d.Frozen -} - -func (d DynamicSamplingContext) String() string { - members := []baggage.Member{} - for k, entry := range d.Entries { - member, err := baggage.NewMember(sentryPrefix+k, entry) - if err != nil { - continue - } - members = append(members, member) - } - - if len(members) == 0 { - return "" - } - - baggage, err := baggage.New(members...) - if err != nil { - return "" - } - - return baggage.String() -} - -// Constructs a new DynamicSamplingContext using a scope and client. Accessing -// fields on the scope are not thread safe, and this function should only be -// called within scope methods. -func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext { - entries := map[string]string{} - - if client == nil || scope == nil { - return DynamicSamplingContext{ - Entries: entries, - Frozen: false, - } - } - - propagationContext := scope.propagationContext - - if traceID := propagationContext.TraceID.String(); traceID != "" { - entries["trace_id"] = traceID - } - if sampleRate := client.options.TracesSampleRate; sampleRate != 0 { - entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) - } - - if dsn := client.dsn; dsn != nil { - if publicKey := dsn.publicKey; publicKey != "" { - entries["public_key"] = publicKey - } - } - if release := client.options.Release; release != "" { - entries["release"] = release - } - if environment := client.options.Environment; environment != "" { - entries["environment"] = environment - } - - return DynamicSamplingContext{ - Entries: entries, - Frozen: true, - } -} diff --git a/vendor/github.com/getsentry/sentry-go/echo/LICENSE b/vendor/github.com/getsentry/sentry-go/echo/LICENSE deleted file mode 100644 index b1b358e41..000000000 --- a/vendor/github.com/getsentry/sentry-go/echo/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Functional Software, Inc. dba Sentry - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/getsentry/sentry-go/echo/README.md b/vendor/github.com/getsentry/sentry-go/echo/README.md deleted file mode 100644 index b1be6ec3b..000000000 --- a/vendor/github.com/getsentry/sentry-go/echo/README.md +++ /dev/null @@ -1,135 +0,0 @@ -

- - - -
-

- -# Official Sentry Echo Handler for Sentry-go SDK - -**go.dev:** https://pkg.go.dev/github.com/getsentry/sentry-go/echo - -**Example:** https://github.com/getsentry/sentry-go/tree/master/_examples/echo - -## Installation - -```sh -go get github.com/getsentry/sentry-go/echo -``` - -```go -import ( - "fmt" - "net/http" - - "github.com/getsentry/sentry-go" - sentryecho "github.com/getsentry/sentry-go/echo" - "github.com/labstack/echo/v4" - "github.com/labstack/echo/v4/middleware" -) - -// To initialize Sentry's handler, you need to initialize Sentry itself beforehand -if err := sentry.Init(sentry.ClientOptions{ - Dsn: "your-public-dsn", -}); err != nil { - fmt.Printf("Sentry initialization failed: %v\n", err) -} - -// Then create your app -app := echo.New() - -app.Use(middleware.Logger()) -app.Use(middleware.Recover()) - -// Once it's done, you can attach the handler as one of your middleware -app.Use(sentryecho.New(sentryecho.Options{})) - -// Set up routes -app.GET("/", func(ctx echo.Context) error { - return ctx.String(http.StatusOK, "Hello, World!") -}) - -// And run it -app.Logger.Fatal(app.Start(":3000")) -``` - -## Configuration - -`sentryecho` accepts a struct of `Options` that allows you to configure how the handler will behave. - -Currently it respects 3 options: - -```go -// Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to true, -// as echo includes its own Recover middleware that handles http responses. -Repanic bool -// WaitForDelivery configures whether you want to block the request before moving forward with the response. -// Because Echo's `Recover` handler doesn't restart the application, -// it's safe to either skip this option or set it to `false`. -WaitForDelivery bool -// Timeout for the event delivery requests. -Timeout time.Duration -``` - -## Usage - -`sentryecho` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the `echo.Context`, which makes it available throughout the rest of the request's lifetime. -You can access it by using the `sentryecho.GetHubFromContext()` method on the context itself in any of your proceeding middleware and routes. -And it should be used instead of the global `sentry.CaptureMessage`, `sentry.CaptureException`, or any other calls, as it keeps the separation of data between the requests. - -**Keep in mind that `*sentry.Hub` won't be available in middleware attached before to `sentryecho`!** - -```go -app := echo.New() - -app.Use(middleware.Logger()) -app.Use(middleware.Recover()) - -app.Use(sentryecho.New(sentryecho.Options{ - Repanic: true, -})) - -app.Use(func(next echo.HandlerFunc) echo.HandlerFunc { - return func(ctx echo.Context) error { - if hub := sentryecho.GetHubFromContext(ctx); hub != nil { - hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt") - } - return next(ctx) - } -}) - -app.GET("/", func(ctx echo.Context) error { - if hub := sentryecho.GetHubFromContext(ctx); hub != nil { - hub.WithScope(func(scope *sentry.Scope) { - scope.SetExtra("unwantedQuery", "someQueryDataMaybe") - hub.CaptureMessage("User provided unwanted query string, but we recovered just fine") - }) - } - return ctx.String(http.StatusOK, "Hello, World!") -}) - -app.GET("/foo", func(ctx echo.Context) error { - // sentryecho handler will catch it just fine. Also, because we attached "someRandomTag" - // in the middleware before, it will be sent through as well - panic("y tho") -}) - -app.Logger.Fatal(app.Start(":3000")) -``` - -### Accessing Request in `BeforeSend` callback - -```go -sentry.Init(sentry.ClientOptions{ - Dsn: "your-public-dsn", - BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event { - if hint.Context != nil { - if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok { - // You have access to the original Request here - } - } - - return event - }, -}) -``` diff --git a/vendor/github.com/getsentry/sentry-go/echo/sentryecho.go b/vendor/github.com/getsentry/sentry-go/echo/sentryecho.go deleted file mode 100644 index b892577c1..000000000 --- a/vendor/github.com/getsentry/sentry-go/echo/sentryecho.go +++ /dev/null @@ -1,158 +0,0 @@ -package sentryecho - -import ( - "context" - "fmt" - "net/http" - "time" - - "github.com/getsentry/sentry-go" - "github.com/labstack/echo/v4" -) - -const ( - // sdkIdentifier is the identifier of the Echo SDK. - sdkIdentifier = "sentry.go.echo" - - // valuesKey is used as a key to store the Sentry Hub instance on the echo.Context. - valuesKey = "sentry" - - // transactionKey is used as a key to store the Sentry transaction on the echo.Context. - transactionKey = "sentry_transaction" - - // errorKey is used as a key to store the error on the echo.Context. - errorKey = "error" -) - -type handler struct { - repanic bool - waitForDelivery bool - timeout time.Duration -} - -type Options struct { - // Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to true, - // as Echo includes its own Recover middleware that handles HTTP responses. - Repanic bool - // WaitForDelivery configures whether you want to block the request before moving forward with the response. - // Because Echo's Recover handler doesn't restart the application, - // it's safe to either skip this option or set it to false. - WaitForDelivery bool - // Timeout for the event delivery requests. - Timeout time.Duration -} - -// New returns a function that satisfies echo.HandlerFunc interface -// It can be used with Use() methods. -func New(options Options) echo.MiddlewareFunc { - if options.Timeout == 0 { - options.Timeout = 2 * time.Second - } - - return (&handler{ - repanic: options.Repanic, - timeout: options.Timeout, - waitForDelivery: options.WaitForDelivery, - }).handle -} - -func (h *handler) handle(next echo.HandlerFunc) echo.HandlerFunc { - return func(ctx echo.Context) error { - hub := GetHubFromContext(ctx) - if hub == nil { - hub = sentry.CurrentHub().Clone() - } - - if client := hub.Client(); client != nil { - client.SetSDKIdentifier(sdkIdentifier) - } - - r := ctx.Request() - - transactionName := r.URL.Path - transactionSource := sentry.SourceURL - - if path := ctx.Path(); path != "" { - transactionName = path - transactionSource = sentry.SourceRoute - } - - options := []sentry.SpanOption{ - sentry.ContinueTrace(hub, r.Header.Get(sentry.SentryTraceHeader), r.Header.Get(sentry.SentryBaggageHeader)), - sentry.WithOpName("http.server"), - sentry.WithTransactionSource(transactionSource), - sentry.WithSpanOrigin(sentry.SpanOriginEcho), - } - - transaction := sentry.StartTransaction( - sentry.SetHubOnContext(r.Context(), hub), - fmt.Sprintf("%s %s", r.Method, transactionName), - options..., - ) - - transaction.SetData("http.request.method", r.Method) - - defer func() { - status := ctx.Response().Status - if err := ctx.Get(errorKey); err != nil { - if httpError, ok := err.(*echo.HTTPError); ok { - status = httpError.Code - } - } - - transaction.Status = sentry.HTTPtoSpanStatus(status) - transaction.SetData("http.response.status_code", status) - transaction.Finish() - }() - - hub.Scope().SetRequest(r) - ctx.Set(valuesKey, hub) - ctx.Set(transactionKey, transaction) - defer h.recoverWithSentry(hub, r) - - err := next(ctx) - if err != nil { - // Store the error so it can be used in the deferred function - ctx.Set(errorKey, err) - } - - return err - } -} - -func (h *handler) recoverWithSentry(hub *sentry.Hub, r *http.Request) { - if err := recover(); err != nil { - eventID := hub.RecoverWithContext( - context.WithValue(r.Context(), sentry.RequestContextKey, r), - err, - ) - if eventID != nil && h.waitForDelivery { - hub.Flush(h.timeout) - } - if h.repanic { - panic(err) - } - } -} - -// GetHubFromContext retrieves attached *sentry.Hub instance from echo.Context. -func GetHubFromContext(ctx echo.Context) *sentry.Hub { - if hub, ok := ctx.Get(valuesKey).(*sentry.Hub); ok { - return hub - } - return nil -} - -// SetHubOnContext attaches *sentry.Hub instance to echo.Context. -func SetHubOnContext(ctx echo.Context, hub *sentry.Hub) { - ctx.Set(valuesKey, hub) -} - -// GetSpanFromContext retrieves attached *sentry.Span instance from echo.Context. -// If there is no transaction on echo.Context, it will return nil. -func GetSpanFromContext(ctx echo.Context) *sentry.Span { - if span, ok := ctx.Get(transactionKey).(*sentry.Span); ok { - return span - } - return nil -} diff --git a/vendor/github.com/getsentry/sentry-go/hub.go b/vendor/github.com/getsentry/sentry-go/hub.go deleted file mode 100644 index 04cebee3e..000000000 --- a/vendor/github.com/getsentry/sentry-go/hub.go +++ /dev/null @@ -1,423 +0,0 @@ -package sentry - -import ( - "context" - "fmt" - "sync" - "time" -) - -type contextKey int - -// Keys used to store values in a Context. Use with Context.Value to access -// values stored by the SDK. -const ( - // HubContextKey is the key used to store the current Hub. - HubContextKey = contextKey(1) - // RequestContextKey is the key used to store the current http.Request. - RequestContextKey = contextKey(2) -) - -// defaultMaxBreadcrumbs is the default maximum number of breadcrumbs added to -// an event. Can be overwritten with the maxBreadcrumbs option. -const defaultMaxBreadcrumbs = 30 - -// maxBreadcrumbs is the absolute maximum number of breadcrumbs added to an -// event. The maxBreadcrumbs option cannot be set higher than this value. -const maxBreadcrumbs = 100 - -// currentHub is the initial Hub with no Client bound and an empty Scope. -var currentHub = NewHub(nil, NewScope()) - -// Hub is the central object that manages scopes and clients. -// -// This can be used to capture events and manage the scope. -// The default hub that is available automatically. -// -// In most situations developers do not need to interface the hub. Instead -// toplevel convenience functions are exposed that will automatically dispatch -// to global (CurrentHub) hub. In some situations this might not be -// possible in which case it might become necessary to manually work with the -// hub. This is for instance the case when working with async code. -type Hub struct { - mu sync.RWMutex - stack *stack - lastEventID EventID -} - -type layer struct { - // mu protects concurrent reads and writes to client. - mu sync.RWMutex - client *Client - // scope is read-only, not protected by mu. - scope *Scope -} - -// Client returns the layer's client. Safe for concurrent use. -func (l *layer) Client() *Client { - l.mu.RLock() - defer l.mu.RUnlock() - return l.client -} - -// SetClient sets the layer's client. Safe for concurrent use. -func (l *layer) SetClient(c *Client) { - l.mu.Lock() - defer l.mu.Unlock() - l.client = c -} - -type stack []*layer - -// NewHub returns an instance of a Hub with provided Client and Scope bound. -func NewHub(client *Client, scope *Scope) *Hub { - hub := Hub{ - stack: &stack{{ - client: client, - scope: scope, - }}, - } - return &hub -} - -// CurrentHub returns an instance of previously initialized Hub stored in the global namespace. -func CurrentHub() *Hub { - return currentHub -} - -// LastEventID returns the ID of the last event (error or message) captured -// through the hub and sent to the underlying transport. -// -// Transactions and events dropped by sampling or event processors do not change -// the last event ID. -// -// LastEventID is a convenience method to cover use cases in which errors are -// captured indirectly and the ID is needed. For example, it can be used as part -// of an HTTP middleware to log the ID of the last error, if any. -// -// For more flexibility, consider instead using the ClientOptions.BeforeSend -// function or event processors. -func (hub *Hub) LastEventID() EventID { - hub.mu.RLock() - defer hub.mu.RUnlock() - - return hub.lastEventID -} - -// stackTop returns the top layer of the hub stack. Valid hubs always have at -// least one layer, therefore stackTop always return a non-nil pointer. -func (hub *Hub) stackTop() *layer { - hub.mu.RLock() - defer hub.mu.RUnlock() - - stack := hub.stack - stackLen := len(*stack) - top := (*stack)[stackLen-1] - return top -} - -// Clone returns a copy of the current Hub with top-most scope and client copied over. -func (hub *Hub) Clone() *Hub { - top := hub.stackTop() - scope := top.scope - if scope != nil { - scope = scope.Clone() - } - return NewHub(top.Client(), scope) -} - -// Scope returns top-level Scope of the current Hub or nil if no Scope is bound. -func (hub *Hub) Scope() *Scope { - top := hub.stackTop() - return top.scope -} - -// Client returns top-level Client of the current Hub or nil if no Client is bound. -func (hub *Hub) Client() *Client { - top := hub.stackTop() - return top.Client() -} - -// PushScope pushes a new scope for the current Hub and reuses previously bound Client. -func (hub *Hub) PushScope() *Scope { - top := hub.stackTop() - - var scope *Scope - if top.scope != nil { - scope = top.scope.Clone() - } else { - scope = NewScope() - } - - hub.mu.Lock() - defer hub.mu.Unlock() - - *hub.stack = append(*hub.stack, &layer{ - client: top.Client(), - scope: scope, - }) - - return scope -} - -// PopScope drops the most recent scope. -// -// Calls to PopScope must be coordinated with PushScope. For most cases, using -// WithScope should be more convenient. -// -// Calls to PopScope that do not match previous calls to PushScope are silently -// ignored. -func (hub *Hub) PopScope() { - hub.mu.Lock() - defer hub.mu.Unlock() - - stack := *hub.stack - stackLen := len(stack) - if stackLen > 1 { - // Never pop the last item off the stack, the stack should always have - // at least one item. - *hub.stack = stack[0 : stackLen-1] - } -} - -// BindClient binds a new Client for the current Hub. -func (hub *Hub) BindClient(client *Client) { - top := hub.stackTop() - top.SetClient(client) -} - -// WithScope runs f in an isolated temporary scope. -// -// It is useful when extra data should be sent with a single capture call, for -// instance a different level or tags. -// -// The scope passed to f starts as a clone of the current scope and can be -// freely modified without affecting the current scope. -// -// It is a shorthand for PushScope followed by PopScope. -func (hub *Hub) WithScope(f func(scope *Scope)) { - scope := hub.PushScope() - defer hub.PopScope() - f(scope) -} - -// ConfigureScope runs f in the current scope. -// -// It is useful to set data that applies to all events that share the current -// scope. -// -// Modifying the scope affects all references to the current scope. -// -// See also WithScope for making isolated temporary changes. -func (hub *Hub) ConfigureScope(f func(scope *Scope)) { - scope := hub.Scope() - f(scope) -} - -// CaptureEvent calls the method of a same name on currently bound Client instance -// passing it a top-level Scope. -// Returns EventID if successfully, or nil if there's no Scope or Client available. -func (hub *Hub) CaptureEvent(event *Event) *EventID { - client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { - return nil - } - eventID := client.CaptureEvent(event, nil, scope) - - if event.Type != transactionType && eventID != nil { - hub.mu.Lock() - hub.lastEventID = *eventID - hub.mu.Unlock() - } - return eventID -} - -// CaptureMessage calls the method of a same name on currently bound Client instance -// passing it a top-level Scope. -// Returns EventID if successfully, or nil if there's no Scope or Client available. -func (hub *Hub) CaptureMessage(message string) *EventID { - client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { - return nil - } - eventID := client.CaptureMessage(message, nil, scope) - - if eventID != nil { - hub.mu.Lock() - hub.lastEventID = *eventID - hub.mu.Unlock() - } - return eventID -} - -// CaptureException calls the method of a same name on currently bound Client instance -// passing it a top-level Scope. -// Returns EventID if successfully, or nil if there's no Scope or Client available. -func (hub *Hub) CaptureException(exception error) *EventID { - client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { - return nil - } - eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope) - - if eventID != nil { - hub.mu.Lock() - hub.lastEventID = *eventID - hub.mu.Unlock() - } - return eventID -} - -// CaptureCheckIn calls the method of the same name on currently bound Client instance -// passing it a top-level Scope. -// Returns CheckInID if the check-in was captured successfully, or nil otherwise. -func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID { - client, scope := hub.Client(), hub.Scope() - if client == nil { - return nil - } - - return client.CaptureCheckIn(checkIn, monitorConfig, scope) -} - -// AddBreadcrumb records a new breadcrumb. -// -// The total number of breadcrumbs that can be recorded are limited by the -// configuration on the client. -func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) { - client := hub.Client() - - // If there's no client, just store it on the scope straight away - if client == nil { - hub.Scope().AddBreadcrumb(breadcrumb, maxBreadcrumbs) - return - } - - max := client.options.MaxBreadcrumbs - switch { - case max < 0: - return - case max == 0: - max = defaultMaxBreadcrumbs - case max > maxBreadcrumbs: - max = maxBreadcrumbs - } - - if client.options.BeforeBreadcrumb != nil { - if hint == nil { - hint = &BreadcrumbHint{} - } - if breadcrumb = client.options.BeforeBreadcrumb(breadcrumb, hint); breadcrumb == nil { - Logger.Println("breadcrumb dropped due to BeforeBreadcrumb callback.") - return - } - } - - hub.Scope().AddBreadcrumb(breadcrumb, max) -} - -// Recover calls the method of a same name on currently bound Client instance -// passing it a top-level Scope. -// Returns EventID if successfully, or nil if there's no Scope or Client available. -func (hub *Hub) Recover(err interface{}) *EventID { - if err == nil { - err = recover() - } - client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { - return nil - } - return client.Recover(err, &EventHint{RecoveredException: err}, scope) -} - -// RecoverWithContext calls the method of a same name on currently bound Client instance -// passing it a top-level Scope. -// Returns EventID if successfully, or nil if there's no Scope or Client available. -func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventID { - if err == nil { - err = recover() - } - client, scope := hub.Client(), hub.Scope() - if client == nil || scope == nil { - return nil - } - return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope) -} - -// Flush waits until the underlying Transport sends any buffered events to the -// Sentry server, blocking for at most the given timeout. It returns false if -// the timeout was reached. In that case, some events may not have been sent. -// -// Flush should be called before terminating the program to avoid -// unintentionally dropping events. -// -// Do not call Flush indiscriminately after every call to CaptureEvent, -// CaptureException or CaptureMessage. Instead, to have the SDK send events over -// the network synchronously, configure it to use the HTTPSyncTransport in the -// call to Init. -func (hub *Hub) Flush(timeout time.Duration) bool { - client := hub.Client() - - if client == nil { - return false - } - - return client.Flush(timeout) -} - -// GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value -// or HTML meta tag value. -// This function is context aware, as in it either returns the traceparent based -// on the current span, or the scope's propagation context. -func (hub *Hub) GetTraceparent() string { - scope := hub.Scope() - - if scope.span != nil { - return scope.span.ToSentryTrace() - } - - return fmt.Sprintf("%s-%s", scope.propagationContext.TraceID, scope.propagationContext.SpanID) -} - -// GetBaggage returns the current Sentry baggage string, to be used as a HTTP header value -// or HTML meta tag value. -// This function is context aware, as in it either returns the baggage based -// on the current span or the scope's propagation context. -func (hub *Hub) GetBaggage() string { - scope := hub.Scope() - - if scope.span != nil { - return scope.span.ToBaggage() - } - - return scope.propagationContext.DynamicSamplingContext.String() -} - -// HasHubOnContext checks whether Hub instance is bound to a given Context struct. -func HasHubOnContext(ctx context.Context) bool { - _, ok := ctx.Value(HubContextKey).(*Hub) - return ok -} - -// GetHubFromContext tries to retrieve Hub instance from the given Context struct -// or return nil if one is not found. -func GetHubFromContext(ctx context.Context) *Hub { - if hub, ok := ctx.Value(HubContextKey).(*Hub); ok { - return hub - } - return nil -} - -// hubFromContext returns either a hub stored in the context or the current hub. -// The return value is guaranteed to be non-nil, unlike GetHubFromContext. -func hubFromContext(ctx context.Context) *Hub { - if hub, ok := ctx.Value(HubContextKey).(*Hub); ok { - return hub - } - return currentHub -} - -// SetHubOnContext stores given Hub instance on the Context struct and returns a new Context. -func SetHubOnContext(ctx context.Context, hub *Hub) context.Context { - return context.WithValue(ctx, HubContextKey, hub) -} diff --git a/vendor/github.com/getsentry/sentry-go/integrations.go b/vendor/github.com/getsentry/sentry-go/integrations.go deleted file mode 100644 index a8b2082a8..000000000 --- a/vendor/github.com/getsentry/sentry-go/integrations.go +++ /dev/null @@ -1,391 +0,0 @@ -package sentry - -import ( - "fmt" - "os" - "regexp" - "runtime" - "runtime/debug" - "strings" - "sync" -) - -// ================================ -// Modules Integration -// ================================ - -type modulesIntegration struct { - once sync.Once - modules map[string]string -} - -func (mi *modulesIntegration) Name() string { - return "Modules" -} - -func (mi *modulesIntegration) SetupOnce(client *Client) { - client.AddEventProcessor(mi.processor) -} - -func (mi *modulesIntegration) processor(event *Event, _ *EventHint) *Event { - if len(event.Modules) == 0 { - mi.once.Do(func() { - info, ok := debug.ReadBuildInfo() - if !ok { - Logger.Print("The Modules integration is not available in binaries built without module support.") - return - } - mi.modules = extractModules(info) - }) - } - event.Modules = mi.modules - return event -} - -func extractModules(info *debug.BuildInfo) map[string]string { - modules := map[string]string{ - info.Main.Path: info.Main.Version, - } - for _, dep := range info.Deps { - ver := dep.Version - if dep.Replace != nil { - ver += fmt.Sprintf(" => %s %s", dep.Replace.Path, dep.Replace.Version) - } - modules[dep.Path] = strings.TrimSuffix(ver, " ") - } - return modules -} - -// ================================ -// Environment Integration -// ================================ - -type environmentIntegration struct{} - -func (ei *environmentIntegration) Name() string { - return "Environment" -} - -func (ei *environmentIntegration) SetupOnce(client *Client) { - client.AddEventProcessor(ei.processor) -} - -func (ei *environmentIntegration) processor(event *Event, _ *EventHint) *Event { - // Initialize maps as necessary. - contextNames := []string{"device", "os", "runtime"} - if event.Contexts == nil { - event.Contexts = make(map[string]Context, len(contextNames)) - } - for _, name := range contextNames { - if event.Contexts[name] == nil { - event.Contexts[name] = make(Context) - } - } - - // Set contextual information preserving existing data. For each context, if - // the existing value is not of type map[string]interface{}, then no - // additional information is added. - if deviceContext, ok := event.Contexts["device"]; ok { - if _, ok := deviceContext["arch"]; !ok { - deviceContext["arch"] = runtime.GOARCH - } - if _, ok := deviceContext["num_cpu"]; !ok { - deviceContext["num_cpu"] = runtime.NumCPU() - } - } - if osContext, ok := event.Contexts["os"]; ok { - if _, ok := osContext["name"]; !ok { - osContext["name"] = runtime.GOOS - } - } - if runtimeContext, ok := event.Contexts["runtime"]; ok { - if _, ok := runtimeContext["name"]; !ok { - runtimeContext["name"] = "go" - } - if _, ok := runtimeContext["version"]; !ok { - runtimeContext["version"] = runtime.Version() - } - if _, ok := runtimeContext["go_numroutines"]; !ok { - runtimeContext["go_numroutines"] = runtime.NumGoroutine() - } - if _, ok := runtimeContext["go_maxprocs"]; !ok { - runtimeContext["go_maxprocs"] = runtime.GOMAXPROCS(0) - } - if _, ok := runtimeContext["go_numcgocalls"]; !ok { - runtimeContext["go_numcgocalls"] = runtime.NumCgoCall() - } - } - return event -} - -// ================================ -// Ignore Errors Integration -// ================================ - -type ignoreErrorsIntegration struct { - ignoreErrors []*regexp.Regexp -} - -func (iei *ignoreErrorsIntegration) Name() string { - return "IgnoreErrors" -} - -func (iei *ignoreErrorsIntegration) SetupOnce(client *Client) { - iei.ignoreErrors = transformStringsIntoRegexps(client.options.IgnoreErrors) - client.AddEventProcessor(iei.processor) -} - -func (iei *ignoreErrorsIntegration) processor(event *Event, _ *EventHint) *Event { - suspects := getIgnoreErrorsSuspects(event) - - for _, suspect := range suspects { - for _, pattern := range iei.ignoreErrors { - if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) { - Logger.Printf("Event dropped due to being matched by `IgnoreErrors` option."+ - "| Value matched: %s | Filter used: %s", suspect, pattern) - return nil - } - } - } - - return event -} - -func transformStringsIntoRegexps(strings []string) []*regexp.Regexp { - var exprs []*regexp.Regexp - - for _, s := range strings { - r, err := regexp.Compile(s) - if err == nil { - exprs = append(exprs, r) - } - } - - return exprs -} - -func getIgnoreErrorsSuspects(event *Event) []string { - suspects := []string{} - - if event.Message != "" { - suspects = append(suspects, event.Message) - } - - for _, ex := range event.Exception { - suspects = append(suspects, ex.Type, ex.Value) - } - - return suspects -} - -// ================================ -// Ignore Transactions Integration -// ================================ - -type ignoreTransactionsIntegration struct { - ignoreTransactions []*regexp.Regexp -} - -func (iei *ignoreTransactionsIntegration) Name() string { - return "IgnoreTransactions" -} - -func (iei *ignoreTransactionsIntegration) SetupOnce(client *Client) { - iei.ignoreTransactions = transformStringsIntoRegexps(client.options.IgnoreTransactions) - client.AddEventProcessor(iei.processor) -} - -func (iei *ignoreTransactionsIntegration) processor(event *Event, _ *EventHint) *Event { - suspect := event.Transaction - if suspect == "" { - return event - } - - for _, pattern := range iei.ignoreTransactions { - if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) { - Logger.Printf("Transaction dropped due to being matched by `IgnoreTransactions` option."+ - "| Value matched: %s | Filter used: %s", suspect, pattern) - return nil - } - } - - return event -} - -// ================================ -// Contextify Frames Integration -// ================================ - -type contextifyFramesIntegration struct { - sr sourceReader - contextLines int - cachedLocations sync.Map -} - -func (cfi *contextifyFramesIntegration) Name() string { - return "ContextifyFrames" -} - -func (cfi *contextifyFramesIntegration) SetupOnce(client *Client) { - cfi.sr = newSourceReader() - cfi.contextLines = 5 - - client.AddEventProcessor(cfi.processor) -} - -func (cfi *contextifyFramesIntegration) processor(event *Event, _ *EventHint) *Event { - // Range over all exceptions - for _, ex := range event.Exception { - // If it has no stacktrace, just bail out - if ex.Stacktrace == nil { - continue - } - - // If it does, it should have frames, so try to contextify them - ex.Stacktrace.Frames = cfi.contextify(ex.Stacktrace.Frames) - } - - // Range over all threads - for _, th := range event.Threads { - // If it has no stacktrace, just bail out - if th.Stacktrace == nil { - continue - } - - // If it does, it should have frames, so try to contextify them - th.Stacktrace.Frames = cfi.contextify(th.Stacktrace.Frames) - } - - return event -} - -func (cfi *contextifyFramesIntegration) contextify(frames []Frame) []Frame { - contextifiedFrames := make([]Frame, 0, len(frames)) - - for _, frame := range frames { - if !frame.InApp { - contextifiedFrames = append(contextifiedFrames, frame) - continue - } - - var path string - - if cachedPath, ok := cfi.cachedLocations.Load(frame.AbsPath); ok { - if p, ok := cachedPath.(string); ok { - path = p - } - } else { - // Optimize for happy path here - if fileExists(frame.AbsPath) { - path = frame.AbsPath - } else { - path = cfi.findNearbySourceCodeLocation(frame.AbsPath) - } - } - - if path == "" { - contextifiedFrames = append(contextifiedFrames, frame) - continue - } - - lines, contextLine := cfi.sr.readContextLines(path, frame.Lineno, cfi.contextLines) - contextifiedFrames = append(contextifiedFrames, cfi.addContextLinesToFrame(frame, lines, contextLine)) - } - - return contextifiedFrames -} - -func (cfi *contextifyFramesIntegration) findNearbySourceCodeLocation(originalPath string) string { - trimmedPath := strings.TrimPrefix(originalPath, "/") - components := strings.Split(trimmedPath, "/") - - for len(components) > 0 { - components = components[1:] - possibleLocation := strings.Join(components, "/") - - if fileExists(possibleLocation) { - cfi.cachedLocations.Store(originalPath, possibleLocation) - return possibleLocation - } - } - - cfi.cachedLocations.Store(originalPath, "") - return "" -} - -func (cfi *contextifyFramesIntegration) addContextLinesToFrame(frame Frame, lines [][]byte, contextLine int) Frame { - for i, line := range lines { - switch { - case i < contextLine: - frame.PreContext = append(frame.PreContext, string(line)) - case i == contextLine: - frame.ContextLine = string(line) - default: - frame.PostContext = append(frame.PostContext, string(line)) - } - } - return frame -} - -// ================================ -// Global Tags Integration -// ================================ - -const envTagsPrefix = "SENTRY_TAGS_" - -type globalTagsIntegration struct { - tags map[string]string - envTags map[string]string -} - -func (ti *globalTagsIntegration) Name() string { - return "GlobalTags" -} - -func (ti *globalTagsIntegration) SetupOnce(client *Client) { - ti.tags = make(map[string]string, len(client.options.Tags)) - for k, v := range client.options.Tags { - ti.tags[k] = v - } - - ti.envTags = loadEnvTags() - - client.AddEventProcessor(ti.processor) -} - -func (ti *globalTagsIntegration) processor(event *Event, _ *EventHint) *Event { - if len(ti.tags) == 0 && len(ti.envTags) == 0 { - return event - } - - if event.Tags == nil { - event.Tags = make(map[string]string, len(ti.tags)+len(ti.envTags)) - } - - for k, v := range ti.tags { - if _, ok := event.Tags[k]; !ok { - event.Tags[k] = v - } - } - - for k, v := range ti.envTags { - if _, ok := event.Tags[k]; !ok { - event.Tags[k] = v - } - } - - return event -} - -func loadEnvTags() map[string]string { - tags := map[string]string{} - for _, pair := range os.Environ() { - parts := strings.Split(pair, "=") - if !strings.HasPrefix(parts[0], envTagsPrefix) { - continue - } - tag := strings.TrimPrefix(parts[0], envTagsPrefix) - tags[tag] = parts[1] - } - return tags -} diff --git a/vendor/github.com/getsentry/sentry-go/interfaces.go b/vendor/github.com/getsentry/sentry-go/interfaces.go deleted file mode 100644 index c6461f1fe..000000000 --- a/vendor/github.com/getsentry/sentry-go/interfaces.go +++ /dev/null @@ -1,549 +0,0 @@ -package sentry - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "reflect" - "slices" - "strings" - "time" -) - -// eventType is the type of an error event. -const eventType = "event" - -// transactionType is the type of a transaction event. -const transactionType = "transaction" - -// checkInType is the type of a check in event. -const checkInType = "check_in" - -// Level marks the severity of the event. -type Level string - -// Describes the severity of the event. -const ( - LevelDebug Level = "debug" - LevelInfo Level = "info" - LevelWarning Level = "warning" - LevelError Level = "error" - LevelFatal Level = "fatal" -) - -// SdkInfo contains all metadata about about the SDK being used. -type SdkInfo struct { - Name string `json:"name,omitempty"` - Version string `json:"version,omitempty"` - Integrations []string `json:"integrations,omitempty"` - Packages []SdkPackage `json:"packages,omitempty"` -} - -// SdkPackage describes a package that was installed. -type SdkPackage struct { - Name string `json:"name,omitempty"` - Version string `json:"version,omitempty"` -} - -// TODO: This type could be more useful, as map of interface{} is too generic -// and requires a lot of type assertions in beforeBreadcrumb calls -// plus it could just be map[string]interface{} then. - -// BreadcrumbHint contains information that can be associated with a Breadcrumb. -type BreadcrumbHint map[string]interface{} - -// Breadcrumb specifies an application event that occurred before a Sentry event. -// An event may contain one or more breadcrumbs. -type Breadcrumb struct { - Type string `json:"type,omitempty"` - Category string `json:"category,omitempty"` - Message string `json:"message,omitempty"` - Data map[string]interface{} `json:"data,omitempty"` - Level Level `json:"level,omitempty"` - Timestamp time.Time `json:"timestamp"` -} - -// TODO: provide constants for known breadcrumb types. -// See https://develop.sentry.dev/sdk/event-payloads/breadcrumbs/#breadcrumb-types. - -// MarshalJSON converts the Breadcrumb struct to JSON. -func (b *Breadcrumb) MarshalJSON() ([]byte, error) { - // We want to omit time.Time zero values, otherwise the server will try to - // interpret dates too far in the past. However, encoding/json doesn't - // support the "omitempty" option for struct types. See - // https://golang.org/issues/11939. - // - // We overcome the limitation and achieve what we want by shadowing fields - // and a few type tricks. - - // breadcrumb aliases Breadcrumb to allow calling json.Marshal without an - // infinite loop. It preserves all fields while none of the attached - // methods. - type breadcrumb Breadcrumb - - if b.Timestamp.IsZero() { - return json.Marshal(struct { - // Embed all of the fields of Breadcrumb. - *breadcrumb - // Timestamp shadows the original Timestamp field and is meant to - // remain nil, triggering the omitempty behavior. - Timestamp json.RawMessage `json:"timestamp,omitempty"` - }{breadcrumb: (*breadcrumb)(b)}) - } - return json.Marshal((*breadcrumb)(b)) -} - -// Attachment allows associating files with your events to aid in investigation. -// An event may contain one or more attachments. -type Attachment struct { - Filename string - ContentType string - Payload []byte -} - -// User describes the user associated with an Event. If this is used, at least -// an ID or an IP address should be provided. -type User struct { - ID string `json:"id,omitempty"` - Email string `json:"email,omitempty"` - IPAddress string `json:"ip_address,omitempty"` - Username string `json:"username,omitempty"` - Name string `json:"name,omitempty"` - Data map[string]string `json:"data,omitempty"` -} - -func (u User) IsEmpty() bool { - if u.ID != "" { - return false - } - - if u.Email != "" { - return false - } - - if u.IPAddress != "" { - return false - } - - if u.Username != "" { - return false - } - - if u.Name != "" { - return false - } - - if len(u.Data) > 0 { - return false - } - - return true -} - -// Request contains information on a HTTP request related to the event. -type Request struct { - URL string `json:"url,omitempty"` - Method string `json:"method,omitempty"` - Data string `json:"data,omitempty"` - QueryString string `json:"query_string,omitempty"` - Cookies string `json:"cookies,omitempty"` - Headers map[string]string `json:"headers,omitempty"` - Env map[string]string `json:"env,omitempty"` -} - -var sensitiveHeaders = map[string]struct{}{ - "Authorization": {}, - "Proxy-Authorization": {}, - "Cookie": {}, - "X-Forwarded-For": {}, - "X-Real-Ip": {}, -} - -// NewRequest returns a new Sentry Request from the given http.Request. -// -// NewRequest avoids operations that depend on network access. In particular, it -// does not read r.Body. -func NewRequest(r *http.Request) *Request { - protocol := schemeHTTP - if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" { - protocol = schemeHTTPS - } - url := fmt.Sprintf("%s://%s%s", protocol, r.Host, r.URL.Path) - - var cookies string - var env map[string]string - headers := map[string]string{} - - if client := CurrentHub().Client(); client != nil && client.options.SendDefaultPII { - // We read only the first Cookie header because of the specification: - // https://tools.ietf.org/html/rfc6265#section-5.4 - // When the user agent generates an HTTP request, the user agent MUST NOT - // attach more than one Cookie header field. - cookies = r.Header.Get("Cookie") - - headers = make(map[string]string, len(r.Header)) - for k, v := range r.Header { - headers[k] = strings.Join(v, ",") - } - - if addr, port, err := net.SplitHostPort(r.RemoteAddr); err == nil { - env = map[string]string{"REMOTE_ADDR": addr, "REMOTE_PORT": port} - } - } else { - for k, v := range r.Header { - if _, ok := sensitiveHeaders[k]; !ok { - headers[k] = strings.Join(v, ",") - } - } - } - - headers["Host"] = r.Host - - return &Request{ - URL: url, - Method: r.Method, - QueryString: r.URL.RawQuery, - Cookies: cookies, - Headers: headers, - Env: env, - } -} - -// Mechanism is the mechanism by which an exception was generated and handled. -type Mechanism struct { - Type string `json:"type,omitempty"` - Description string `json:"description,omitempty"` - HelpLink string `json:"help_link,omitempty"` - Source string `json:"source,omitempty"` - Handled *bool `json:"handled,omitempty"` - ParentID *int `json:"parent_id,omitempty"` - ExceptionID int `json:"exception_id"` - IsExceptionGroup bool `json:"is_exception_group,omitempty"` - Data map[string]any `json:"data,omitempty"` -} - -// SetUnhandled indicates that the exception is an unhandled exception, i.e. -// from a panic. -func (m *Mechanism) SetUnhandled() { - m.Handled = Pointer(false) -} - -// Exception specifies an error that occurred. -type Exception struct { - Type string `json:"type,omitempty"` // used as the main issue title - Value string `json:"value,omitempty"` // used as the main issue subtitle - Module string `json:"module,omitempty"` - ThreadID uint64 `json:"thread_id,omitempty"` - Stacktrace *Stacktrace `json:"stacktrace,omitempty"` - Mechanism *Mechanism `json:"mechanism,omitempty"` -} - -// SDKMetaData is a struct to stash data which is needed at some point in the SDK's event processing pipeline -// but which shouldn't get send to Sentry. -type SDKMetaData struct { - dsc DynamicSamplingContext -} - -// Contains information about how the name of the transaction was determined. -type TransactionInfo struct { - Source TransactionSource `json:"source,omitempty"` -} - -// The DebugMeta interface is not used in Golang apps, but may be populated -// when proxying Events from other platforms, like iOS, Android, and the -// Web. (See: https://develop.sentry.dev/sdk/event-payloads/debugmeta/ ). -type DebugMeta struct { - SdkInfo *DebugMetaSdkInfo `json:"sdk_info,omitempty"` - Images []DebugMetaImage `json:"images,omitempty"` -} - -type DebugMetaSdkInfo struct { - SdkName string `json:"sdk_name,omitempty"` - VersionMajor int `json:"version_major,omitempty"` - VersionMinor int `json:"version_minor,omitempty"` - VersionPatchlevel int `json:"version_patchlevel,omitempty"` -} - -type DebugMetaImage struct { - Type string `json:"type,omitempty"` // all - ImageAddr string `json:"image_addr,omitempty"` // macho,elf,pe - ImageSize int `json:"image_size,omitempty"` // macho,elf,pe - DebugID string `json:"debug_id,omitempty"` // macho,elf,pe,wasm,sourcemap - DebugFile string `json:"debug_file,omitempty"` // macho,elf,pe,wasm - CodeID string `json:"code_id,omitempty"` // macho,elf,pe,wasm - CodeFile string `json:"code_file,omitempty"` // macho,elf,pe,wasm,sourcemap - ImageVmaddr string `json:"image_vmaddr,omitempty"` // macho,elf,pe - Arch string `json:"arch,omitempty"` // macho,elf,pe - UUID string `json:"uuid,omitempty"` // proguard -} - -// EventID is a hexadecimal string representing a unique uuid4 for an Event. -// An EventID must be 32 characters long, lowercase and not have any dashes. -type EventID string - -type Context = map[string]interface{} - -// Event is the fundamental data structure that is sent to Sentry. -type Event struct { - Breadcrumbs []*Breadcrumb `json:"breadcrumbs,omitempty"` - Contexts map[string]Context `json:"contexts,omitempty"` - Dist string `json:"dist,omitempty"` - Environment string `json:"environment,omitempty"` - EventID EventID `json:"event_id,omitempty"` - Extra map[string]interface{} `json:"extra,omitempty"` - Fingerprint []string `json:"fingerprint,omitempty"` - Level Level `json:"level,omitempty"` - Message string `json:"message,omitempty"` - Platform string `json:"platform,omitempty"` - Release string `json:"release,omitempty"` - Sdk SdkInfo `json:"sdk,omitempty"` - ServerName string `json:"server_name,omitempty"` - Threads []Thread `json:"threads,omitempty"` - Tags map[string]string `json:"tags,omitempty"` - Timestamp time.Time `json:"timestamp"` - Transaction string `json:"transaction,omitempty"` - User User `json:"user,omitempty"` - Logger string `json:"logger,omitempty"` - Modules map[string]string `json:"modules,omitempty"` - Request *Request `json:"request,omitempty"` - Exception []Exception `json:"exception,omitempty"` - DebugMeta *DebugMeta `json:"debug_meta,omitempty"` - Attachments []*Attachment `json:"-"` - - // The fields below are only relevant for transactions. - - Type string `json:"type,omitempty"` - StartTime time.Time `json:"start_timestamp"` - Spans []*Span `json:"spans,omitempty"` - TransactionInfo *TransactionInfo `json:"transaction_info,omitempty"` - - // The fields below are only relevant for crons/check ins - - CheckIn *CheckIn `json:"check_in,omitempty"` - MonitorConfig *MonitorConfig `json:"monitor_config,omitempty"` - - // The fields below are not part of the final JSON payload. - - sdkMetaData SDKMetaData -} - -// SetException appends the unwrapped errors to the event's exception list. -// -// maxErrorDepth is the maximum depth of the error chain we will look -// into while unwrapping the errors. If maxErrorDepth is -1, we will -// unwrap all errors in the chain. -func (e *Event) SetException(exception error, maxErrorDepth int) { - if exception == nil { - return - } - - err := exception - - for i := 0; err != nil && (i < maxErrorDepth || maxErrorDepth == -1); i++ { - // Add the current error to the exception slice with its details - e.Exception = append(e.Exception, Exception{ - Value: err.Error(), - Type: reflect.TypeOf(err).String(), - Stacktrace: ExtractStacktrace(err), - }) - - // Attempt to unwrap the error using the standard library's Unwrap method. - // If errors.Unwrap returns nil, it means either there is no error to unwrap, - // or the error does not implement the Unwrap method. - unwrappedErr := errors.Unwrap(err) - - if unwrappedErr != nil { - // The error was successfully unwrapped using the standard library's Unwrap method. - err = unwrappedErr - continue - } - - cause, ok := err.(interface{ Cause() error }) - if !ok { - // We cannot unwrap the error further. - break - } - - // The error implements the Cause method, indicating it may have been wrapped - // using the github.com/pkg/errors package. - err = cause.Cause() - } - - // Add a trace of the current stack to the most recent error in a chain if - // it doesn't have a stack trace yet. - // We only add to the most recent error to avoid duplication and because the - // current stack is most likely unrelated to errors deeper in the chain. - if e.Exception[0].Stacktrace == nil { - e.Exception[0].Stacktrace = NewStacktrace() - } - - if len(e.Exception) <= 1 { - return - } - - // event.Exception should be sorted such that the most recent error is last. - slices.Reverse(e.Exception) - - for i := range e.Exception { - e.Exception[i].Mechanism = &Mechanism{ - IsExceptionGroup: true, - ExceptionID: i, - Type: "generic", - } - if i == 0 { - continue - } - e.Exception[i].Mechanism.ParentID = Pointer(i - 1) - } -} - -// TODO: Event.Contexts map[string]interface{} => map[string]EventContext, -// to prevent accidentally storing T when we mean *T. -// For example, the TraceContext must be stored as *TraceContext to pick up the -// MarshalJSON method (and avoid copying). -// type EventContext interface{ EventContext() } - -// MarshalJSON converts the Event struct to JSON. -func (e *Event) MarshalJSON() ([]byte, error) { - // We want to omit time.Time zero values, otherwise the server will try to - // interpret dates too far in the past. However, encoding/json doesn't - // support the "omitempty" option for struct types. See - // https://golang.org/issues/11939. - // - // We overcome the limitation and achieve what we want by shadowing fields - // and a few type tricks. - if e.Type == transactionType { - return e.transactionMarshalJSON() - } - - if e.Type == checkInType { - return e.checkInMarshalJSON() - } - return e.defaultMarshalJSON() -} - -func (e *Event) defaultMarshalJSON() ([]byte, error) { - // event aliases Event to allow calling json.Marshal without an infinite - // loop. It preserves all fields while none of the attached methods. - type event Event - - // errorEvent is like Event with shadowed fields for customizing JSON - // marshaling. - type errorEvent struct { - *event - - // Timestamp shadows the original Timestamp field. It allows us to - // include the timestamp when non-zero and omit it otherwise. - Timestamp json.RawMessage `json:"timestamp,omitempty"` - - // The fields below are not part of error events and only make sense to - // be sent for transactions. They shadow the respective fields in Event - // and are meant to remain nil, triggering the omitempty behavior. - - Type json.RawMessage `json:"type,omitempty"` - StartTime json.RawMessage `json:"start_timestamp,omitempty"` - Spans json.RawMessage `json:"spans,omitempty"` - TransactionInfo json.RawMessage `json:"transaction_info,omitempty"` - } - - x := errorEvent{event: (*event)(e)} - if !e.Timestamp.IsZero() { - b, err := e.Timestamp.MarshalJSON() - if err != nil { - return nil, err - } - x.Timestamp = b - } - return json.Marshal(x) -} - -func (e *Event) transactionMarshalJSON() ([]byte, error) { - // event aliases Event to allow calling json.Marshal without an infinite - // loop. It preserves all fields while none of the attached methods. - type event Event - - // transactionEvent is like Event with shadowed fields for customizing JSON - // marshaling. - type transactionEvent struct { - *event - - // The fields below shadow the respective fields in Event. They allow us - // to include timestamps when non-zero and omit them otherwise. - - StartTime json.RawMessage `json:"start_timestamp,omitempty"` - Timestamp json.RawMessage `json:"timestamp,omitempty"` - } - - x := transactionEvent{event: (*event)(e)} - if !e.Timestamp.IsZero() { - b, err := e.Timestamp.MarshalJSON() - if err != nil { - return nil, err - } - x.Timestamp = b - } - if !e.StartTime.IsZero() { - b, err := e.StartTime.MarshalJSON() - if err != nil { - return nil, err - } - x.StartTime = b - } - return json.Marshal(x) -} - -func (e *Event) checkInMarshalJSON() ([]byte, error) { - checkIn := serializedCheckIn{ - CheckInID: string(e.CheckIn.ID), - MonitorSlug: e.CheckIn.MonitorSlug, - Status: e.CheckIn.Status, - Duration: e.CheckIn.Duration.Seconds(), - Release: e.Release, - Environment: e.Environment, - MonitorConfig: nil, - } - - if e.MonitorConfig != nil { - checkIn.MonitorConfig = &MonitorConfig{ - Schedule: e.MonitorConfig.Schedule, - CheckInMargin: e.MonitorConfig.CheckInMargin, - MaxRuntime: e.MonitorConfig.MaxRuntime, - Timezone: e.MonitorConfig.Timezone, - } - } - - return json.Marshal(checkIn) -} - -// NewEvent creates a new Event. -func NewEvent() *Event { - return &Event{ - Contexts: make(map[string]Context), - Extra: make(map[string]interface{}), - Tags: make(map[string]string), - Modules: make(map[string]string), - } -} - -// Thread specifies threads that were running at the time of an event. -type Thread struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Stacktrace *Stacktrace `json:"stacktrace,omitempty"` - Crashed bool `json:"crashed,omitempty"` - Current bool `json:"current,omitempty"` -} - -// EventHint contains information that can be associated with an Event. -type EventHint struct { - Data interface{} - EventID string - OriginalException error - RecoveredException interface{} - Context context.Context - Request *http.Request - Response *http.Response -} diff --git a/vendor/github.com/getsentry/sentry-go/internal/debug/transport.go b/vendor/github.com/getsentry/sentry-go/internal/debug/transport.go deleted file mode 100644 index 199c3a303..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/debug/transport.go +++ /dev/null @@ -1,79 +0,0 @@ -package debug - -import ( - "bytes" - "fmt" - "io" - "net/http" - "net/http/httptrace" - "net/http/httputil" -) - -// Transport implements http.RoundTripper and can be used to wrap other HTTP -// transports for debugging, normally http.DefaultTransport. -type Transport struct { - http.RoundTripper - Output io.Writer - // Dump controls whether to dump HTTP request and responses. - Dump bool - // Trace enables usage of net/http/httptrace. - Trace bool -} - -func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { - var buf bytes.Buffer - if t.Dump { - b, err := httputil.DumpRequestOut(req, true) - if err != nil { - panic(err) - } - _, err = buf.Write(ensureTrailingNewline(b)) - if err != nil { - panic(err) - } - } - if t.Trace { - trace := &httptrace.ClientTrace{ - DNSDone: func(di httptrace.DNSDoneInfo) { - fmt.Fprintf(&buf, "* DNS %v → %v\n", req.Host, di.Addrs) - }, - GotConn: func(ci httptrace.GotConnInfo) { - fmt.Fprintf(&buf, "* Connection local=%v remote=%v", ci.Conn.LocalAddr(), ci.Conn.RemoteAddr()) - if ci.Reused { - fmt.Fprint(&buf, " (reused)") - } - if ci.WasIdle { - fmt.Fprintf(&buf, " (idle %v)", ci.IdleTime) - } - fmt.Fprintln(&buf) - }, - } - req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) - } - resp, err := t.RoundTripper.RoundTrip(req) - if err != nil { - return nil, err - } - if t.Dump { - b, err := httputil.DumpResponse(resp, true) - if err != nil { - panic(err) - } - _, err = buf.Write(ensureTrailingNewline(b)) - if err != nil { - panic(err) - } - } - _, err = io.Copy(t.Output, &buf) - if err != nil { - panic(err) - } - return resp, nil -} - -func ensureTrailingNewline(b []byte) []byte { - if len(b) > 0 && b[len(b)-1] != '\n' { - b = append(b, '\n') - } - return b -} diff --git a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/README.md b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/README.md deleted file mode 100644 index 2718f314b..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Why do we have this "otel/baggage" folder? - -The root sentry-go SDK (namely, the Dynamic Sampling functionality) needs an implementation of the [baggage spec](https://www.w3.org/TR/baggage/). -For that reason, we've taken the existing baggage implementation from the [opentelemetry-go](https://github.com/open-telemetry/opentelemetry-go/) repository, and fixed a few things that in our opinion were violating the specification. - -These issues are: -1. Baggage string value `one%20two` should be properly parsed as "one two" -1. Baggage string value `one+two` should be parsed as "one+two" -1. Go string value "one two" should be encoded as `one%20two` (percent encoding), and NOT as `one+two` (URL query encoding). -1. Go string value "1=1" might be encoded as `1=1`, because the spec says: "Note, value MAY contain any number of the equal sign (=) characters. Parsers MUST NOT assume that the equal sign is only used to separate key and value.". `1%3D1` is also valid, but to simplify the implementation we're not doing it. - -Changes were made in this PR: https://github.com/getsentry/sentry-go/pull/568 diff --git a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/baggage.go b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/baggage.go deleted file mode 100644 index 180655506..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/baggage.go +++ /dev/null @@ -1,604 +0,0 @@ -// Adapted from https://github.com/open-telemetry/opentelemetry-go/blob/c21b6b6bb31a2f74edd06e262f1690f3f6ea3d5c/baggage/baggage.go -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 baggage - -import ( - "errors" - "fmt" - "net/url" - "regexp" - "strings" - "unicode/utf8" - - "github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage" -) - -const ( - maxMembers = 180 - maxBytesPerMembers = 4096 - maxBytesPerBaggageString = 8192 - - listDelimiter = "," - keyValueDelimiter = "=" - propertyDelimiter = ";" - - keyDef = `([\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5a\x5e-\x7a\x7c\x7e]+)` - valueDef = `([\x21\x23-\x2b\x2d-\x3a\x3c-\x5B\x5D-\x7e]*)` - keyValueDef = `\s*` + keyDef + `\s*` + keyValueDelimiter + `\s*` + valueDef + `\s*` -) - -var ( - keyRe = regexp.MustCompile(`^` + keyDef + `$`) - valueRe = regexp.MustCompile(`^` + valueDef + `$`) - propertyRe = regexp.MustCompile(`^(?:\s*` + keyDef + `\s*|` + keyValueDef + `)$`) -) - -var ( - errInvalidKey = errors.New("invalid key") - errInvalidValue = errors.New("invalid value") - errInvalidProperty = errors.New("invalid baggage list-member property") - errInvalidMember = errors.New("invalid baggage list-member") - errMemberNumber = errors.New("too many list-members in baggage-string") - errMemberBytes = errors.New("list-member too large") - errBaggageBytes = errors.New("baggage-string too large") -) - -// Property is an additional metadata entry for a baggage list-member. -type Property struct { - key, value string - - // hasValue indicates if a zero-value value means the property does not - // have a value or if it was the zero-value. - hasValue bool - - // hasData indicates whether the created property contains data or not. - // Properties that do not contain data are invalid with no other check - // required. - hasData bool -} - -// NewKeyProperty returns a new Property for key. -// -// If key is invalid, an error will be returned. -func NewKeyProperty(key string) (Property, error) { - if !keyRe.MatchString(key) { - return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key) - } - - p := Property{key: key, hasData: true} - return p, nil -} - -// NewKeyValueProperty returns a new Property for key with value. -// -// If key or value are invalid, an error will be returned. -func NewKeyValueProperty(key, value string) (Property, error) { - if !keyRe.MatchString(key) { - return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key) - } - if !valueRe.MatchString(value) { - return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidValue, value) - } - - p := Property{ - key: key, - value: value, - hasValue: true, - hasData: true, - } - return p, nil -} - -func newInvalidProperty() Property { - return Property{} -} - -// parseProperty attempts to decode a Property from the passed string. It -// returns an error if the input is invalid according to the W3C Baggage -// specification. -func parseProperty(property string) (Property, error) { - if property == "" { - return newInvalidProperty(), nil - } - - match := propertyRe.FindStringSubmatch(property) - if len(match) != 4 { - return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidProperty, property) - } - - p := Property{hasData: true} - if match[1] != "" { - p.key = match[1] - } else { - p.key = match[2] - p.value = match[3] - p.hasValue = true - } - - return p, nil -} - -// validate ensures p conforms to the W3C Baggage specification, returning an -// error otherwise. -func (p Property) validate() error { - errFunc := func(err error) error { - return fmt.Errorf("invalid property: %w", err) - } - - if !p.hasData { - return errFunc(fmt.Errorf("%w: %q", errInvalidProperty, p)) - } - - if !keyRe.MatchString(p.key) { - return errFunc(fmt.Errorf("%w: %q", errInvalidKey, p.key)) - } - if p.hasValue && !valueRe.MatchString(p.value) { - return errFunc(fmt.Errorf("%w: %q", errInvalidValue, p.value)) - } - if !p.hasValue && p.value != "" { - return errFunc(errors.New("inconsistent value")) - } - return nil -} - -// Key returns the Property key. -func (p Property) Key() string { - return p.key -} - -// Value returns the Property value. Additionally, a boolean value is returned -// indicating if the returned value is the empty if the Property has a value -// that is empty or if the value is not set. -func (p Property) Value() (string, bool) { - return p.value, p.hasValue -} - -// String encodes Property into a string compliant with the W3C Baggage -// specification. -func (p Property) String() string { - if p.hasValue { - return fmt.Sprintf("%s%s%v", p.key, keyValueDelimiter, p.value) - } - return p.key -} - -type properties []Property - -func fromInternalProperties(iProps []baggage.Property) properties { - if len(iProps) == 0 { - return nil - } - - props := make(properties, len(iProps)) - for i, p := range iProps { - props[i] = Property{ - key: p.Key, - value: p.Value, - hasValue: p.HasValue, - } - } - return props -} - -func (p properties) asInternal() []baggage.Property { - if len(p) == 0 { - return nil - } - - iProps := make([]baggage.Property, len(p)) - for i, prop := range p { - iProps[i] = baggage.Property{ - Key: prop.key, - Value: prop.value, - HasValue: prop.hasValue, - } - } - return iProps -} - -func (p properties) Copy() properties { - if len(p) == 0 { - return nil - } - - props := make(properties, len(p)) - copy(props, p) - return props -} - -// validate ensures each Property in p conforms to the W3C Baggage -// specification, returning an error otherwise. -func (p properties) validate() error { - for _, prop := range p { - if err := prop.validate(); err != nil { - return err - } - } - return nil -} - -// String encodes properties into a string compliant with the W3C Baggage -// specification. -func (p properties) String() string { - props := make([]string, len(p)) - for i, prop := range p { - props[i] = prop.String() - } - return strings.Join(props, propertyDelimiter) -} - -// Member is a list-member of a baggage-string as defined by the W3C Baggage -// specification. -type Member struct { - key, value string - properties properties - - // hasData indicates whether the created property contains data or not. - // Properties that do not contain data are invalid with no other check - // required. - hasData bool -} - -// NewMember returns a new Member from the passed arguments. The key will be -// used directly while the value will be url decoded after validation. An error -// is returned if the created Member would be invalid according to the W3C -// Baggage specification. -func NewMember(key, value string, props ...Property) (Member, error) { - m := Member{ - key: key, - value: value, - properties: properties(props).Copy(), - hasData: true, - } - if err := m.validate(); err != nil { - return newInvalidMember(), err - } - //// NOTE(anton): I don't think we need to unescape here - // decodedValue, err := url.PathUnescape(value) - // if err != nil { - // return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value) - // } - // m.value = decodedValue - return m, nil -} - -func newInvalidMember() Member { - return Member{} -} - -// parseMember attempts to decode a Member from the passed string. It returns -// an error if the input is invalid according to the W3C Baggage -// specification. -func parseMember(member string) (Member, error) { - if n := len(member); n > maxBytesPerMembers { - return newInvalidMember(), fmt.Errorf("%w: %d", errMemberBytes, n) - } - - var ( - key, value string - props properties - ) - - parts := strings.SplitN(member, propertyDelimiter, 2) - switch len(parts) { - case 2: - // Parse the member properties. - for _, pStr := range strings.Split(parts[1], propertyDelimiter) { - p, err := parseProperty(pStr) - if err != nil { - return newInvalidMember(), err - } - props = append(props, p) - } - fallthrough - case 1: - // Parse the member key/value pair. - - // Take into account a value can contain equal signs (=). - kv := strings.SplitN(parts[0], keyValueDelimiter, 2) - if len(kv) != 2 { - return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidMember, member) - } - // "Leading and trailing whitespaces are allowed but MUST be trimmed - // when converting the header into a data structure." - key = strings.TrimSpace(kv[0]) - value = strings.TrimSpace(kv[1]) - var err error - if !keyRe.MatchString(key) { - return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidKey, key) - } - if !valueRe.MatchString(value) { - return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value) - } - decodedValue, err := url.PathUnescape(value) - if err != nil { - return newInvalidMember(), fmt.Errorf("%w: %q", err, value) - } - value = decodedValue - default: - // This should never happen unless a developer has changed the string - // splitting somehow. Panic instead of failing silently and allowing - // the bug to slip past the CI checks. - panic("failed to parse baggage member") - } - - return Member{key: key, value: value, properties: props, hasData: true}, nil -} - -// validate ensures m conforms to the W3C Baggage specification. -// A key is just an ASCII string, but a value must be URL encoded UTF-8, -// returning an error otherwise. -func (m Member) validate() error { - if !m.hasData { - return fmt.Errorf("%w: %q", errInvalidMember, m) - } - - if !keyRe.MatchString(m.key) { - return fmt.Errorf("%w: %q", errInvalidKey, m.key) - } - //// NOTE(anton): IMO it's too early to validate the value here. - // if !valueRe.MatchString(m.value) { - // return fmt.Errorf("%w: %q", errInvalidValue, m.value) - // } - return m.properties.validate() -} - -// Key returns the Member key. -func (m Member) Key() string { return m.key } - -// Value returns the Member value. -func (m Member) Value() string { return m.value } - -// Properties returns a copy of the Member properties. -func (m Member) Properties() []Property { return m.properties.Copy() } - -// String encodes Member into a string compliant with the W3C Baggage -// specification. -func (m Member) String() string { - // A key is just an ASCII string, but a value is URL encoded UTF-8. - s := fmt.Sprintf("%s%s%s", m.key, keyValueDelimiter, percentEncodeValue(m.value)) - if len(m.properties) > 0 { - s = fmt.Sprintf("%s%s%s", s, propertyDelimiter, m.properties.String()) - } - return s -} - -// percentEncodeValue encodes the baggage value, using percent-encoding for -// disallowed octets. -func percentEncodeValue(s string) string { - const upperhex = "0123456789ABCDEF" - var sb strings.Builder - - for byteIndex, width := 0, 0; byteIndex < len(s); byteIndex += width { - runeValue, w := utf8.DecodeRuneInString(s[byteIndex:]) - width = w - char := string(runeValue) - if valueRe.MatchString(char) && char != "%" { - // The character is returned as is, no need to percent-encode - sb.WriteString(char) - } else { - // We need to percent-encode each byte of the multi-octet character - for j := 0; j < width; j++ { - b := s[byteIndex+j] - sb.WriteByte('%') - // Bitwise operations are inspired by "net/url" - sb.WriteByte(upperhex[b>>4]) - sb.WriteByte(upperhex[b&15]) - } - } - } - return sb.String() -} - -// Baggage is a list of baggage members representing the baggage-string as -// defined by the W3C Baggage specification. -type Baggage struct { //nolint:golint - list baggage.List -} - -// New returns a new valid Baggage. It returns an error if it results in a -// Baggage exceeding limits set in that specification. -// -// It expects all the provided members to have already been validated. -func New(members ...Member) (Baggage, error) { - if len(members) == 0 { - return Baggage{}, nil - } - - b := make(baggage.List) - for _, m := range members { - if !m.hasData { - return Baggage{}, errInvalidMember - } - - // OpenTelemetry resolves duplicates by last-one-wins. - b[m.key] = baggage.Item{ - Value: m.value, - Properties: m.properties.asInternal(), - } - } - - // Check member numbers after deduplication. - if len(b) > maxMembers { - return Baggage{}, errMemberNumber - } - - bag := Baggage{b} - if n := len(bag.String()); n > maxBytesPerBaggageString { - return Baggage{}, fmt.Errorf("%w: %d", errBaggageBytes, n) - } - - return bag, nil -} - -// Parse attempts to decode a baggage-string from the passed string. It -// returns an error if the input is invalid according to the W3C Baggage -// specification. -// -// If there are duplicate list-members contained in baggage, the last one -// defined (reading left-to-right) will be the only one kept. This diverges -// from the W3C Baggage specification which allows duplicate list-members, but -// conforms to the OpenTelemetry Baggage specification. -func Parse(bStr string) (Baggage, error) { - if bStr == "" { - return Baggage{}, nil - } - - if n := len(bStr); n > maxBytesPerBaggageString { - return Baggage{}, fmt.Errorf("%w: %d", errBaggageBytes, n) - } - - b := make(baggage.List) - for _, memberStr := range strings.Split(bStr, listDelimiter) { - m, err := parseMember(memberStr) - if err != nil { - return Baggage{}, err - } - // OpenTelemetry resolves duplicates by last-one-wins. - b[m.key] = baggage.Item{ - Value: m.value, - Properties: m.properties.asInternal(), - } - } - - // OpenTelemetry does not allow for duplicate list-members, but the W3C - // specification does. Now that we have deduplicated, ensure the baggage - // does not exceed list-member limits. - if len(b) > maxMembers { - return Baggage{}, errMemberNumber - } - - return Baggage{b}, nil -} - -// Member returns the baggage list-member identified by key. -// -// If there is no list-member matching the passed key the returned Member will -// be a zero-value Member. -// The returned member is not validated, as we assume the validation happened -// when it was added to the Baggage. -func (b Baggage) Member(key string) Member { - v, ok := b.list[key] - if !ok { - // We do not need to worry about distinguishing between the situation - // where a zero-valued Member is included in the Baggage because a - // zero-valued Member is invalid according to the W3C Baggage - // specification (it has an empty key). - return newInvalidMember() - } - - return Member{ - key: key, - value: v.Value, - properties: fromInternalProperties(v.Properties), - hasData: true, - } -} - -// Members returns all the baggage list-members. -// The order of the returned list-members does not have significance. -// -// The returned members are not validated, as we assume the validation happened -// when they were added to the Baggage. -func (b Baggage) Members() []Member { - if len(b.list) == 0 { - return nil - } - - members := make([]Member, 0, len(b.list)) - for k, v := range b.list { - members = append(members, Member{ - key: k, - value: v.Value, - properties: fromInternalProperties(v.Properties), - hasData: true, - }) - } - return members -} - -// SetMember returns a copy the Baggage with the member included. If the -// baggage contains a Member with the same key the existing Member is -// replaced. -// -// If member is invalid according to the W3C Baggage specification, an error -// is returned with the original Baggage. -func (b Baggage) SetMember(member Member) (Baggage, error) { - if !member.hasData { - return b, errInvalidMember - } - - n := len(b.list) - if _, ok := b.list[member.key]; !ok { - n++ - } - list := make(baggage.List, n) - - for k, v := range b.list { - // Do not copy if we are just going to overwrite. - if k == member.key { - continue - } - list[k] = v - } - - list[member.key] = baggage.Item{ - Value: member.value, - Properties: member.properties.asInternal(), - } - - return Baggage{list: list}, nil -} - -// DeleteMember returns a copy of the Baggage with the list-member identified -// by key removed. -func (b Baggage) DeleteMember(key string) Baggage { - n := len(b.list) - if _, ok := b.list[key]; ok { - n-- - } - list := make(baggage.List, n) - - for k, v := range b.list { - if k == key { - continue - } - list[k] = v - } - - return Baggage{list: list} -} - -// Len returns the number of list-members in the Baggage. -func (b Baggage) Len() int { - return len(b.list) -} - -// String encodes Baggage into a string compliant with the W3C Baggage -// specification. The returned string will be invalid if the Baggage contains -// any invalid list-members. -func (b Baggage) String() string { - members := make([]string, 0, len(b.list)) - for k, v := range b.list { - members = append(members, Member{ - key: k, - value: v.Value, - properties: fromInternalProperties(v.Properties), - }.String()) - } - return strings.Join(members, listDelimiter) -} diff --git a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage/baggage.go b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage/baggage.go deleted file mode 100644 index ea99ccbff..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage/baggage.go +++ /dev/null @@ -1,45 +0,0 @@ -// Adapted from https://github.com/open-telemetry/opentelemetry-go/blob/c21b6b6bb31a2f74edd06e262f1690f3f6ea3d5c/internal/baggage/baggage.go -// -// Copyright The OpenTelemetry Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 baggage provides base types and functionality to store and retrieve -baggage in Go context. This package exists because the OpenTracing bridge to -OpenTelemetry needs to synchronize state whenever baggage for a context is -modified and that context contains an OpenTracing span. If it were not for -this need this package would not need to exist and the -`go.opentelemetry.io/otel/baggage` package would be the singular place where -W3C baggage is handled. -*/ -package baggage - -// List is the collection of baggage members. The W3C allows for duplicates, -// but OpenTelemetry does not, therefore, this is represented as a map. -type List map[string]Item - -// Item is the value and metadata properties part of a list-member. -type Item struct { - Value string - Properties []Property -} - -// Property is a metadata entry for a list-member. -type Property struct { - Key, Value string - - // HasValue indicates if a zero-value value means the property does not - // have a value or if it was the zero-value. - HasValue bool -} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go deleted file mode 100644 index 2db76d2bf..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go +++ /dev/null @@ -1,45 +0,0 @@ -package ratelimit - -import ( - "strings" - - "golang.org/x/text/cases" - "golang.org/x/text/language" -) - -// Reference: -// https://github.com/getsentry/relay/blob/0424a2e017d193a93918053c90cdae9472d164bf/relay-common/src/constants.rs#L116-L127 - -// Category classifies supported payload types that can be ingested by Sentry -// and, therefore, rate limited. -type Category string - -// Known rate limit categories. As a special case, the CategoryAll applies to -// all known payload types. -const ( - CategoryAll Category = "" - CategoryError Category = "error" - CategoryTransaction Category = "transaction" -) - -// knownCategories is the set of currently known categories. Other categories -// are ignored for the purpose of rate-limiting. -var knownCategories = map[Category]struct{}{ - CategoryAll: {}, - CategoryError: {}, - CategoryTransaction: {}, -} - -// String returns the category formatted for debugging. -func (c Category) String() string { - if c == "" { - return "CategoryAll" - } - - caser := cases.Title(language.English) - rv := "Category" - for _, w := range strings.Fields(string(c)) { - rv += caser.String(w) - } - return rv -} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/deadline.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/deadline.go deleted file mode 100644 index c00258335..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/deadline.go +++ /dev/null @@ -1,22 +0,0 @@ -package ratelimit - -import "time" - -// A Deadline is a time instant when a rate limit expires. -type Deadline time.Time - -// After reports whether the deadline d is after other. -func (d Deadline) After(other Deadline) bool { - return time.Time(d).After(time.Time(other)) -} - -// Equal reports whether d and e represent the same deadline. -func (d Deadline) Equal(e Deadline) bool { - return time.Time(d).Equal(time.Time(e)) -} - -// String returns the deadline formatted for debugging. -func (d Deadline) String() string { - // Like time.Time.String, but without the monotonic clock reading. - return time.Time(d).Round(0).String() -} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/doc.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/doc.go deleted file mode 100644 index 80b9fdda2..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package ratelimit provides tools to work with rate limits imposed by Sentry's -// data ingestion pipeline. -package ratelimit diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/map.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/map.go deleted file mode 100644 index e590430ec..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/map.go +++ /dev/null @@ -1,64 +0,0 @@ -package ratelimit - -import ( - "net/http" - "time" -) - -// Map maps categories to rate limit deadlines. -// -// A rate limit is in effect for a given category if either the category's -// deadline or the deadline for the special CategoryAll has not yet expired. -// -// Use IsRateLimited to check whether a category is rate-limited. -type Map map[Category]Deadline - -// IsRateLimited returns true if the category is currently rate limited. -func (m Map) IsRateLimited(c Category) bool { - return m.isRateLimited(c, time.Now()) -} - -func (m Map) isRateLimited(c Category, now time.Time) bool { - return m.Deadline(c).After(Deadline(now)) -} - -// Deadline returns the deadline when the rate limit for the given category or -// the special CategoryAll expire, whichever is furthest into the future. -func (m Map) Deadline(c Category) Deadline { - categoryDeadline := m[c] - allDeadline := m[CategoryAll] - if categoryDeadline.After(allDeadline) { - return categoryDeadline - } - return allDeadline -} - -// Merge merges the other map into m. -// -// If a category appears in both maps, the deadline that is furthest into the -// future is preserved. -func (m Map) Merge(other Map) { - for c, d := range other { - if d.After(m[c]) { - m[c] = d - } - } -} - -// FromResponse returns a rate limit map from an HTTP response. -func FromResponse(r *http.Response) Map { - return fromResponse(r, time.Now()) -} - -func fromResponse(r *http.Response, now time.Time) Map { - s := r.Header.Get("X-Sentry-Rate-Limits") - if s != "" { - return parseXSentryRateLimits(s, now) - } - if r.StatusCode == http.StatusTooManyRequests { - s := r.Header.Get("Retry-After") - deadline, _ := parseRetryAfter(s, now) - return Map{CategoryAll: deadline} - } - return Map{} -} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/rate_limits.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/rate_limits.go deleted file mode 100644 index 579297e42..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/rate_limits.go +++ /dev/null @@ -1,76 +0,0 @@ -package ratelimit - -import ( - "errors" - "math" - "strconv" - "strings" - "time" -) - -var errInvalidXSRLRetryAfter = errors.New("invalid retry-after value") - -// parseXSentryRateLimits returns a RateLimits map by parsing an input string in -// the format of the X-Sentry-Rate-Limits header. -// -// Example -// -// X-Sentry-Rate-Limits: 60:transaction, 2700:default;error;security -// -// This will rate limit transactions for the next 60 seconds and errors for the -// next 2700 seconds. -// -// Limits for unknown categories are ignored. -func parseXSentryRateLimits(s string, now time.Time) Map { - // https://github.com/getsentry/relay/blob/0424a2e017d193a93918053c90cdae9472d164bf/relay-server/src/utils/rate_limits.rs#L44-L82 - m := make(Map, len(knownCategories)) - for _, limit := range strings.Split(s, ",") { - limit = strings.TrimSpace(limit) - if limit == "" { - continue - } - components := strings.Split(limit, ":") - if len(components) == 0 { - continue - } - retryAfter, err := parseXSRLRetryAfter(strings.TrimSpace(components[0]), now) - if err != nil { - continue - } - categories := "" - if len(components) > 1 { - categories = components[1] - } - for _, category := range strings.Split(categories, ";") { - c := Category(strings.ToLower(strings.TrimSpace(category))) - if _, ok := knownCategories[c]; !ok { - // skip unknown categories, keep m small - continue - } - // always keep the deadline furthest into the future - if retryAfter.After(m[c]) { - m[c] = retryAfter - } - } - } - return m -} - -// parseXSRLRetryAfter parses a string into a retry-after rate limit deadline. -// -// Valid input is a number, possibly signed and possibly floating-point, -// indicating the number of seconds to wait before sending another request. -// Negative values are treated as zero. Fractional values are rounded to the -// next integer. -func parseXSRLRetryAfter(s string, now time.Time) (Deadline, error) { - // https://github.com/getsentry/relay/blob/0424a2e017d193a93918053c90cdae9472d164bf/relay-quotas/src/rate_limit.rs#L88-L96 - f, err := strconv.ParseFloat(s, 64) - if err != nil { - return Deadline{}, errInvalidXSRLRetryAfter - } - d := time.Duration(math.Ceil(math.Max(f, 0.0))) * time.Second - if d < 0 { - d = 0 - } - return Deadline(now.Add(d)), nil -} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/retry_after.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/retry_after.go deleted file mode 100644 index 576e29dcd..000000000 --- a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/retry_after.go +++ /dev/null @@ -1,40 +0,0 @@ -package ratelimit - -import ( - "errors" - "strconv" - "time" -) - -const defaultRetryAfter = 1 * time.Minute - -var errInvalidRetryAfter = errors.New("invalid input") - -// parseRetryAfter parses a string s as in the standard Retry-After HTTP header -// and returns a deadline until when requests are rate limited and therefore new -// requests should not be sent. The input may be either a date or a non-negative -// integer number of seconds. -// -// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After -// -// parseRetryAfter always returns a usable deadline, even in case of an error. -// -// This is the original rate limiting mechanism used by Sentry, superseeded by -// the X-Sentry-Rate-Limits response header. -func parseRetryAfter(s string, now time.Time) (Deadline, error) { - if s == "" { - goto invalid - } - if n, err := strconv.Atoi(s); err == nil { - if n < 0 { - goto invalid - } - d := time.Duration(n) * time.Second - return Deadline(now.Add(d)), nil - } - if date, err := time.Parse(time.RFC1123, s); err == nil { - return Deadline(date), nil - } -invalid: - return Deadline(now.Add(defaultRetryAfter)), errInvalidRetryAfter -} diff --git a/vendor/github.com/getsentry/sentry-go/logrus/LICENSE b/vendor/github.com/getsentry/sentry-go/logrus/LICENSE deleted file mode 100644 index b1b358e41..000000000 --- a/vendor/github.com/getsentry/sentry-go/logrus/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Functional Software, Inc. dba Sentry - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/getsentry/sentry-go/logrus/README.md b/vendor/github.com/getsentry/sentry-go/logrus/README.md deleted file mode 100644 index b4444530d..000000000 --- a/vendor/github.com/getsentry/sentry-go/logrus/README.md +++ /dev/null @@ -1,91 +0,0 @@ -

- - - -
-

- -# Official Sentry Logrus Hook for Sentry-go SDK - -**Go.dev Documentation:** https://pkg.go.dev/github.com/getsentry/sentry-go/logrus -**Example Usage:** https://github.com/getsentry/sentry-go/tree/master/_examples/logrus - -## Installation - -```sh -go get github.com/getsentry/sentry-go/logrus -``` - -## Usage - -```go -import ( - "fmt" - "os" - "time" - - "github.com/sirupsen/logrus" - "github.com/getsentry/sentry-go" - sentrylogrus "github.com/getsentry/sentry-go/logrus" -) - -func main() { - // Initialize Logrus - logger := logrus.New() - logger.Level = logrus.DebugLevel - logger.Out = os.Stderr - - // Define log levels to send to Sentry - sentryLevels := []logrus.Level{logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel} - - // Initialize Sentry - sentryHook, err := sentrylogrus.New(sentryLevels, sentry.ClientOptions{ - Dsn: "your-public-dsn", - BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event { - fmt.Println(event) // Optional debugging - return event - }, - Debug: true, - }) - if err != nil { - panic(err) - } - defer sentryHook.Flush(5 * time.Second) - logger.AddHook(sentryHook) - - // Example logging - logger.WithField("user", "test-user").Error("An error occurred") - - // Ensure all events are flushed before exit - logrus.RegisterExitHandler(func() { sentryHook.Flush(5 * time.Second) }) -} -``` - -## Configuration - -The `sentrylogrus` package accepts an array of `logrus.Level` and a struct of `sentry.ClientOptions` that allows you to configure how the hook will behave. -The `logrus.Level` array defines which log levels should be sent to Sentry. - -In addition, the Hook returned by `sentrylogrus.New` can be configured with the following options: - -- Fallback Functionality: Configure a fallback for handling errors during log transmission. - -```go -sentryHook.Fallback = func(entry *logrus.Entry, err error) { - // Handle error -} -``` - -- Setting default tags for all events sent to Sentry - -```go -sentryHook.AddTags(map[string]string{ - "key": "value", -}) -``` -- - -## Notes - -- Always call Flush to ensure all events are sent to Sentry before program termination - diff --git a/vendor/github.com/getsentry/sentry-go/logrus/logrusentry.go b/vendor/github.com/getsentry/sentry-go/logrus/logrusentry.go deleted file mode 100644 index e6739950b..000000000 --- a/vendor/github.com/getsentry/sentry-go/logrus/logrusentry.go +++ /dev/null @@ -1,217 +0,0 @@ -// Package sentrylogrus provides a simple Logrus hook for Sentry. -package sentrylogrus - -import ( - "errors" - "net/http" - "time" - - "github.com/sirupsen/logrus" - - sentry "github.com/getsentry/sentry-go" -) - -const ( - // sdkIdentifier is the identifier of the Logrus SDK. - sdkIdentifier = "sentry.go.logrus" - - // the name of the logger - name = "logrus" -) - -// These default log field keys are used to pass specific metadata in a way that -// Sentry understands. If they are found in the log fields, and the value is of -// the expected datatype, it will be converted from a generic field, into Sentry -// metadata. -// -// These keys may be overridden by calling SetKey on the hook object. -const ( - // FieldRequest holds an *http.Request. - FieldRequest = "request" - // FieldUser holds a User or *User value. - FieldUser = "user" - // FieldTransaction holds a transaction ID as a string. - FieldTransaction = "transaction" - // FieldFingerprint holds a string slice ([]string), used to dictate the - // grouping of this event. - FieldFingerprint = "fingerprint" - - // These fields are simply omitted, as they are duplicated by the Sentry SDK. - FieldGoVersion = "go_version" - FieldMaxProcs = "go_maxprocs" -) - -// Hook is the logrus hook for Sentry. -// -// It is not safe to configure the hook while logging is happening. Please -// perform all configuration before using it. -type Hook struct { - hubProvider func() *sentry.Hub - fallback FallbackFunc - keys map[string]string - levels []logrus.Level -} - -var _ logrus.Hook = &Hook{} - -// New initializes a new Logrus hook which sends logs to a new Sentry client -// configured according to opts. -func New(levels []logrus.Level, opts sentry.ClientOptions) (*Hook, error) { - client, err := sentry.NewClient(opts) - if err != nil { - return nil, err - } - - client.SetSDKIdentifier(sdkIdentifier) - - return NewFromClient(levels, client), nil -} - -// NewFromClient initializes a new Logrus hook which sends logs to the provided -// sentry client. -func NewFromClient(levels []logrus.Level, client *sentry.Client) *Hook { - defaultHub := sentry.NewHub(client, sentry.NewScope()) - return &Hook{ - levels: levels, - hubProvider: func() *sentry.Hub { - // Default to using the same hub if no specific provider is set - return defaultHub - }, - keys: make(map[string]string), - } -} - -// SetHubProvider sets a function to provide a hub for each log entry. -// This can be used to ensure separate hubs per goroutine if needed. -func (h *Hook) SetHubProvider(provider func() *sentry.Hub) { - h.hubProvider = provider -} - -// AddTags adds tags to the hook's scope. -func (h *Hook) AddTags(tags map[string]string) { - h.hubProvider().Scope().SetTags(tags) -} - -// A FallbackFunc can be used to attempt to handle any errors in logging, before -// resorting to Logrus's standard error reporting. -type FallbackFunc func(*logrus.Entry) error - -// SetFallback sets a fallback function, which will be called in case logging to -// sentry fails. In case of a logging failure in the Fire() method, the -// fallback function is called with the original logrus entry. If the -// fallback function returns nil, the error is considered handled. If it returns -// an error, that error is passed along to logrus as the return value from the -// Fire() call. If no fallback function is defined, a default error message is -// returned to Logrus in case of failure to send to Sentry. -func (h *Hook) SetFallback(fb FallbackFunc) { - h.fallback = fb -} - -// SetKey sets an alternate field key. Use this if the default values conflict -// with other loggers, for instance. You may pass "" for new, to unset an -// existing alternate. -func (h *Hook) SetKey(oldKey, newKey string) { - if oldKey == "" { - return - } - if newKey == "" { - delete(h.keys, oldKey) - return - } - delete(h.keys, newKey) - h.keys[oldKey] = newKey -} - -func (h *Hook) key(key string) string { - if val := h.keys[key]; val != "" { - return val - } - return key -} - -// Levels returns the list of logging levels that will be sent to -// Sentry. -func (h *Hook) Levels() []logrus.Level { - return h.levels -} - -// Fire sends entry to Sentry. -func (h *Hook) Fire(entry *logrus.Entry) error { - hub := h.hubProvider() // Use the hub provided by the HubProvider - event := h.entryToEvent(entry) - if id := hub.CaptureEvent(event); id == nil { - if h.fallback != nil { - return h.fallback(entry) - } - return errors.New("failed to send to sentry") - } - return nil -} - -var levelMap = map[logrus.Level]sentry.Level{ - logrus.TraceLevel: sentry.LevelDebug, - logrus.DebugLevel: sentry.LevelDebug, - logrus.InfoLevel: sentry.LevelInfo, - logrus.WarnLevel: sentry.LevelWarning, - logrus.ErrorLevel: sentry.LevelError, - logrus.FatalLevel: sentry.LevelFatal, - logrus.PanicLevel: sentry.LevelFatal, -} - -func (h *Hook) entryToEvent(l *logrus.Entry) *sentry.Event { - data := make(logrus.Fields, len(l.Data)) - for k, v := range l.Data { - data[k] = v - } - s := &sentry.Event{ - Level: levelMap[l.Level], - Extra: data, - Message: l.Message, - Timestamp: l.Time, - Logger: name, - } - - key := h.key(FieldRequest) - if req, ok := s.Extra[key].(*http.Request); ok { - delete(s.Extra, key) - s.Request = sentry.NewRequest(req) - } - - if err, ok := s.Extra[logrus.ErrorKey].(error); ok { - delete(s.Extra, logrus.ErrorKey) - s.SetException(err, -1) - } - - key = h.key(FieldUser) - switch user := s.Extra[key].(type) { - case sentry.User: - delete(s.Extra, key) - s.User = user - case *sentry.User: - delete(s.Extra, key) - s.User = *user - } - - key = h.key(FieldTransaction) - if txn, ok := s.Extra[key].(string); ok { - delete(s.Extra, key) - s.Transaction = txn - } - - key = h.key(FieldFingerprint) - if fp, ok := s.Extra[key].([]string); ok { - delete(s.Extra, key) - s.Fingerprint = fp - } - - delete(s.Extra, FieldGoVersion) - delete(s.Extra, FieldMaxProcs) - return s -} - -// Flush waits until the underlying Sentry transport sends any buffered events, -// blocking for at most the given timeout. It returns false if the timeout was -// reached, in which case some events may not have been sent. -func (h *Hook) Flush(timeout time.Duration) bool { - return h.hubProvider().Client().Flush(timeout) -} diff --git a/vendor/github.com/getsentry/sentry-go/propagation_context.go b/vendor/github.com/getsentry/sentry-go/propagation_context.go deleted file mode 100644 index 7a0766a8a..000000000 --- a/vendor/github.com/getsentry/sentry-go/propagation_context.go +++ /dev/null @@ -1,90 +0,0 @@ -package sentry - -import ( - "crypto/rand" - "encoding/json" -) - -type PropagationContext struct { - TraceID TraceID `json:"trace_id"` - SpanID SpanID `json:"span_id"` - ParentSpanID SpanID `json:"parent_span_id"` - DynamicSamplingContext DynamicSamplingContext `json:"-"` -} - -func (p PropagationContext) MarshalJSON() ([]byte, error) { - type propagationContext PropagationContext - var parentSpanID string - if p.ParentSpanID != zeroSpanID { - parentSpanID = p.ParentSpanID.String() - } - return json.Marshal(struct { - *propagationContext - ParentSpanID string `json:"parent_span_id,omitempty"` - }{ - propagationContext: (*propagationContext)(&p), - ParentSpanID: parentSpanID, - }) -} - -func (p PropagationContext) Map() map[string]interface{} { - m := map[string]interface{}{ - "trace_id": p.TraceID, - "span_id": p.SpanID, - } - - if p.ParentSpanID != zeroSpanID { - m["parent_span_id"] = p.ParentSpanID - } - - return m -} - -func NewPropagationContext() PropagationContext { - p := PropagationContext{} - - if _, err := rand.Read(p.TraceID[:]); err != nil { - panic(err) - } - - if _, err := rand.Read(p.SpanID[:]); err != nil { - panic(err) - } - - return p -} - -func PropagationContextFromHeaders(trace, baggage string) (PropagationContext, error) { - p := NewPropagationContext() - - if _, err := rand.Read(p.SpanID[:]); err != nil { - panic(err) - } - - hasTrace := false - if trace != "" { - if tpc, valid := ParseTraceParentContext([]byte(trace)); valid { - hasTrace = true - p.TraceID = tpc.TraceID - p.ParentSpanID = tpc.ParentSpanID - } - } - - if baggage != "" { - dsc, err := DynamicSamplingContextFromHeader([]byte(baggage)) - if err != nil { - return PropagationContext{}, err - } - p.DynamicSamplingContext = dsc - } - - // In case a sentry-trace header is present but there are no sentry-related - // values in the baggage, create an empty, frozen DynamicSamplingContext. - if hasTrace && !p.DynamicSamplingContext.HasEntries() { - p.DynamicSamplingContext = DynamicSamplingContext{ - Frozen: true, - } - } - - return p, nil -} diff --git a/vendor/github.com/getsentry/sentry-go/scope.go b/vendor/github.com/getsentry/sentry-go/scope.go deleted file mode 100644 index 8245fdbd2..000000000 --- a/vendor/github.com/getsentry/sentry-go/scope.go +++ /dev/null @@ -1,486 +0,0 @@ -package sentry - -import ( - "bytes" - "io" - "net/http" - "sync" - "time" -) - -// Scope holds contextual data for the current scope. -// -// The scope is an object that can cloned efficiently and stores data that is -// locally relevant to an event. For instance the scope will hold recorded -// breadcrumbs and similar information. -// -// The scope can be interacted with in two ways. First, the scope is routinely -// updated with information by functions such as AddBreadcrumb which will modify -// the current scope. Second, the current scope can be configured through the -// ConfigureScope function or Hub method of the same name. -// -// The scope is meant to be modified but not inspected directly. When preparing -// an event for reporting, the current client adds information from the current -// scope into the event. -type Scope struct { - mu sync.RWMutex - breadcrumbs []*Breadcrumb - attachments []*Attachment - user User - tags map[string]string - contexts map[string]Context - extra map[string]interface{} - fingerprint []string - level Level - request *http.Request - // requestBody holds a reference to the original request.Body. - requestBody interface { - // Bytes returns bytes from the original body, lazily buffered as the - // original body is read. - Bytes() []byte - // Overflow returns true if the body is larger than the maximum buffer - // size. - Overflow() bool - } - eventProcessors []EventProcessor - - propagationContext PropagationContext - span *Span -} - -// NewScope creates a new Scope. -func NewScope() *Scope { - return &Scope{ - breadcrumbs: make([]*Breadcrumb, 0), - attachments: make([]*Attachment, 0), - tags: make(map[string]string), - contexts: make(map[string]Context), - extra: make(map[string]interface{}), - fingerprint: make([]string, 0), - propagationContext: NewPropagationContext(), - } -} - -// AddBreadcrumb adds new breadcrumb to the current scope -// and optionally throws the old one if limit is reached. -func (scope *Scope) AddBreadcrumb(breadcrumb *Breadcrumb, limit int) { - if breadcrumb.Timestamp.IsZero() { - breadcrumb.Timestamp = time.Now() - } - - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.breadcrumbs = append(scope.breadcrumbs, breadcrumb) - if len(scope.breadcrumbs) > limit { - scope.breadcrumbs = scope.breadcrumbs[1 : limit+1] - } -} - -// ClearBreadcrumbs clears all breadcrumbs from the current scope. -func (scope *Scope) ClearBreadcrumbs() { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.breadcrumbs = []*Breadcrumb{} -} - -// AddAttachment adds new attachment to the current scope. -func (scope *Scope) AddAttachment(attachment *Attachment) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.attachments = append(scope.attachments, attachment) -} - -// ClearAttachments clears all attachments from the current scope. -func (scope *Scope) ClearAttachments() { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.attachments = []*Attachment{} -} - -// SetUser sets the user for the current scope. -func (scope *Scope) SetUser(user User) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.user = user -} - -// SetRequest sets the request for the current scope. -func (scope *Scope) SetRequest(r *http.Request) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.request = r - - if r == nil { - return - } - - // Don't buffer request body if we know it is oversized. - if r.ContentLength > maxRequestBodyBytes { - return - } - // Don't buffer if there is no body. - if r.Body == nil || r.Body == http.NoBody { - return - } - buf := &limitedBuffer{Capacity: maxRequestBodyBytes} - r.Body = readCloser{ - Reader: io.TeeReader(r.Body, buf), - Closer: r.Body, - } - scope.requestBody = buf -} - -// SetRequestBody sets the request body for the current scope. -// -// This method should only be called when the body bytes are already available -// in memory. Typically, the request body is buffered lazily from the -// Request.Body from SetRequest. -func (scope *Scope) SetRequestBody(b []byte) { - scope.mu.Lock() - defer scope.mu.Unlock() - - capacity := maxRequestBodyBytes - overflow := false - if len(b) > capacity { - overflow = true - b = b[:capacity] - } - scope.requestBody = &limitedBuffer{ - Capacity: capacity, - Buffer: *bytes.NewBuffer(b), - overflow: overflow, - } -} - -// maxRequestBodyBytes is the default maximum request body size to send to -// Sentry. -const maxRequestBodyBytes = 10 * 1024 - -// A limitedBuffer is like a bytes.Buffer, but limited to store at most Capacity -// bytes. Any writes past the capacity are silently discarded, similar to -// io.Discard. -type limitedBuffer struct { - Capacity int - - bytes.Buffer - overflow bool -} - -// Write implements io.Writer. -func (b *limitedBuffer) Write(p []byte) (n int, err error) { - // Silently ignore writes after overflow. - if b.overflow { - return len(p), nil - } - left := b.Capacity - b.Len() - if left < 0 { - left = 0 - } - if len(p) > left { - b.overflow = true - p = p[:left] - } - return b.Buffer.Write(p) -} - -// Overflow returns true if the limitedBuffer discarded bytes written to it. -func (b *limitedBuffer) Overflow() bool { - return b.overflow -} - -// readCloser combines an io.Reader and an io.Closer to implement io.ReadCloser. -type readCloser struct { - io.Reader - io.Closer -} - -// SetTag adds a tag to the current scope. -func (scope *Scope) SetTag(key, value string) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.tags[key] = value -} - -// SetTags assigns multiple tags to the current scope. -func (scope *Scope) SetTags(tags map[string]string) { - scope.mu.Lock() - defer scope.mu.Unlock() - - for k, v := range tags { - scope.tags[k] = v - } -} - -// RemoveTag removes a tag from the current scope. -func (scope *Scope) RemoveTag(key string) { - scope.mu.Lock() - defer scope.mu.Unlock() - - delete(scope.tags, key) -} - -// SetContext adds a context to the current scope. -func (scope *Scope) SetContext(key string, value Context) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.contexts[key] = value -} - -// SetContexts assigns multiple contexts to the current scope. -func (scope *Scope) SetContexts(contexts map[string]Context) { - scope.mu.Lock() - defer scope.mu.Unlock() - - for k, v := range contexts { - scope.contexts[k] = v - } -} - -// RemoveContext removes a context from the current scope. -func (scope *Scope) RemoveContext(key string) { - scope.mu.Lock() - defer scope.mu.Unlock() - - delete(scope.contexts, key) -} - -// SetExtra adds an extra to the current scope. -func (scope *Scope) SetExtra(key string, value interface{}) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.extra[key] = value -} - -// SetExtras assigns multiple extras to the current scope. -func (scope *Scope) SetExtras(extra map[string]interface{}) { - scope.mu.Lock() - defer scope.mu.Unlock() - - for k, v := range extra { - scope.extra[k] = v - } -} - -// RemoveExtra removes a extra from the current scope. -func (scope *Scope) RemoveExtra(key string) { - scope.mu.Lock() - defer scope.mu.Unlock() - - delete(scope.extra, key) -} - -// SetFingerprint sets new fingerprint for the current scope. -func (scope *Scope) SetFingerprint(fingerprint []string) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.fingerprint = fingerprint -} - -// SetLevel sets new level for the current scope. -func (scope *Scope) SetLevel(level Level) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.level = level -} - -// SetPropagationContext sets the propagation context for the current scope. -func (scope *Scope) SetPropagationContext(propagationContext PropagationContext) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.propagationContext = propagationContext -} - -// SetSpan sets a span for the current scope. -func (scope *Scope) SetSpan(span *Span) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.span = span -} - -// Clone returns a copy of the current scope with all data copied over. -func (scope *Scope) Clone() *Scope { - scope.mu.RLock() - defer scope.mu.RUnlock() - - clone := NewScope() - clone.user = scope.user - clone.breadcrumbs = make([]*Breadcrumb, len(scope.breadcrumbs)) - copy(clone.breadcrumbs, scope.breadcrumbs) - clone.attachments = make([]*Attachment, len(scope.attachments)) - copy(clone.attachments, scope.attachments) - for key, value := range scope.tags { - clone.tags[key] = value - } - for key, value := range scope.contexts { - clone.contexts[key] = cloneContext(value) - } - for key, value := range scope.extra { - clone.extra[key] = value - } - clone.fingerprint = make([]string, len(scope.fingerprint)) - copy(clone.fingerprint, scope.fingerprint) - clone.level = scope.level - clone.request = scope.request - clone.requestBody = scope.requestBody - clone.eventProcessors = scope.eventProcessors - clone.propagationContext = scope.propagationContext - clone.span = scope.span - return clone -} - -// Clear removes the data from the current scope. Not safe for concurrent use. -func (scope *Scope) Clear() { - *scope = *NewScope() -} - -// AddEventProcessor adds an event processor to the current scope. -func (scope *Scope) AddEventProcessor(processor EventProcessor) { - scope.mu.Lock() - defer scope.mu.Unlock() - - scope.eventProcessors = append(scope.eventProcessors, processor) -} - -// ApplyToEvent takes the data from the current scope and attaches it to the event. -func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) *Event { - scope.mu.RLock() - defer scope.mu.RUnlock() - - if len(scope.breadcrumbs) > 0 { - event.Breadcrumbs = append(event.Breadcrumbs, scope.breadcrumbs...) - } - - if len(scope.attachments) > 0 { - event.Attachments = append(event.Attachments, scope.attachments...) - } - - if len(scope.tags) > 0 { - if event.Tags == nil { - event.Tags = make(map[string]string, len(scope.tags)) - } - - for key, value := range scope.tags { - event.Tags[key] = value - } - } - - if len(scope.contexts) > 0 { - if event.Contexts == nil { - event.Contexts = make(map[string]Context) - } - - for key, value := range scope.contexts { - if key == "trace" && event.Type == transactionType { - // Do not override trace context of - // transactions, otherwise it breaks the - // transaction event representation. - // For error events, the trace context is used - // to link errors and traces/spans in Sentry. - continue - } - - // Ensure we are not overwriting event fields - if _, ok := event.Contexts[key]; !ok { - event.Contexts[key] = cloneContext(value) - } - } - } - - if event.Contexts == nil { - event.Contexts = make(map[string]Context) - } - - if scope.span != nil { - if _, ok := event.Contexts["trace"]; !ok { - event.Contexts["trace"] = scope.span.traceContext().Map() - } - - transaction := scope.span.GetTransaction() - if transaction != nil { - event.sdkMetaData.dsc = DynamicSamplingContextFromTransaction(transaction) - } - } else { - event.Contexts["trace"] = scope.propagationContext.Map() - - dsc := scope.propagationContext.DynamicSamplingContext - if !dsc.HasEntries() && client != nil { - dsc = DynamicSamplingContextFromScope(scope, client) - } - event.sdkMetaData.dsc = dsc - } - - if len(scope.extra) > 0 { - if event.Extra == nil { - event.Extra = make(map[string]interface{}, len(scope.extra)) - } - - for key, value := range scope.extra { - event.Extra[key] = value - } - } - - if event.User.IsEmpty() { - event.User = scope.user - } - - if len(event.Fingerprint) == 0 { - event.Fingerprint = append(event.Fingerprint, scope.fingerprint...) - } - - if scope.level != "" { - event.Level = scope.level - } - - if event.Request == nil && scope.request != nil { - event.Request = NewRequest(scope.request) - // NOTE: The SDK does not attempt to send partial request body data. - // - // The reason being that Sentry's ingest pipeline and UI are optimized - // to show structured data. Additionally, tooling around PII scrubbing - // relies on structured data; truncated request bodies would create - // invalid payloads that are more prone to leaking PII data. - // - // Users can still send more data along their events if they want to, - // for example using Event.Extra. - if scope.requestBody != nil && !scope.requestBody.Overflow() { - event.Request.Data = string(scope.requestBody.Bytes()) - } - } - - for _, processor := range scope.eventProcessors { - id := event.EventID - event = processor(event, hint) - if event == nil { - Logger.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id) - return nil - } - } - - return event -} - -// cloneContext returns a new context with keys and values copied from the passed one. -// -// Note: a new Context (map) is returned, but the function does NOT do -// a proper deep copy: if some context values are pointer types (e.g. maps), -// they won't be properly copied. -func cloneContext(c Context) Context { - res := make(Context, len(c)) - for k, v := range c { - res[k] = v - } - return res -} diff --git a/vendor/github.com/getsentry/sentry-go/sentry.go b/vendor/github.com/getsentry/sentry-go/sentry.go deleted file mode 100644 index 7f2fe05fb..000000000 --- a/vendor/github.com/getsentry/sentry-go/sentry.go +++ /dev/null @@ -1,132 +0,0 @@ -package sentry - -import ( - "context" - "time" -) - -// The version of the SDK. -const SDKVersion = "0.31.1" - -// apiVersion is the minimum version of the Sentry API compatible with the -// sentry-go SDK. -const apiVersion = "7" - -// Init initializes the SDK with options. The returned error is non-nil if -// options is invalid, for instance if a malformed DSN is provided. -func Init(options ClientOptions) error { - hub := CurrentHub() - client, err := NewClient(options) - if err != nil { - return err - } - hub.BindClient(client) - return nil -} - -// AddBreadcrumb records a new breadcrumb. -// -// The total number of breadcrumbs that can be recorded are limited by the -// configuration on the client. -func AddBreadcrumb(breadcrumb *Breadcrumb) { - hub := CurrentHub() - hub.AddBreadcrumb(breadcrumb, nil) -} - -// CaptureMessage captures an arbitrary message. -func CaptureMessage(message string) *EventID { - hub := CurrentHub() - return hub.CaptureMessage(message) -} - -// CaptureException captures an error. -func CaptureException(exception error) *EventID { - hub := CurrentHub() - return hub.CaptureException(exception) -} - -// CaptureCheckIn captures a (cron) monitor check-in. -func CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID { - hub := CurrentHub() - return hub.CaptureCheckIn(checkIn, monitorConfig) -} - -// CaptureEvent captures an event on the currently active client if any. -// -// The event must already be assembled. Typically code would instead use -// the utility methods like CaptureException. The return value is the -// event ID. In case Sentry is disabled or event was dropped, the return value will be nil. -func CaptureEvent(event *Event) *EventID { - hub := CurrentHub() - return hub.CaptureEvent(event) -} - -// Recover captures a panic. -func Recover() *EventID { - if err := recover(); err != nil { - hub := CurrentHub() - return hub.Recover(err) - } - return nil -} - -// RecoverWithContext captures a panic and passes relevant context object. -func RecoverWithContext(ctx context.Context) *EventID { - err := recover() - if err == nil { - return nil - } - - hub := GetHubFromContext(ctx) - if hub == nil { - hub = CurrentHub() - } - - return hub.RecoverWithContext(ctx, err) -} - -// WithScope is a shorthand for CurrentHub().WithScope. -func WithScope(f func(scope *Scope)) { - hub := CurrentHub() - hub.WithScope(f) -} - -// ConfigureScope is a shorthand for CurrentHub().ConfigureScope. -func ConfigureScope(f func(scope *Scope)) { - hub := CurrentHub() - hub.ConfigureScope(f) -} - -// PushScope is a shorthand for CurrentHub().PushScope. -func PushScope() { - hub := CurrentHub() - hub.PushScope() -} - -// PopScope is a shorthand for CurrentHub().PopScope. -func PopScope() { - hub := CurrentHub() - hub.PopScope() -} - -// Flush waits until the underlying Transport sends any buffered events to the -// Sentry server, blocking for at most the given timeout. It returns false if -// the timeout was reached. In that case, some events may not have been sent. -// -// Flush should be called before terminating the program to avoid -// unintentionally dropping events. -// -// Do not call Flush indiscriminately after every call to CaptureEvent, -// CaptureException or CaptureMessage. Instead, to have the SDK send events over -// the network synchronously, configure it to use the HTTPSyncTransport in the -// call to Init. -func Flush(timeout time.Duration) bool { - hub := CurrentHub() - return hub.Flush(timeout) -} - -// LastEventID returns an ID of last captured event. -func LastEventID() EventID { - hub := CurrentHub() - return hub.LastEventID() -} diff --git a/vendor/github.com/getsentry/sentry-go/sourcereader.go b/vendor/github.com/getsentry/sentry-go/sourcereader.go deleted file mode 100644 index 74a083848..000000000 --- a/vendor/github.com/getsentry/sentry-go/sourcereader.go +++ /dev/null @@ -1,70 +0,0 @@ -package sentry - -import ( - "bytes" - "os" - "sync" -) - -type sourceReader struct { - mu sync.Mutex - cache map[string][][]byte -} - -func newSourceReader() sourceReader { - return sourceReader{ - cache: make(map[string][][]byte), - } -} - -func (sr *sourceReader) readContextLines(filename string, line, context int) ([][]byte, int) { - sr.mu.Lock() - defer sr.mu.Unlock() - - lines, ok := sr.cache[filename] - - if !ok { - data, err := os.ReadFile(filename) - if err != nil { - sr.cache[filename] = nil - return nil, 0 - } - lines = bytes.Split(data, []byte{'\n'}) - sr.cache[filename] = lines - } - - return sr.calculateContextLines(lines, line, context) -} - -func (sr *sourceReader) calculateContextLines(lines [][]byte, line, context int) ([][]byte, int) { - // Stacktrace lines are 1-indexed, slices are 0-indexed - line-- - - // contextLine points to a line that caused an issue itself, in relation to - // returned slice. - contextLine := context - - if lines == nil || line >= len(lines) || line < 0 { - return nil, 0 - } - - if context < 0 { - context = 0 - contextLine = 0 - } - - start := line - context - - if start < 0 { - contextLine += start - start = 0 - } - - end := line + context + 1 - - if end > len(lines) { - end = len(lines) - } - - return lines[start:end], contextLine -} diff --git a/vendor/github.com/getsentry/sentry-go/span_recorder.go b/vendor/github.com/getsentry/sentry-go/span_recorder.go deleted file mode 100644 index 9a58574e8..000000000 --- a/vendor/github.com/getsentry/sentry-go/span_recorder.go +++ /dev/null @@ -1,56 +0,0 @@ -package sentry - -import ( - "sync" -) - -// A spanRecorder stores a span tree that makes up a transaction. Safe for -// concurrent use. It is okay to add child spans from multiple goroutines. -type spanRecorder struct { - mu sync.Mutex - spans []*Span - overflowOnce sync.Once -} - -// record stores a span. The first stored span is assumed to be the root of a -// span tree. -func (r *spanRecorder) record(s *Span) { - maxSpans := defaultMaxSpans - if client := CurrentHub().Client(); client != nil { - maxSpans = client.options.MaxSpans - } - r.mu.Lock() - defer r.mu.Unlock() - if len(r.spans) >= maxSpans { - r.overflowOnce.Do(func() { - root := r.spans[0] - Logger.Printf("Too many spans: dropping spans from transaction with TraceID=%s SpanID=%s limit=%d", - root.TraceID, root.SpanID, maxSpans) - }) - // TODO(tracing): mark the transaction event in some way to - // communicate that spans were dropped. - return - } - r.spans = append(r.spans, s) -} - -// root returns the first recorded span. Returns nil if none have been recorded. -func (r *spanRecorder) root() *Span { - r.mu.Lock() - defer r.mu.Unlock() - if len(r.spans) == 0 { - return nil - } - return r.spans[0] -} - -// children returns a list of all recorded spans, except the root. Returns nil -// if there are no children. -func (r *spanRecorder) children() []*Span { - r.mu.Lock() - defer r.mu.Unlock() - if len(r.spans) < 2 { - return nil - } - return r.spans[1:] -} diff --git a/vendor/github.com/getsentry/sentry-go/stacktrace.go b/vendor/github.com/getsentry/sentry-go/stacktrace.go deleted file mode 100644 index f59e23664..000000000 --- a/vendor/github.com/getsentry/sentry-go/stacktrace.go +++ /dev/null @@ -1,407 +0,0 @@ -package sentry - -import ( - "go/build" - "reflect" - "runtime" - "slices" - "strings" -) - -const unknown string = "unknown" - -// The module download is split into two parts: downloading the go.mod and downloading the actual code. -// If you have dependencies only needed for tests, then they will show up in your go.mod, -// and go get will download their go.mods, but it will not download their code. -// The test-only dependencies get downloaded only when you need it, such as the first time you run go test. -// -// https://github.com/golang/go/issues/26913#issuecomment-411976222 - -// Stacktrace holds information about the frames of the stack. -type Stacktrace struct { - Frames []Frame `json:"frames,omitempty"` - FramesOmitted []uint `json:"frames_omitted,omitempty"` -} - -// NewStacktrace creates a stacktrace using runtime.Callers. -func NewStacktrace() *Stacktrace { - pcs := make([]uintptr, 100) - n := runtime.Callers(1, pcs) - - if n == 0 { - return nil - } - - runtimeFrames := extractFrames(pcs[:n]) - frames := createFrames(runtimeFrames) - - stacktrace := Stacktrace{ - Frames: frames, - } - - return &stacktrace -} - -// TODO: Make it configurable so that anyone can provide their own implementation? -// Use of reflection allows us to not have a hard dependency on any given -// package, so we don't have to import it. - -// ExtractStacktrace creates a new Stacktrace based on the given error. -func ExtractStacktrace(err error) *Stacktrace { - method := extractReflectedStacktraceMethod(err) - - var pcs []uintptr - - if method.IsValid() { - pcs = extractPcs(method) - } else { - pcs = extractXErrorsPC(err) - } - - if len(pcs) == 0 { - return nil - } - - runtimeFrames := extractFrames(pcs) - frames := createFrames(runtimeFrames) - - stacktrace := Stacktrace{ - Frames: frames, - } - - return &stacktrace -} - -func extractReflectedStacktraceMethod(err error) reflect.Value { - errValue := reflect.ValueOf(err) - - // https://github.com/go-errors/errors - methodStackFrames := errValue.MethodByName("StackFrames") - if methodStackFrames.IsValid() { - return methodStackFrames - } - - // https://github.com/pkg/errors - methodStackTrace := errValue.MethodByName("StackTrace") - if methodStackTrace.IsValid() { - return methodStackTrace - } - - // https://github.com/pingcap/errors - methodGetStackTracer := errValue.MethodByName("GetStackTracer") - if methodGetStackTracer.IsValid() { - stacktracer := methodGetStackTracer.Call(nil)[0] - stacktracerStackTrace := reflect.ValueOf(stacktracer).MethodByName("StackTrace") - - if stacktracerStackTrace.IsValid() { - return stacktracerStackTrace - } - } - - return reflect.Value{} -} - -func extractPcs(method reflect.Value) []uintptr { - var pcs []uintptr - - stacktrace := method.Call(nil)[0] - - if stacktrace.Kind() != reflect.Slice { - return nil - } - - for i := 0; i < stacktrace.Len(); i++ { - pc := stacktrace.Index(i) - - switch pc.Kind() { - case reflect.Uintptr: - pcs = append(pcs, uintptr(pc.Uint())) - case reflect.Struct: - for _, fieldName := range []string{"ProgramCounter", "PC"} { - field := pc.FieldByName(fieldName) - if !field.IsValid() { - continue - } - if field.Kind() == reflect.Uintptr { - pcs = append(pcs, uintptr(field.Uint())) - break - } - } - } - } - - return pcs -} - -// extractXErrorsPC extracts program counters from error values compatible with -// the error types from golang.org/x/xerrors. -// -// It returns nil if err is not compatible with errors from that package or if -// no program counters are stored in err. -func extractXErrorsPC(err error) []uintptr { - // This implementation uses the reflect package to avoid a hard dependency - // on third-party packages. - - // We don't know if err matches the expected type. For simplicity, instead - // of trying to account for all possible ways things can go wrong, some - // assumptions are made and if they are violated the code will panic. We - // recover from any panic and ignore it, returning nil. - //nolint: errcheck - defer func() { recover() }() - - field := reflect.ValueOf(err).Elem().FieldByName("frame") // type Frame struct{ frames [3]uintptr } - field = field.FieldByName("frames") - field = field.Slice(1, field.Len()) // drop first pc pointing to xerrors.New - pc := make([]uintptr, field.Len()) - for i := 0; i < field.Len(); i++ { - pc[i] = uintptr(field.Index(i).Uint()) - } - return pc -} - -// Frame represents a function call and it's metadata. Frames are associated -// with a Stacktrace. -type Frame struct { - Function string `json:"function,omitempty"` - Symbol string `json:"symbol,omitempty"` - // Module is, despite the name, the Sentry protocol equivalent of a Go - // package's import path. - Module string `json:"module,omitempty"` - Filename string `json:"filename,omitempty"` - AbsPath string `json:"abs_path,omitempty"` - Lineno int `json:"lineno,omitempty"` - Colno int `json:"colno,omitempty"` - PreContext []string `json:"pre_context,omitempty"` - ContextLine string `json:"context_line,omitempty"` - PostContext []string `json:"post_context,omitempty"` - InApp bool `json:"in_app"` - Vars map[string]interface{} `json:"vars,omitempty"` - // Package and the below are not used for Go stack trace frames. In - // other platforms it refers to a container where the Module can be - // found. For example, a Java JAR, a .NET Assembly, or a native - // dynamic library. They exists for completeness, allowing the - // construction and reporting of custom event payloads. - Package string `json:"package,omitempty"` - InstructionAddr string `json:"instruction_addr,omitempty"` - AddrMode string `json:"addr_mode,omitempty"` - SymbolAddr string `json:"symbol_addr,omitempty"` - ImageAddr string `json:"image_addr,omitempty"` - Platform string `json:"platform,omitempty"` - StackStart bool `json:"stack_start,omitempty"` -} - -// NewFrame assembles a stacktrace frame out of runtime.Frame. -func NewFrame(f runtime.Frame) Frame { - function := f.Function - var pkg string - - if function != "" { - pkg, function = splitQualifiedFunctionName(function) - } - - return newFrame(pkg, function, f.File, f.Line) -} - -// Like filepath.IsAbs() but doesn't care what platform you run this on. -// I.e. it also recognizies `/path/to/file` when run on Windows. -func isAbsPath(path string) bool { - if len(path) == 0 { - return false - } - - // If the volume name starts with a double slash, this is an absolute path. - if len(path) >= 1 && (path[0] == '/' || path[0] == '\\') { - return true - } - - // Windows absolute path, see https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats - if len(path) >= 3 && path[1] == ':' && (path[2] == '/' || path[2] == '\\') { - return true - } - - return false -} - -func newFrame(module string, function string, file string, line int) Frame { - frame := Frame{ - Lineno: line, - Module: module, - Function: function, - } - - switch { - case len(file) == 0: - frame.Filename = unknown - // Leave abspath as the empty string to be omitted when serializing event as JSON. - case isAbsPath(file): - frame.AbsPath = file - // TODO: in the general case, it is not trivial to come up with a - // "project relative" path with the data we have in run time. - // We shall not use filepath.Base because it creates ambiguous paths and - // affects the "Suspect Commits" feature. - // For now, leave relpath empty to be omitted when serializing the event - // as JSON. Improve this later. - default: - // f.File is a relative path. This may happen when the binary is built - // with the -trimpath flag. - frame.Filename = file - // Omit abspath when serializing the event as JSON. - } - - setInAppFrame(&frame) - - return frame -} - -// splitQualifiedFunctionName splits a package path-qualified function name into -// package name and function name. Such qualified names are found in -// runtime.Frame.Function values. -func splitQualifiedFunctionName(name string) (pkg string, fun string) { - pkg = packageName(name) - if len(pkg) > 0 { - fun = name[len(pkg)+1:] - } - return -} - -func extractFrames(pcs []uintptr) []runtime.Frame { - var frames = make([]runtime.Frame, 0, len(pcs)) - callersFrames := runtime.CallersFrames(pcs) - - for { - callerFrame, more := callersFrames.Next() - - frames = append(frames, callerFrame) - - if !more { - break - } - } - - slices.Reverse(frames) - return frames -} - -// createFrames creates Frame objects while filtering out frames that are not -// meant to be reported to Sentry, those are frames internal to the SDK or Go. -func createFrames(frames []runtime.Frame) []Frame { - if len(frames) == 0 { - return nil - } - - result := make([]Frame, 0, len(frames)) - - for _, frame := range frames { - function := frame.Function - var pkg string - if function != "" { - pkg, function = splitQualifiedFunctionName(function) - } - - if !shouldSkipFrame(pkg) { - result = append(result, newFrame(pkg, function, frame.File, frame.Line)) - } - } - - // Fix issues grouping errors with the new fully qualified function names - // introduced from Go 1.21 - result = cleanupFunctionNamePrefix(result) - return result -} - -// TODO ID: why do we want to do this? -// I'm not aware of other SDKs skipping all Sentry frames, regardless of their position in the stactrace. -// For example, in the .NET SDK, only the first frames are skipped until the call to the SDK. -// As is, this will also hide any intermediate frames in the stack and make debugging issues harder. -func shouldSkipFrame(module string) bool { - // Skip Go internal frames. - if module == "runtime" || module == "testing" { - return true - } - - // Skip Sentry internal frames, except for frames in _test packages (for testing). - if strings.HasPrefix(module, "github.com/getsentry/sentry-go") && - !strings.HasSuffix(module, "_test") { - return true - } - - return false -} - -// On Windows, GOROOT has backslashes, but we want forward slashes. -var goRoot = strings.ReplaceAll(build.Default.GOROOT, "\\", "/") - -func setInAppFrame(frame *Frame) { - frame.InApp = true - if strings.HasPrefix(frame.AbsPath, goRoot) || strings.Contains(frame.Module, "vendor") || - strings.Contains(frame.Module, "third_party") { - frame.InApp = false - } -} - -func callerFunctionName() string { - pcs := make([]uintptr, 1) - runtime.Callers(3, pcs) - callersFrames := runtime.CallersFrames(pcs) - callerFrame, _ := callersFrames.Next() - return baseName(callerFrame.Function) -} - -// packageName returns the package part of the symbol name, or the empty string -// if there is none. -// It replicates https://golang.org/pkg/debug/gosym/#Sym.PackageName, avoiding a -// dependency on debug/gosym. -func packageName(name string) string { - if isCompilerGeneratedSymbol(name) { - return "" - } - - pathend := strings.LastIndex(name, "/") - if pathend < 0 { - pathend = 0 - } - - if i := strings.Index(name[pathend:], "."); i != -1 { - return name[:pathend+i] - } - return "" -} - -// baseName returns the symbol name without the package or receiver name. -// It replicates https://golang.org/pkg/debug/gosym/#Sym.BaseName, avoiding a -// dependency on debug/gosym. -func baseName(name string) string { - if i := strings.LastIndex(name, "."); i != -1 { - return name[i+1:] - } - return name -} - -func isCompilerGeneratedSymbol(name string) bool { - // In versions of Go 1.20 and above a prefix of "type:" and "go:" is a - // compiler-generated symbol that doesn't belong to any package. - // See variable reservedimports in cmd/compile/internal/gc/subr.go - if strings.HasPrefix(name, "go:") || strings.HasPrefix(name, "type:") { - return true - } - return false -} - -// Walk backwards through the results and for the current function name -// remove it's parent function's prefix, leaving only it's actual name. This -// fixes issues grouping errors with the new fully qualified function names -// introduced from Go 1.21. -func cleanupFunctionNamePrefix(f []Frame) []Frame { - for i := len(f) - 1; i > 0; i-- { - name := f[i].Function - parentName := f[i-1].Function + "." - - if !strings.HasPrefix(name, parentName) { - continue - } - - f[i].Function = name[len(parentName):] - } - - return f -} diff --git a/vendor/github.com/getsentry/sentry-go/traces_sampler.go b/vendor/github.com/getsentry/sentry-go/traces_sampler.go deleted file mode 100644 index 69e7cb7fa..000000000 --- a/vendor/github.com/getsentry/sentry-go/traces_sampler.go +++ /dev/null @@ -1,19 +0,0 @@ -package sentry - -// A SamplingContext is passed to a TracesSampler to determine a sampling -// decision. -// -// TODO(tracing): possibly expand SamplingContext to include custom / -// user-provided data. -type SamplingContext struct { - Span *Span // The current span, always non-nil. - Parent *Span // The parent span, may be nil. -} - -// The TracesSample type is an adapter to allow the use of ordinary -// functions as a TracesSampler. -type TracesSampler func(ctx SamplingContext) float64 - -func (f TracesSampler) Sample(ctx SamplingContext) float64 { - return f(ctx) -} diff --git a/vendor/github.com/getsentry/sentry-go/tracing.go b/vendor/github.com/getsentry/sentry-go/tracing.go deleted file mode 100644 index 0c5877c59..000000000 --- a/vendor/github.com/getsentry/sentry-go/tracing.go +++ /dev/null @@ -1,1028 +0,0 @@ -package sentry - -import ( - "context" - "crypto/rand" - "encoding/hex" - "encoding/json" - "fmt" - "net/http" - "regexp" - "strings" - "sync" - "time" -) - -const ( - SentryTraceHeader = "sentry-trace" - SentryBaggageHeader = "baggage" -) - -// SpanOrigin indicates what created a trace or a span. See: https://develop.sentry.dev/sdk/performance/trace-origin/ -type SpanOrigin string - -const ( - SpanOriginManual = "manual" - SpanOriginEcho = "auto.http.echo" - SpanOriginFastHTTP = "auto.http.fasthttp" - SpanOriginFiber = "auto.http.fiber" - SpanOriginGin = "auto.http.gin" - SpanOriginStdLib = "auto.http.stdlib" - SpanOriginIris = "auto.http.iris" - SpanOriginNegroni = "auto.http.negroni" -) - -// A Span is the building block of a Sentry transaction. Spans build up a tree -// structure of timed operations. The span tree makes up a transaction event -// that is sent to Sentry when the root span is finished. -// -// Spans must be started with either StartSpan or Span.StartChild. -type Span struct { //nolint: maligned // prefer readability over optimal memory layout (see note below *) - TraceID TraceID `json:"trace_id"` - SpanID SpanID `json:"span_id"` - ParentSpanID SpanID `json:"parent_span_id"` - Name string `json:"name,omitempty"` - Op string `json:"op,omitempty"` - Description string `json:"description,omitempty"` - Status SpanStatus `json:"status,omitempty"` - Tags map[string]string `json:"tags,omitempty"` - StartTime time.Time `json:"start_timestamp"` - EndTime time.Time `json:"timestamp"` - Data map[string]interface{} `json:"data,omitempty"` - Sampled Sampled `json:"-"` - Source TransactionSource `json:"-"` - Origin SpanOrigin `json:"origin,omitempty"` - - // mu protects concurrent writes to map fields - mu sync.RWMutex - // sample rate the span was sampled with. - sampleRate float64 - // ctx is the context where the span was started. Always non-nil. - ctx context.Context - // Dynamic Sampling context - dynamicSamplingContext DynamicSamplingContext - // parent refers to the immediate local parent span. A remote parent span is - // only referenced by setting ParentSpanID. - parent *Span - // recorder stores all spans in a transaction. Guaranteed to be non-nil. - recorder *spanRecorder - // span context, can only be set on transactions - contexts map[string]Context - // a Once instance to make sure that Finish() is only called once. - finishOnce sync.Once -} - -// TraceParentContext describes the context of a (remote) parent span. -// -// The context is normally extracted from a received "sentry-trace" header and -// used to initialize a new transaction. -// -// Note: the name might be not the best one. It was taken mostly to stay aligned -// with other SDKs, and it alludes to W3C "traceparent" header (https://www.w3.org/TR/trace-context/), -// which serves a similar purpose to "sentry-trace". We should eventually consider -// making this type internal-only and give it a better name. -type TraceParentContext struct { - TraceID TraceID - ParentSpanID SpanID - Sampled Sampled -} - -// (*) Note on maligned: -// -// We prefer readability over optimal memory layout. If we ever decide to -// reorder fields, we can use a tool: -// -// go run honnef.co/go/tools/cmd/structlayout -json . Span | go run honnef.co/go/tools/cmd/structlayout-optimize -// -// Other structs would deserve reordering as well, for example Event. - -// TODO: make Span.Tags and Span.Data opaque types (struct{unexported []slice}). -// An opaque type allows us to add methods and make it more convenient to use -// than maps, because maps require careful nil checks to use properly or rely on -// explicit initialization for every span, even when there might be no -// tags/data. For Span.Data, must gracefully handle values that cannot be -// marshaled into JSON (see transport.go:getRequestBodyFromEvent). - -// StartSpan starts a new span to describe an operation. The new span will be a -// child of the last span stored in ctx, if any. -// -// One or more options can be used to modify the span properties. Typically one -// option as a function literal is enough. Combining multiple options can be -// useful to define and reuse specific properties with named functions. -// -// Caller should call the Finish method on the span to mark its end. Finishing a -// root span sends the span and all of its children, recursively, as a -// transaction to Sentry. -func StartSpan(ctx context.Context, operation string, options ...SpanOption) *Span { - parent, hasParent := ctx.Value(spanContextKey{}).(*Span) - var span Span - span = Span{ - // defaults - Op: operation, - StartTime: time.Now(), - Sampled: SampledUndefined, - - ctx: context.WithValue(ctx, spanContextKey{}, &span), - parent: parent, - } - - _, err := rand.Read(span.SpanID[:]) - if err != nil { - panic(err) - } - - if hasParent { - span.TraceID = parent.TraceID - span.ParentSpanID = parent.SpanID - span.Origin = parent.Origin - } else { - // Only set the Source if this is a transaction - span.Source = SourceCustom - span.Origin = SpanOriginManual - - // Implementation note: - // - // While math/rand is ~2x faster than crypto/rand (exact - // difference depends on hardware / OS), crypto/rand is probably - // fast enough and a safer choice. - // - // For reference, OpenTelemetry [1] uses crypto/rand to seed - // math/rand. AFAICT this approach does not preserve the - // properties from crypto/rand that make it suitable for - // cryptography. While it might be debatable whether those - // properties are important for us here, again, we're taking the - // safer path. - // - // See [2a] & [2b] for a discussion of some of the properties we - // obtain by using crypto/rand and [3a] & [3b] for why we avoid - // math/rand. - // - // Because the math/rand seed has only 64 bits (int64), if the - // first thing we do after seeding an RNG is to read in a random - // TraceID, there are only 2^64 possible values. Compared to - // UUID v4 that have 122 random bits, there is a much greater - // chance of collision [4a] & [4b]. - // - // [1]: https://github.com/open-telemetry/opentelemetry-go/blob/958041ddf619a128/sdk/trace/trace.go#L25-L31 - // [2a]: https://security.stackexchange.com/q/120352/246345 - // [2b]: https://security.stackexchange.com/a/120365/246345 - // [3a]: https://github.com/golang/go/issues/11871#issuecomment-126333686 - // [3b]: https://github.com/golang/go/issues/11871#issuecomment-126357889 - // [4a]: https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions - // [4b]: https://www.wolframalpha.com/input/?i=sqrt%282*2%5E64*ln%281%2F%281-0.5%29%29%29 - _, err := rand.Read(span.TraceID[:]) - if err != nil { - panic(err) - } - } - - // Apply options to override defaults. - for _, option := range options { - option(&span) - } - - span.Sampled = span.sample() - - span.recorder = &spanRecorder{} - if hasParent { - span.recorder = parent.spanRecorder() - } - - span.recorder.record(&span) - - clientOptions := span.clientOptions() - if clientOptions.EnableTracing { - hub := hubFromContext(ctx) - if !span.IsTransaction() { - // Push a new scope to stack for non transaction span - hub.PushScope() - } - hub.Scope().SetSpan(&span) - } - - return &span -} - -// Finish sets the span's end time, unless already set. If the span is the root -// of a span tree, Finish sends the span tree to Sentry as a transaction. -// -// The logic is executed at most once per span, so that (incorrectly) calling it twice -// never double sends to Sentry. -func (s *Span) Finish() { - s.finishOnce.Do(s.doFinish) -} - -// Context returns the context containing the span. -func (s *Span) Context() context.Context { return s.ctx } - -// StartChild starts a new child span. -// -// The call span.StartChild(operation, options...) is a shortcut for -// StartSpan(span.Context(), operation, options...). -func (s *Span) StartChild(operation string, options ...SpanOption) *Span { - return StartSpan(s.Context(), operation, options...) -} - -// SetTag sets a tag on the span. It is recommended to use SetTag instead of -// accessing the tags map directly as SetTag takes care of initializing the map -// when necessary. -func (s *Span) SetTag(name, value string) { - s.mu.Lock() - defer s.mu.Unlock() - - if s.Tags == nil { - s.Tags = make(map[string]string) - } - s.Tags[name] = value -} - -// SetData sets a data on the span. It is recommended to use SetData instead of -// accessing the data map directly as SetData takes care of initializing the map -// when necessary. -func (s *Span) SetData(name string, value interface{}) { - if value == nil { - return - } - - s.mu.Lock() - defer s.mu.Unlock() - - if s.Data == nil { - s.Data = make(map[string]interface{}) - } - s.Data[name] = value -} - -// SetContext sets a context on the span. It is recommended to use SetContext instead of -// accessing the contexts map directly as SetContext takes care of initializing the map -// when necessary. -func (s *Span) SetContext(key string, value Context) { - s.mu.Lock() - defer s.mu.Unlock() - - if s.contexts == nil { - s.contexts = make(map[string]Context) - } - s.contexts[key] = value -} - -// IsTransaction checks if the given span is a transaction. -func (s *Span) IsTransaction() bool { - return s.parent == nil -} - -// GetTransaction returns the transaction that contains this span. -// -// For transaction spans it returns itself. For spans that were created manually -// the method returns "nil". -func (s *Span) GetTransaction() *Span { - spanRecorder := s.spanRecorder() - if spanRecorder == nil { - // This probably means that the Span was created manually (not via - // StartTransaction/StartSpan or StartChild). - // Return "nil" to indicate that it's not a normal situation. - return nil - } - recorderRoot := spanRecorder.root() - if recorderRoot == nil { - // Same as above: manually created Span. - return nil - } - return recorderRoot -} - -// TODO(tracing): maybe add shortcuts to get/set transaction name. Right now the -// transaction name is in the Scope, as it has existed there historically, prior -// to tracing. -// -// See Scope.Transaction() and Scope.SetTransaction(). -// -// func (s *Span) TransactionName() string -// func (s *Span) SetTransactionName(name string) - -// ToSentryTrace returns the seralized TraceParentContext from a transaction/span. -// Use this function to propagate the TraceParentContext to a downstream SDK, -// either as the value of the "sentry-trace" HTTP header, or as an html "sentry-trace" meta tag. -func (s *Span) ToSentryTrace() string { - // TODO(tracing): add instrumentation for outgoing HTTP requests using - // ToSentryTrace. - var b strings.Builder - fmt.Fprintf(&b, "%s-%s", s.TraceID.Hex(), s.SpanID.Hex()) - switch s.Sampled { - case SampledTrue: - b.WriteString("-1") - case SampledFalse: - b.WriteString("-0") - } - return b.String() -} - -// ToBaggage returns the serialized DynamicSamplingContext from a transaction. -// Use this function to propagate the DynamicSamplingContext to a downstream SDK, -// either as the value of the "baggage" HTTP header, or as an html "baggage" meta tag. -func (s *Span) ToBaggage() string { - t := s.GetTransaction() - if t == nil { - return "" - } - - // In case there is currently no frozen DynamicSamplingContext attached to the transaction, - // create one from the properties of the transaction. - if !s.dynamicSamplingContext.IsFrozen() { - // This will return a frozen DynamicSamplingContext. - if dsc := DynamicSamplingContextFromTransaction(t); dsc.HasEntries() { - t.dynamicSamplingContext = dsc - } - } - - return t.dynamicSamplingContext.String() -} - -// SetDynamicSamplingContext sets the given dynamic sampling context on the -// current transaction. -func (s *Span) SetDynamicSamplingContext(dsc DynamicSamplingContext) { - if s.IsTransaction() { - s.dynamicSamplingContext = dsc - } -} - -// doFinish runs the actual Span.Finish() logic. -func (s *Span) doFinish() { - if s.EndTime.IsZero() { - s.EndTime = monotonicTimeSince(s.StartTime) - } - - hub := hubFromContext(s.ctx) - if !s.IsTransaction() { - // Referenced to StartSpan function that pushes current non-transaction span to scope stack - defer hub.PopScope() - } - - if !s.Sampled.Bool() { - return - } - event := s.toEvent() - if event == nil { - return - } - - // TODO(tracing): add breadcrumbs - // (see https://github.com/getsentry/sentry-python/blob/f6f3525f8812f609/sentry_sdk/tracing.py#L372) - - hub.CaptureEvent(event) -} - -// sentryTracePattern matches either -// -// TRACE_ID - SPAN_ID -// [[:xdigit:]]{32}-[[:xdigit:]]{16} -// -// or -// -// TRACE_ID - SPAN_ID - SAMPLED -// [[:xdigit:]]{32}-[[:xdigit:]]{16}-[01] -var sentryTracePattern = regexp.MustCompile(`^([[:xdigit:]]{32})-([[:xdigit:]]{16})(?:-([01]))?$`) - -// updateFromSentryTrace parses a sentry-trace HTTP header (as returned by -// ToSentryTrace) and updates fields of the span. If the header cannot be -// recognized as valid, the span is left unchanged. The returned value indicates -// whether the span was updated. -func (s *Span) updateFromSentryTrace(header []byte) (updated bool) { - m := sentryTracePattern.FindSubmatch(header) - if m == nil { - // no match - return false - } - _, _ = hex.Decode(s.TraceID[:], m[1]) - _, _ = hex.Decode(s.ParentSpanID[:], m[2]) - if len(m[3]) != 0 { - switch m[3][0] { - case '0': - s.Sampled = SampledFalse - case '1': - s.Sampled = SampledTrue - } - } - return true -} - -func (s *Span) updateFromBaggage(header []byte) { - if s.IsTransaction() { - dsc, err := DynamicSamplingContextFromHeader(header) - if err != nil { - return - } - - s.dynamicSamplingContext = dsc - } -} - -func (s *Span) MarshalJSON() ([]byte, error) { - // span aliases Span to allow calling json.Marshal without an infinite loop. - // It preserves all fields while none of the attached methods. - type span Span - var parentSpanID string - if s.ParentSpanID != zeroSpanID { - parentSpanID = s.ParentSpanID.String() - } - return json.Marshal(struct { - *span - ParentSpanID string `json:"parent_span_id,omitempty"` - }{ - span: (*span)(s), - ParentSpanID: parentSpanID, - }) -} - -func (s *Span) clientOptions() *ClientOptions { - client := hubFromContext(s.ctx).Client() - if client != nil { - return &client.options - } - return &ClientOptions{} -} - -func (s *Span) sample() Sampled { - clientOptions := s.clientOptions() - // https://develop.sentry.dev/sdk/performance/#sampling - // #1 tracing is not enabled. - if !clientOptions.EnableTracing { - Logger.Printf("Dropping transaction: EnableTracing is set to %t", clientOptions.EnableTracing) - s.sampleRate = 0.0 - return SampledFalse - } - - // #2 explicit sampling decision via StartSpan/StartTransaction options. - if s.Sampled != SampledUndefined { - Logger.Printf("Using explicit sampling decision from StartSpan/StartTransaction: %v", s.Sampled) - switch s.Sampled { - case SampledTrue: - s.sampleRate = 1.0 - case SampledFalse: - s.sampleRate = 0.0 - } - return s.Sampled - } - - // Variant for non-transaction spans: they inherit the parent decision. - // Note: non-transaction should always have a parent, but we check both - // conditions anyway -- the first for semantic meaning, the second to - // avoid a nil pointer dereference. - if !s.IsTransaction() && s.parent != nil { - return s.parent.Sampled - } - - // #3 use TracesSampler from ClientOptions. - sampler := clientOptions.TracesSampler - samplingContext := SamplingContext{ - Span: s, - Parent: s.parent, - } - - if sampler != nil { - tracesSamplerSampleRate := sampler.Sample(samplingContext) - s.sampleRate = tracesSamplerSampleRate - if tracesSamplerSampleRate < 0.0 || tracesSamplerSampleRate > 1.0 { - Logger.Printf("Dropping transaction: Returned TracesSampler rate is out of range [0.0, 1.0]: %f", tracesSamplerSampleRate) - return SampledFalse - } - if tracesSamplerSampleRate == 0 { - Logger.Printf("Dropping transaction: Returned TracesSampler rate is: %f", tracesSamplerSampleRate) - return SampledFalse - } - - if rng.Float64() < tracesSamplerSampleRate { - return SampledTrue - } - Logger.Printf("Dropping transaction: TracesSampler returned rate: %f", tracesSamplerSampleRate) - return SampledFalse - } - // #4 inherit parent decision. - if s.parent != nil { - Logger.Printf("Using sampling decision from parent: %v", s.parent.Sampled) - switch s.parent.Sampled { - case SampledTrue: - s.sampleRate = 1.0 - case SampledFalse: - s.sampleRate = 0.0 - } - return s.parent.Sampled - } - - // #5 use TracesSampleRate from ClientOptions. - sampleRate := clientOptions.TracesSampleRate - s.sampleRate = sampleRate - if sampleRate < 0.0 || sampleRate > 1.0 { - Logger.Printf("Dropping transaction: TracesSamplerRate out of range [0.0, 1.0]: %f", sampleRate) - return SampledFalse - } - if sampleRate == 0.0 { - Logger.Printf("Dropping transaction: TracesSampleRate rate is: %f", sampleRate) - return SampledFalse - } - - if rng.Float64() < sampleRate { - return SampledTrue - } - - return SampledFalse -} - -func (s *Span) toEvent() *Event { - s.mu.Lock() - defer s.mu.Unlock() - - if !s.IsTransaction() { - return nil // only transactions can be transformed into events - } - - children := s.recorder.children() - finished := make([]*Span, 0, len(children)) - for _, child := range children { - if child.EndTime.IsZero() { - Logger.Printf("Dropped unfinished span: Op=%q TraceID=%s SpanID=%s", child.Op, child.TraceID, child.SpanID) - continue - } - finished = append(finished, child) - } - - // Create and attach a DynamicSamplingContext to the transaction. - // If the DynamicSamplingContext is not frozen at this point, we can assume being head of trace. - if !s.dynamicSamplingContext.IsFrozen() { - s.dynamicSamplingContext = DynamicSamplingContextFromTransaction(s) - } - - contexts := make(map[string]Context, len(s.contexts)+1) - for k, v := range s.contexts { - contexts[k] = cloneContext(v) - } - contexts["trace"] = s.traceContext().Map() - - // Make sure that the transaction source is valid - transactionSource := s.Source - if !transactionSource.isValid() { - transactionSource = SourceCustom - } - - return &Event{ - Type: transactionType, - Transaction: s.Name, - Contexts: contexts, - Tags: s.Tags, - Extra: s.Data, - Timestamp: s.EndTime, - StartTime: s.StartTime, - Spans: finished, - TransactionInfo: &TransactionInfo{ - Source: transactionSource, - }, - sdkMetaData: SDKMetaData{ - dsc: s.dynamicSamplingContext, - }, - } -} - -func (s *Span) traceContext() *TraceContext { - return &TraceContext{ - TraceID: s.TraceID, - SpanID: s.SpanID, - ParentSpanID: s.ParentSpanID, - Op: s.Op, - Description: s.Description, - Status: s.Status, - } -} - -// spanRecorder stores the span tree. Guaranteed to be non-nil. -func (s *Span) spanRecorder() *spanRecorder { return s.recorder } - -// ParseTraceParentContext parses a sentry-trace header and builds a TraceParentContext from the -// parsed values. If the header was parsed correctly, the second returned argument -// ("valid") will be set to true, otherwise (e.g., empty or malformed header) it will -// be false. -func ParseTraceParentContext(header []byte) (traceParentContext TraceParentContext, valid bool) { - s := Span{} - updated := s.updateFromSentryTrace(header) - if !updated { - return TraceParentContext{}, false - } - return TraceParentContext{ - TraceID: s.TraceID, - ParentSpanID: s.ParentSpanID, - Sampled: s.Sampled, - }, true -} - -// TraceID identifies a trace. -type TraceID [16]byte - -func (id TraceID) Hex() []byte { - b := make([]byte, hex.EncodedLen(len(id))) - hex.Encode(b, id[:]) - return b -} - -func (id TraceID) String() string { - return string(id.Hex()) -} - -func (id TraceID) MarshalText() ([]byte, error) { - return id.Hex(), nil -} - -// SpanID identifies a span. -type SpanID [8]byte - -func (id SpanID) Hex() []byte { - b := make([]byte, hex.EncodedLen(len(id))) - hex.Encode(b, id[:]) - return b -} - -func (id SpanID) String() string { - return string(id.Hex()) -} - -func (id SpanID) MarshalText() ([]byte, error) { - return id.Hex(), nil -} - -// Zero values of TraceID and SpanID used for comparisons. -var ( - zeroTraceID TraceID - zeroSpanID SpanID -) - -// Contains information about how the name of the transaction was determined. -type TransactionSource string - -const ( - SourceCustom TransactionSource = "custom" - SourceURL TransactionSource = "url" - SourceRoute TransactionSource = "route" - SourceView TransactionSource = "view" - SourceComponent TransactionSource = "component" - SourceTask TransactionSource = "task" -) - -// A set of all valid transaction sources. -var allTransactionSources = map[TransactionSource]struct{}{ - SourceCustom: {}, - SourceURL: {}, - SourceRoute: {}, - SourceView: {}, - SourceComponent: {}, - SourceTask: {}, -} - -// isValid returns 'true' if the given transaction source is a valid -// source as recognized by the envelope protocol: -// https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations -func (ts TransactionSource) isValid() bool { - _, found := allTransactionSources[ts] - return found -} - -// SpanStatus is the status of a span. -type SpanStatus uint8 - -// Implementation note: -// -// In Relay (ingestion), the SpanStatus type is an enum used as -// Annotated when embedded in structs, making it effectively -// Option. It means the status is either null or one of the known -// string values. -// -// In Snuba (search), the SpanStatus is stored as an uint8 and defaulted to 2 -// ("unknown") when not set. It means that Discover searches for -// `transaction.status:unknown` return both transactions/spans with status -// `null` or `"unknown"`. Searches for `transaction.status:""` return nothing. -// -// With that in mind, the Go SDK default is SpanStatusUndefined, which is -// null/omitted when serializing to JSON, but integrations may update the status -// automatically based on contextual information. - -const ( - SpanStatusUndefined SpanStatus = iota - SpanStatusOK - SpanStatusCanceled - SpanStatusUnknown - SpanStatusInvalidArgument - SpanStatusDeadlineExceeded - SpanStatusNotFound - SpanStatusAlreadyExists - SpanStatusPermissionDenied - SpanStatusResourceExhausted - SpanStatusFailedPrecondition - SpanStatusAborted - SpanStatusOutOfRange - SpanStatusUnimplemented - SpanStatusInternalError - SpanStatusUnavailable - SpanStatusDataLoss - SpanStatusUnauthenticated - maxSpanStatus -) - -var spanStatuses = [maxSpanStatus]string{ - "", - "ok", - "cancelled", // [sic] - "unknown", - "invalid_argument", - "deadline_exceeded", - "not_found", - "already_exists", - "permission_denied", - "resource_exhausted", - "failed_precondition", - "aborted", - "out_of_range", - "unimplemented", - "internal_error", - "unavailable", - "data_loss", - "unauthenticated", -} - -func (ss SpanStatus) String() string { - if ss >= maxSpanStatus { - return "" - } - return spanStatuses[ss] -} - -func (ss SpanStatus) MarshalJSON() ([]byte, error) { - s := ss.String() - if s == "" { - return []byte("null"), nil - } - return json.Marshal(s) -} - -// A TraceContext carries information about an ongoing trace and is meant to be -// stored in Event.Contexts (as *TraceContext). -type TraceContext struct { - TraceID TraceID `json:"trace_id"` - SpanID SpanID `json:"span_id"` - ParentSpanID SpanID `json:"parent_span_id"` - Op string `json:"op,omitempty"` - Description string `json:"description,omitempty"` - Status SpanStatus `json:"status,omitempty"` -} - -func (tc *TraceContext) MarshalJSON() ([]byte, error) { - // traceContext aliases TraceContext to allow calling json.Marshal without - // an infinite loop. It preserves all fields while none of the attached - // methods. - type traceContext TraceContext - var parentSpanID string - if tc.ParentSpanID != zeroSpanID { - parentSpanID = tc.ParentSpanID.String() - } - return json.Marshal(struct { - *traceContext - ParentSpanID string `json:"parent_span_id,omitempty"` - }{ - traceContext: (*traceContext)(tc), - ParentSpanID: parentSpanID, - }) -} - -func (tc TraceContext) Map() map[string]interface{} { - m := map[string]interface{}{ - "trace_id": tc.TraceID, - "span_id": tc.SpanID, - } - - if tc.ParentSpanID != [8]byte{} { - m["parent_span_id"] = tc.ParentSpanID - } - - if tc.Op != "" { - m["op"] = tc.Op - } - - if tc.Description != "" { - m["description"] = tc.Description - } - - if tc.Status > 0 && tc.Status < maxSpanStatus { - m["status"] = tc.Status - } - - return m -} - -// Sampled signifies a sampling decision. -type Sampled int8 - -// The possible trace sampling decisions are: SampledFalse, SampledUndefined -// (default) and SampledTrue. -const ( - SampledFalse Sampled = -1 - SampledUndefined Sampled = 0 - SampledTrue Sampled = 1 -) - -func (s Sampled) String() string { - switch s { - case SampledFalse: - return "SampledFalse" - case SampledUndefined: - return "SampledUndefined" - case SampledTrue: - return "SampledTrue" - default: - return fmt.Sprintf("SampledInvalid(%d)", s) - } -} - -// Bool returns true if the sample decision is SampledTrue, false otherwise. -func (s Sampled) Bool() bool { - return s == SampledTrue -} - -// A SpanOption is a function that can modify the properties of a span. -type SpanOption func(s *Span) - -// WithTransactionName option sets the name of the current transaction. -// -// A span tree has a single transaction name, therefore using this option when -// starting a span affects the span tree as a whole, potentially overwriting a -// name set previously. -func WithTransactionName(name string) SpanOption { - return func(s *Span) { - s.Name = name - } -} - -// WithDescription sets the description of a span. -func WithDescription(description string) SpanOption { - return func(s *Span) { - s.Description = description - } -} - -// WithOpName sets the operation name for a given span. -func WithOpName(name string) SpanOption { - return func(s *Span) { - s.Op = name - } -} - -// WithTransactionSource sets the source of the transaction name. -// -// Note: if the transaction source is not a valid source (as described -// by the spec https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations), -// it will be corrected to "custom" eventually, before the transaction is sent. -func WithTransactionSource(source TransactionSource) SpanOption { - return func(s *Span) { - s.Source = source - } -} - -// WithSpanSampled updates the sampling flag for a given span. -func WithSpanSampled(sampled Sampled) SpanOption { - return func(s *Span) { - s.Sampled = sampled - } -} - -// WithSpanOrigin sets the origin of the span. -func WithSpanOrigin(origin SpanOrigin) SpanOption { - return func(s *Span) { - s.Origin = origin - } -} - -// Continue a trace based on traceparent and bagge values. -// If the SDK is configured with tracing enabled, -// this function returns populated SpanOption. -// In any other cases, it populates the propagation context on the scope. -func ContinueTrace(hub *Hub, traceparent, baggage string) SpanOption { - scope := hub.Scope() - propagationContext, _ := PropagationContextFromHeaders(traceparent, baggage) - scope.SetPropagationContext(propagationContext) - - return ContinueFromHeaders(traceparent, baggage) -} - -// ContinueFromRequest returns a span option that updates the span to continue -// an existing trace. If it cannot detect an existing trace in the request, the -// span will be left unchanged. -// -// ContinueFromRequest is an alias for: -// -// ContinueFromHeaders(r.Header.Get(SentryTraceHeader), r.Header.Get(SentryBaggageHeader)). -func ContinueFromRequest(r *http.Request) SpanOption { - return ContinueFromHeaders(r.Header.Get(SentryTraceHeader), r.Header.Get(SentryBaggageHeader)) -} - -// ContinueFromHeaders returns a span option that updates the span to continue -// an existing TraceID and propagates the Dynamic Sampling context. -func ContinueFromHeaders(trace, baggage string) SpanOption { - return func(s *Span) { - if trace != "" { - s.updateFromSentryTrace([]byte(trace)) - } - if baggage != "" { - s.updateFromBaggage([]byte(baggage)) - } - - // In case a sentry-trace header is present but there are no sentry-related - // values in the baggage, create an empty, frozen DynamicSamplingContext. - if trace != "" && !s.dynamicSamplingContext.HasEntries() { - s.dynamicSamplingContext = DynamicSamplingContext{ - Frozen: true, - } - } - } -} - -// ContinueFromTrace returns a span option that updates the span to continue -// an existing TraceID. -func ContinueFromTrace(trace string) SpanOption { - return func(s *Span) { - if trace == "" { - return - } - s.updateFromSentryTrace([]byte(trace)) - } -} - -// spanContextKey is used to store span values in contexts. -type spanContextKey struct{} - -// TransactionFromContext returns the root span of the current transaction. It -// returns nil if no transaction is tracked in the context. -func TransactionFromContext(ctx context.Context) *Span { - if span, ok := ctx.Value(spanContextKey{}).(*Span); ok { - return span.recorder.root() - } - return nil -} - -// SpanFromContext returns the last span stored in the context, or nil if no span -// is set on the context. -func SpanFromContext(ctx context.Context) *Span { - if span, ok := ctx.Value(spanContextKey{}).(*Span); ok { - return span - } - return nil -} - -// StartTransaction will create a transaction (root span) if there's no existing -// transaction in the context otherwise, it will return the existing transaction. -func StartTransaction(ctx context.Context, name string, options ...SpanOption) *Span { - currentTransaction, exists := ctx.Value(spanContextKey{}).(*Span) - if exists { - currentTransaction.ctx = ctx - return currentTransaction - } - - options = append(options, WithTransactionName(name)) - return StartSpan( - ctx, - "", - options..., - ) -} - -// HTTPtoSpanStatus converts an HTTP status code to a SpanStatus. -func HTTPtoSpanStatus(code int) SpanStatus { - if code < http.StatusBadRequest { - return SpanStatusOK - } - if http.StatusBadRequest <= code && code < http.StatusInternalServerError { - switch code { - case http.StatusForbidden: - return SpanStatusPermissionDenied - case http.StatusNotFound: - return SpanStatusNotFound - case http.StatusTooManyRequests: - return SpanStatusResourceExhausted - case http.StatusRequestEntityTooLarge: - return SpanStatusFailedPrecondition - case http.StatusUnauthorized: - return SpanStatusUnauthenticated - case http.StatusConflict: - return SpanStatusAlreadyExists - default: - return SpanStatusInvalidArgument - } - } - if http.StatusInternalServerError <= code && code < 600 { - switch code { - case http.StatusGatewayTimeout: - return SpanStatusDeadlineExceeded - case http.StatusNotImplemented: - return SpanStatusUnimplemented - case http.StatusServiceUnavailable: - return SpanStatusUnavailable - default: - return SpanStatusInternalError - } - } - return SpanStatusUnknown -} diff --git a/vendor/github.com/getsentry/sentry-go/transport.go b/vendor/github.com/getsentry/sentry-go/transport.go deleted file mode 100644 index 417252f83..000000000 --- a/vendor/github.com/getsentry/sentry-go/transport.go +++ /dev/null @@ -1,709 +0,0 @@ -package sentry - -import ( - "bytes" - "context" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "sync" - "time" - - "github.com/getsentry/sentry-go/internal/ratelimit" -) - -const defaultBufferSize = 30 -const defaultTimeout = time.Second * 30 - -// maxDrainResponseBytes is the maximum number of bytes that transport -// implementations will read from response bodies when draining them. -// -// Sentry's ingestion API responses are typically short and the SDK doesn't need -// the contents of the response body. However, the net/http HTTP client requires -// response bodies to be fully drained (and closed) for TCP keep-alive to work. -// -// maxDrainResponseBytes strikes a balance between reading too much data (if the -// server is misbehaving) and reusing TCP connections. -const maxDrainResponseBytes = 16 << 10 - -// Transport is used by the Client to deliver events to remote server. -type Transport interface { - Flush(timeout time.Duration) bool - Configure(options ClientOptions) - SendEvent(event *Event) - Close() -} - -func getProxyConfig(options ClientOptions) func(*http.Request) (*url.URL, error) { - if options.HTTPSProxy != "" { - return func(*http.Request) (*url.URL, error) { - return url.Parse(options.HTTPSProxy) - } - } - - if options.HTTPProxy != "" { - return func(*http.Request) (*url.URL, error) { - return url.Parse(options.HTTPProxy) - } - } - - return http.ProxyFromEnvironment -} - -func getTLSConfig(options ClientOptions) *tls.Config { - if options.CaCerts != nil { - // #nosec G402 -- We should be using `MinVersion: tls.VersionTLS12`, - // but we don't want to break peoples code without the major bump. - return &tls.Config{ - RootCAs: options.CaCerts, - } - } - - return nil -} - -func getRequestBodyFromEvent(event *Event) []byte { - body, err := json.Marshal(event) - if err == nil { - return body - } - - msg := fmt.Sprintf("Could not encode original event as JSON. "+ - "Succeeded by removing Breadcrumbs, Contexts and Extra. "+ - "Please verify the data you attach to the scope. "+ - "Error: %s", err) - // Try to serialize the event, with all the contextual data that allows for interface{} stripped. - event.Breadcrumbs = nil - event.Contexts = nil - event.Extra = map[string]interface{}{ - "info": msg, - } - body, err = json.Marshal(event) - if err == nil { - Logger.Println(msg) - return body - } - - // This should _only_ happen when Event.Exception[0].Stacktrace.Frames[0].Vars is unserializable - // Which won't ever happen, as we don't use it now (although it's the part of public interface accepted by Sentry) - // Juuust in case something, somehow goes utterly wrong. - Logger.Println("Event couldn't be marshaled, even with stripped contextual data. Skipping delivery. " + - "Please notify the SDK owners with possibly broken payload.") - return nil -} - -func encodeAttachment(enc *json.Encoder, b io.Writer, attachment *Attachment) error { - // Attachment header - err := enc.Encode(struct { - Type string `json:"type"` - Length int `json:"length"` - Filename string `json:"filename"` - ContentType string `json:"content_type,omitempty"` - }{ - Type: "attachment", - Length: len(attachment.Payload), - Filename: attachment.Filename, - ContentType: attachment.ContentType, - }) - if err != nil { - return err - } - - // Attachment payload - if _, err = b.Write(attachment.Payload); err != nil { - return err - } - - // "Envelopes should be terminated with a trailing newline." - // - // [1]: https://develop.sentry.dev/sdk/envelopes/#envelopes - if _, err := b.Write([]byte("\n")); err != nil { - return err - } - - return nil -} - -func encodeEnvelopeItem(enc *json.Encoder, itemType string, body json.RawMessage) error { - // Item header - err := enc.Encode(struct { - Type string `json:"type"` - Length int `json:"length"` - }{ - Type: itemType, - Length: len(body), - }) - if err == nil { - // payload - err = enc.Encode(body) - } - return err -} - -func envelopeFromBody(event *Event, dsn *Dsn, sentAt time.Time, body json.RawMessage) (*bytes.Buffer, error) { - var b bytes.Buffer - enc := json.NewEncoder(&b) - - // Construct the trace envelope header - var trace = map[string]string{} - if dsc := event.sdkMetaData.dsc; dsc.HasEntries() { - for k, v := range dsc.Entries { - trace[k] = v - } - } - - // Envelope header - err := enc.Encode(struct { - EventID EventID `json:"event_id"` - SentAt time.Time `json:"sent_at"` - Dsn string `json:"dsn"` - Sdk map[string]string `json:"sdk"` - Trace map[string]string `json:"trace,omitempty"` - }{ - EventID: event.EventID, - SentAt: sentAt, - Trace: trace, - Dsn: dsn.String(), - Sdk: map[string]string{ - "name": event.Sdk.Name, - "version": event.Sdk.Version, - }, - }) - if err != nil { - return nil, err - } - - switch event.Type { - case transactionType, checkInType: - err = encodeEnvelopeItem(enc, event.Type, body) - default: - err = encodeEnvelopeItem(enc, eventType, body) - } - - if err != nil { - return nil, err - } - - // Attachments - for _, attachment := range event.Attachments { - if err := encodeAttachment(enc, &b, attachment); err != nil { - return nil, err - } - } - - return &b, nil -} - -func getRequestFromEvent(ctx context.Context, event *Event, dsn *Dsn) (r *http.Request, err error) { - defer func() { - if r != nil { - r.Header.Set("User-Agent", fmt.Sprintf("%s/%s", event.Sdk.Name, event.Sdk.Version)) - r.Header.Set("Content-Type", "application/x-sentry-envelope") - - auth := fmt.Sprintf("Sentry sentry_version=%s, "+ - "sentry_client=%s/%s, sentry_key=%s", apiVersion, event.Sdk.Name, event.Sdk.Version, dsn.publicKey) - - // The key sentry_secret is effectively deprecated and no longer needs to be set. - // However, since it was required in older self-hosted versions, - // it should still passed through to Sentry if set. - if dsn.secretKey != "" { - auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey) - } - - r.Header.Set("X-Sentry-Auth", auth) - } - }() - - body := getRequestBodyFromEvent(event) - if body == nil { - return nil, errors.New("event could not be marshaled") - } - - envelope, err := envelopeFromBody(event, dsn, time.Now(), body) - if err != nil { - return nil, err - } - - if ctx == nil { - ctx = context.Background() - } - - return http.NewRequestWithContext( - ctx, - http.MethodPost, - dsn.GetAPIURL().String(), - envelope, - ) -} - -func categoryFor(eventType string) ratelimit.Category { - switch eventType { - case "": - return ratelimit.CategoryError - case transactionType: - return ratelimit.CategoryTransaction - default: - return ratelimit.Category(eventType) - } -} - -// ================================ -// HTTPTransport -// ================================ - -// A batch groups items that are processed sequentially. -type batch struct { - items chan batchItem - started chan struct{} // closed to signal items started to be worked on - done chan struct{} // closed to signal completion of all items -} - -type batchItem struct { - request *http.Request - category ratelimit.Category -} - -// HTTPTransport is the default, non-blocking, implementation of Transport. -// -// Clients using this transport will enqueue requests in a buffer and return to -// the caller before any network communication has happened. Requests are sent -// to Sentry sequentially from a background goroutine. -type HTTPTransport struct { - dsn *Dsn - client *http.Client - transport http.RoundTripper - - // buffer is a channel of batches. Calling Flush terminates work on the - // current in-flight items and starts a new batch for subsequent events. - buffer chan batch - - start sync.Once - - // Size of the transport buffer. Defaults to 30. - BufferSize int - // HTTP Client request timeout. Defaults to 30 seconds. - Timeout time.Duration - - mu sync.RWMutex - limits ratelimit.Map - - // receiving signal will terminate worker. - done chan struct{} -} - -// NewHTTPTransport returns a new pre-configured instance of HTTPTransport. -func NewHTTPTransport() *HTTPTransport { - transport := HTTPTransport{ - BufferSize: defaultBufferSize, - Timeout: defaultTimeout, - done: make(chan struct{}), - } - return &transport -} - -// Configure is called by the Client itself, providing it it's own ClientOptions. -func (t *HTTPTransport) Configure(options ClientOptions) { - dsn, err := NewDsn(options.Dsn) - if err != nil { - Logger.Printf("%v\n", err) - return - } - t.dsn = dsn - - // A buffered channel with capacity 1 works like a mutex, ensuring only one - // goroutine can access the current batch at a given time. Access is - // synchronized by reading from and writing to the channel. - t.buffer = make(chan batch, 1) - t.buffer <- batch{ - items: make(chan batchItem, t.BufferSize), - started: make(chan struct{}), - done: make(chan struct{}), - } - - if options.HTTPTransport != nil { - t.transport = options.HTTPTransport - } else { - t.transport = &http.Transport{ - Proxy: getProxyConfig(options), - TLSClientConfig: getTLSConfig(options), - } - } - - if options.HTTPClient != nil { - t.client = options.HTTPClient - } else { - t.client = &http.Client{ - Transport: t.transport, - Timeout: t.Timeout, - } - } - - t.start.Do(func() { - go t.worker() - }) -} - -// SendEvent assembles a new packet out of Event and sends it to the remote server. -func (t *HTTPTransport) SendEvent(event *Event) { - t.SendEventWithContext(context.Background(), event) -} - -// SendEventWithContext assembles a new packet out of Event and sends it to the remote server. -func (t *HTTPTransport) SendEventWithContext(ctx context.Context, event *Event) { - if t.dsn == nil { - return - } - - category := categoryFor(event.Type) - - if t.disabled(category) { - return - } - - request, err := getRequestFromEvent(ctx, event, t.dsn) - if err != nil { - return - } - - // <-t.buffer is equivalent to acquiring a lock to access the current batch. - // A few lines below, t.buffer <- b releases the lock. - // - // The lock must be held during the select block below to guarantee that - // b.items is not closed while trying to send to it. Remember that sending - // on a closed channel panics. - // - // Note that the select block takes a bounded amount of CPU time because of - // the default case that is executed if sending on b.items would block. That - // is, the event is dropped if it cannot be sent immediately to the b.items - // channel (used as a queue). - b := <-t.buffer - - select { - case b.items <- batchItem{ - request: request, - category: category, - }: - var eventType string - if event.Type == transactionType { - eventType = "transaction" - } else { - eventType = fmt.Sprintf("%s event", event.Level) - } - Logger.Printf( - "Sending %s [%s] to %s project: %s", - eventType, - event.EventID, - t.dsn.host, - t.dsn.projectID, - ) - default: - Logger.Println("Event dropped due to transport buffer being full.") - } - - t.buffer <- b -} - -// Flush waits until any buffered events are sent to the Sentry server, blocking -// for at most the given timeout. It returns false if the timeout was reached. -// In that case, some events may not have been sent. -// -// Flush should be called before terminating the program to avoid -// unintentionally dropping events. -// -// Do not call Flush indiscriminately after every call to SendEvent. Instead, to -// have the SDK send events over the network synchronously, configure it to use -// the HTTPSyncTransport in the call to Init. -func (t *HTTPTransport) Flush(timeout time.Duration) bool { - toolate := time.After(timeout) - - // Wait until processing the current batch has started or the timeout. - // - // We must wait until the worker has seen the current batch, because it is - // the only way b.done will be closed. If we do not wait, there is a - // possible execution flow in which b.done is never closed, and the only way - // out of Flush would be waiting for the timeout, which is undesired. - var b batch - for { - select { - case b = <-t.buffer: - select { - case <-b.started: - goto started - default: - t.buffer <- b - } - case <-toolate: - goto fail - } - } - -started: - // Signal that there won't be any more items in this batch, so that the - // worker inner loop can end. - close(b.items) - // Start a new batch for subsequent events. - t.buffer <- batch{ - items: make(chan batchItem, t.BufferSize), - started: make(chan struct{}), - done: make(chan struct{}), - } - - // Wait until the current batch is done or the timeout. - select { - case <-b.done: - Logger.Println("Buffer flushed successfully.") - return true - case <-toolate: - goto fail - } - -fail: - Logger.Println("Buffer flushing reached the timeout.") - return false -} - -// Close will terminate events sending loop. -// It useful to prevent goroutines leak in case of multiple HTTPTransport instances initiated. -// -// Close should be called after Flush and before terminating the program -// otherwise some events may be lost. -func (t *HTTPTransport) Close() { - close(t.done) -} - -func (t *HTTPTransport) worker() { - for b := range t.buffer { - // Signal that processing of the current batch has started. - close(b.started) - - // Return the batch to the buffer so that other goroutines can use it. - // Equivalent to releasing a lock. - t.buffer <- b - - // Process all batch items. - loop: - for { - select { - case <-t.done: - return - case item, open := <-b.items: - if !open { - break loop - } - if t.disabled(item.category) { - continue - } - - response, err := t.client.Do(item.request) - if err != nil { - Logger.Printf("There was an issue with sending an event: %v", err) - continue - } - if response.StatusCode >= 400 && response.StatusCode <= 599 { - b, err := io.ReadAll(response.Body) - if err != nil { - Logger.Printf("Error while reading response code: %v", err) - } - Logger.Printf("Sending %s failed with the following error: %s", eventType, string(b)) - } - - t.mu.Lock() - if t.limits == nil { - t.limits = make(ratelimit.Map) - } - t.limits.Merge(ratelimit.FromResponse(response)) - t.mu.Unlock() - - // Drain body up to a limit and close it, allowing the - // transport to reuse TCP connections. - _, _ = io.CopyN(io.Discard, response.Body, maxDrainResponseBytes) - response.Body.Close() - } - } - - // Signal that processing of the batch is done. - close(b.done) - } -} - -func (t *HTTPTransport) disabled(c ratelimit.Category) bool { - t.mu.RLock() - defer t.mu.RUnlock() - disabled := t.limits.IsRateLimited(c) - if disabled { - Logger.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) - } - return disabled -} - -// ================================ -// HTTPSyncTransport -// ================================ - -// HTTPSyncTransport is a blocking implementation of Transport. -// -// Clients using this transport will send requests to Sentry sequentially and -// block until a response is returned. -// -// The blocking behavior is useful in a limited set of use cases. For example, -// use it when deploying code to a Function as a Service ("Serverless") -// platform, where any work happening in a background goroutine is not -// guaranteed to execute. -// -// For most cases, prefer HTTPTransport. -type HTTPSyncTransport struct { - dsn *Dsn - client *http.Client - transport http.RoundTripper - - mu sync.Mutex - limits ratelimit.Map - - // HTTP Client request timeout. Defaults to 30 seconds. - Timeout time.Duration -} - -// NewHTTPSyncTransport returns a new pre-configured instance of HTTPSyncTransport. -func NewHTTPSyncTransport() *HTTPSyncTransport { - transport := HTTPSyncTransport{ - Timeout: defaultTimeout, - limits: make(ratelimit.Map), - } - - return &transport -} - -// Configure is called by the Client itself, providing it it's own ClientOptions. -func (t *HTTPSyncTransport) Configure(options ClientOptions) { - dsn, err := NewDsn(options.Dsn) - if err != nil { - Logger.Printf("%v\n", err) - return - } - t.dsn = dsn - - if options.HTTPTransport != nil { - t.transport = options.HTTPTransport - } else { - t.transport = &http.Transport{ - Proxy: getProxyConfig(options), - TLSClientConfig: getTLSConfig(options), - } - } - - if options.HTTPClient != nil { - t.client = options.HTTPClient - } else { - t.client = &http.Client{ - Transport: t.transport, - Timeout: t.Timeout, - } - } -} - -// SendEvent assembles a new packet out of Event and sends it to the remote server. -func (t *HTTPSyncTransport) SendEvent(event *Event) { - t.SendEventWithContext(context.Background(), event) -} - -func (t *HTTPSyncTransport) Close() {} - -// SendEventWithContext assembles a new packet out of Event and sends it to the remote server. -func (t *HTTPSyncTransport) SendEventWithContext(ctx context.Context, event *Event) { - if t.dsn == nil { - return - } - - if t.disabled(categoryFor(event.Type)) { - return - } - - request, err := getRequestFromEvent(ctx, event, t.dsn) - if err != nil { - return - } - - var eventType string - switch { - case event.Type == transactionType: - eventType = "transaction" - default: - eventType = fmt.Sprintf("%s event", event.Level) - } - Logger.Printf( - "Sending %s [%s] to %s project: %s", - eventType, - event.EventID, - t.dsn.host, - t.dsn.projectID, - ) - - response, err := t.client.Do(request) - if err != nil { - Logger.Printf("There was an issue with sending an event: %v", err) - return - } - if response.StatusCode >= 400 && response.StatusCode <= 599 { - b, err := io.ReadAll(response.Body) - if err != nil { - Logger.Printf("Error while reading response code: %v", err) - } - Logger.Printf("Sending %s failed with the following error: %s", eventType, string(b)) - } - - t.mu.Lock() - if t.limits == nil { - t.limits = make(ratelimit.Map) - } - - t.limits.Merge(ratelimit.FromResponse(response)) - t.mu.Unlock() - - // Drain body up to a limit and close it, allowing the - // transport to reuse TCP connections. - _, _ = io.CopyN(io.Discard, response.Body, maxDrainResponseBytes) - response.Body.Close() -} - -// Flush is a no-op for HTTPSyncTransport. It always returns true immediately. -func (t *HTTPSyncTransport) Flush(_ time.Duration) bool { - return true -} - -func (t *HTTPSyncTransport) disabled(c ratelimit.Category) bool { - t.mu.Lock() - defer t.mu.Unlock() - disabled := t.limits.IsRateLimited(c) - if disabled { - Logger.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) - } - return disabled -} - -// ================================ -// noopTransport -// ================================ - -// noopTransport is an implementation of Transport interface which drops all the events. -// Only used internally when an empty DSN is provided, which effectively disables the SDK. -type noopTransport struct{} - -var _ Transport = noopTransport{} - -func (noopTransport) Configure(ClientOptions) { - Logger.Println("Sentry client initialized with an empty DSN. Using noopTransport. No events will be delivered.") -} - -func (noopTransport) SendEvent(*Event) { - Logger.Println("Event dropped due to noopTransport usage.") -} - -func (noopTransport) Flush(time.Duration) bool { - return true -} - -func (noopTransport) Close() {} diff --git a/vendor/github.com/getsentry/sentry-go/util.go b/vendor/github.com/getsentry/sentry-go/util.go deleted file mode 100644 index 8f999ed7b..000000000 --- a/vendor/github.com/getsentry/sentry-go/util.go +++ /dev/null @@ -1,118 +0,0 @@ -package sentry - -import ( - "crypto/rand" - "encoding/hex" - "encoding/json" - "fmt" - "os" - "runtime/debug" - "strings" - "time" - - exec "golang.org/x/sys/execabs" -) - -func uuid() string { - id := make([]byte, 16) - // Prefer rand.Read over rand.Reader, see https://go-review.googlesource.com/c/go/+/272326/. - _, _ = rand.Read(id) - id[6] &= 0x0F // clear version - id[6] |= 0x40 // set version to 4 (random uuid) - id[8] &= 0x3F // clear variant - id[8] |= 0x80 // set to IETF variant - return hex.EncodeToString(id) -} - -func fileExists(fileName string) bool { - _, err := os.Stat(fileName) - return err == nil -} - -// monotonicTimeSince replaces uses of time.Now() to take into account the -// monotonic clock reading stored in start, such that duration = end - start is -// unaffected by changes in the system wall clock. -func monotonicTimeSince(start time.Time) (end time.Time) { - return start.Add(time.Since(start)) -} - -// nolint: deadcode, unused -func prettyPrint(data interface{}) { - dbg, _ := json.MarshalIndent(data, "", " ") - fmt.Println(string(dbg)) -} - -// defaultRelease attempts to guess a default release for the currently running -// program. -func defaultRelease() (release string) { - // Return first non-empty environment variable known to hold release info, if any. - envs := []string{ - "SENTRY_RELEASE", - "HEROKU_SLUG_COMMIT", - "SOURCE_VERSION", - "CODEBUILD_RESOLVED_SOURCE_VERSION", - "CIRCLE_SHA1", - "GAE_DEPLOYMENT_ID", - "GITHUB_SHA", // GitHub Actions - https://help.github.com/en/actions - "COMMIT_REF", // Netlify - https://docs.netlify.com/ - "VERCEL_GIT_COMMIT_SHA", // Vercel - https://vercel.com/ - "ZEIT_GITHUB_COMMIT_SHA", // Zeit (now known as Vercel) - "ZEIT_GITLAB_COMMIT_SHA", - "ZEIT_BITBUCKET_COMMIT_SHA", - } - for _, e := range envs { - if release = os.Getenv(e); release != "" { - Logger.Printf("Using release from environment variable %s: %s", e, release) - return release - } - } - - if info, ok := debug.ReadBuildInfo(); ok { - buildInfoVcsRevision := revisionFromBuildInfo(info) - if len(buildInfoVcsRevision) > 0 { - return buildInfoVcsRevision - } - } - - // Derive a version string from Git. Example outputs: - // v1.0.1-0-g9de4 - // v2.0-8-g77df-dirty - // 4f72d7 - if _, err := exec.LookPath("git"); err == nil { - cmd := exec.Command("git", "describe", "--long", "--always", "--dirty") - b, err := cmd.Output() - if err != nil { - // Either Git is not available or the current directory is not a - // Git repository. - var s strings.Builder - fmt.Fprintf(&s, "Release detection failed: %v", err) - if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 { - fmt.Fprintf(&s, ": %s", err.Stderr) - } - Logger.Print(s.String()) - } else { - release = strings.TrimSpace(string(b)) - Logger.Printf("Using release from Git: %s", release) - return release - } - } - - Logger.Print("Some Sentry features will not be available. See https://docs.sentry.io/product/releases/.") - Logger.Print("To stop seeing this message, pass a Release to sentry.Init or set the SENTRY_RELEASE environment variable.") - return "" -} - -func revisionFromBuildInfo(info *debug.BuildInfo) string { - for _, setting := range info.Settings { - if setting.Key == "vcs.revision" && setting.Value != "" { - Logger.Printf("Using release from debug info: %s", setting.Value) - return setting.Value - } - } - - return "" -} - -func Pointer[T any](v T) *T { - return &v -} diff --git a/vendor/github.com/go-openapi/jsonpointer/.editorconfig b/vendor/github.com/go-openapi/jsonpointer/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/jsonpointer/.gitignore b/vendor/github.com/go-openapi/jsonpointer/.gitignore deleted file mode 100644 index 769c24400..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -secrets.yml diff --git a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml b/vendor/github.com/go-openapi/jsonpointer/.golangci.yml deleted file mode 100644 index 22f8d21cc..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.golangci.yml +++ /dev/null @@ -1,61 +0,0 @@ -linters-settings: - govet: - check-shadowing: true - golint: - min-confidence: 0 - gocyclo: - min-complexity: 45 - maligned: - suggest-new: true - dupl: - threshold: 200 - goconst: - min-len: 2 - min-occurrences: 3 - -linters: - enable-all: true - disable: - - maligned - - unparam - - lll - - gochecknoinits - - gochecknoglobals - - funlen - - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage - - nlreturn - - gomnd - - exhaustivestruct - - goerr113 - - errorlint - - nestif - - godot - - gofumpt - - paralleltest - - tparallel - - thelper - - ifshort - - exhaustruct - - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - - deadcode - - interfacer - - scopelint - - varcheck - - structcheck - - golint - - nosnakecase diff --git a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonpointer/LICENSE b/vendor/github.com/go-openapi/jsonpointer/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/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/vendor/github.com/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md deleted file mode 100644 index 0108f1d57..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# gojsonpointer [![Build Status](https://github.com/go-openapi/jsonpointer/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/jsonpointer/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) - -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonpointer/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/jsonpointer.svg)](https://pkg.go.dev/github.com/go-openapi/jsonpointer) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/jsonpointer)](https://goreportcard.com/report/github.com/go-openapi/jsonpointer) - -An implementation of JSON Pointer - Go language - -## Status -Completed YES - -Tested YES - -## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 - -### Note -The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go deleted file mode 100644 index d970c7cf4..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ /dev/null @@ -1,531 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonpointer -// repository-desc An implementation of JSON Pointer - Go language -// -// description Main and unique file. -// -// created 25-02-2013 - -package jsonpointer - -import ( - "encoding/json" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - - "github.com/go-openapi/swag" -) - -const ( - emptyPointer = `` - pointerSeparator = `/` - - invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator - notFound = `Can't find the pointer in the document` -) - -var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() -var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() - -// JSONPointable is an interface for structs to implement when they need to customize the -// json pointer process -type JSONPointable interface { - JSONLookup(string) (any, error) -} - -// JSONSetable is an interface for structs to implement when they need to customize the -// json pointer process -type JSONSetable interface { - JSONSet(string, any) error -} - -// New creates a new json pointer for the given string -func New(jsonPointerString string) (Pointer, error) { - - var p Pointer - err := p.parse(jsonPointerString) - return p, err - -} - -// Pointer the json pointer reprsentation -type Pointer struct { - referenceTokens []string -} - -// "Constructor", parses the given string JSON pointer -func (p *Pointer) parse(jsonPointerString string) error { - - var err error - - if jsonPointerString != emptyPointer { - if !strings.HasPrefix(jsonPointerString, pointerSeparator) { - err = errors.New(invalidStart) - } else { - referenceTokens := strings.Split(jsonPointerString, pointerSeparator) - p.referenceTokens = append(p.referenceTokens, referenceTokens[1:]...) - } - } - - return err -} - -// Get uses the pointer to retrieve a value from a JSON document -func (p *Pointer) Get(document any) (any, reflect.Kind, error) { - return p.get(document, swag.DefaultJSONNameProvider) -} - -// Set uses the pointer to set a value from a JSON document -func (p *Pointer) Set(document any, value any) (any, error) { - return document, p.set(document, value, swag.DefaultJSONNameProvider) -} - -// GetForToken gets a value for a json pointer token 1 level deep -func GetForToken(document any, decodedToken string) (any, reflect.Kind, error) { - return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) -} - -// SetForToken gets a value for a json pointer token 1 level deep -func SetForToken(document any, decodedToken string, value any) (any, error) { - return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) -} - -func isNil(input any) bool { - if input == nil { - return true - } - - kind := reflect.TypeOf(input).Kind() - switch kind { //nolint:exhaustive - case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: - return reflect.ValueOf(input).IsNil() - default: - return false - } -} - -func getSingleImpl(node any, decodedToken string, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - if isNil(node) { - return nil, kind, fmt.Errorf("nil value has not field %q", decodedToken) - } - - switch typed := node.(type) { - case JSONPointable: - r, err := typed.JSONLookup(decodedToken) - if err != nil { - return nil, kind, err - } - return r, kind, nil - case *any: // case of a pointer to interface, that is not resolved by reflect.Indirect - return getSingleImpl(*typed, decodedToken, nameProvider) - } - - switch kind { //nolint:exhaustive - case reflect.Struct: - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return nil, kind, fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - return fld.Interface(), kind, nil - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if mv.IsValid() { - return mv.Interface(), kind, nil - } - return nil, kind, fmt.Errorf("object has no key %q", decodedToken) - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return nil, kind, err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength-1, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - return elem.Interface(), kind, nil - - default: - return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken) - } - -} - -func setSingleImpl(node, data any, decodedToken string, nameProvider *swag.NameProvider) error { - rValue := reflect.Indirect(reflect.ValueOf(node)) - - if ns, ok := node.(JSONSetable); ok { // pointer impl - return ns.JSONSet(decodedToken, data) - } - - if rValue.Type().Implements(jsonSetableType) { - return node.(JSONSetable).JSONSet(decodedToken, data) - } - - switch rValue.Kind() { //nolint:exhaustive - case reflect.Struct: - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - if fld.IsValid() { - fld.Set(reflect.ValueOf(data)) - } - return nil - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - rValue.SetMapIndex(kv, reflect.ValueOf(data)) - return nil - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - if !elem.CanSet() { - return fmt.Errorf("can't set slice index %s to %v", decodedToken, data) - } - elem.Set(reflect.ValueOf(data)) - return nil - - default: - return fmt.Errorf("invalid token reference %q", decodedToken) - } - -} - -func (p *Pointer) get(node any, nameProvider *swag.NameProvider) (any, reflect.Kind, error) { - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - kind := reflect.Invalid - - // Full document when empty - if len(p.referenceTokens) == 0 { - return node, kind, nil - } - - for _, token := range p.referenceTokens { - - decodedToken := Unescape(token) - - r, knd, err := getSingleImpl(node, decodedToken, nameProvider) - if err != nil { - return nil, knd, err - } - node = r - } - - rValue := reflect.ValueOf(node) - kind = rValue.Kind() - - return node, kind, nil -} - -func (p *Pointer) set(node, data any, nameProvider *swag.NameProvider) error { - knd := reflect.ValueOf(node).Kind() - - if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { - return errors.New("only structs, pointers, maps and slices are supported for setting values") - } - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - // Full document when empty - if len(p.referenceTokens) == 0 { - return nil - } - - lastI := len(p.referenceTokens) - 1 - for i, token := range p.referenceTokens { - isLastToken := i == lastI - decodedToken := Unescape(token) - - if isLastToken { - - return setSingleImpl(node, data, decodedToken, nameProvider) - } - - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - - if rValue.Type().Implements(jsonPointableType) { - r, err := node.(JSONPointable).JSONLookup(decodedToken) - if err != nil { - return err - } - fld := reflect.ValueOf(r) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = r - continue - } - - switch kind { //nolint:exhaustive - case reflect.Struct: - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = fld.Interface() - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if !mv.IsValid() { - return fmt.Errorf("object has no key %q", decodedToken) - } - if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr { - node = mv.Addr().Interface() - continue - } - node = mv.Interface() - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr { - node = elem.Addr().Interface() - continue - } - node = elem.Interface() - - default: - return fmt.Errorf("invalid token reference %q", decodedToken) - } - - } - - return nil -} - -// DecodedTokens returns the decoded tokens -func (p *Pointer) DecodedTokens() []string { - result := make([]string, 0, len(p.referenceTokens)) - for _, t := range p.referenceTokens { - result = append(result, Unescape(t)) - } - return result -} - -// IsEmpty returns true if this is an empty json pointer -// this indicates that it points to the root document -func (p *Pointer) IsEmpty() bool { - return len(p.referenceTokens) == 0 -} - -// Pointer to string representation function -func (p *Pointer) String() string { - - if len(p.referenceTokens) == 0 { - return emptyPointer - } - - pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) - - return pointerString -} - -func (p *Pointer) Offset(document string) (int64, error) { - dec := json.NewDecoder(strings.NewReader(document)) - var offset int64 - for _, ttk := range p.DecodedTokens() { - tk, err := dec.Token() - if err != nil { - return 0, err - } - switch tk := tk.(type) { - case json.Delim: - switch tk { - case '{': - offset, err = offsetSingleObject(dec, ttk) - if err != nil { - return 0, err - } - case '[': - offset, err = offsetSingleArray(dec, ttk) - if err != nil { - return 0, err - } - default: - return 0, fmt.Errorf("invalid token %#v", tk) - } - default: - return 0, fmt.Errorf("invalid token %#v", tk) - } - } - return offset, nil -} - -func offsetSingleObject(dec *json.Decoder, decodedToken string) (int64, error) { - for dec.More() { - offset := dec.InputOffset() - tk, err := dec.Token() - if err != nil { - return 0, err - } - switch tk := tk.(type) { - case json.Delim: - switch tk { - case '{': - if err = drainSingle(dec); err != nil { - return 0, err - } - case '[': - if err = drainSingle(dec); err != nil { - return 0, err - } - } - case string: - if tk == decodedToken { - return offset, nil - } - default: - return 0, fmt.Errorf("invalid token %#v", tk) - } - } - return 0, fmt.Errorf("token reference %q not found", decodedToken) -} - -func offsetSingleArray(dec *json.Decoder, decodedToken string) (int64, error) { - idx, err := strconv.Atoi(decodedToken) - if err != nil { - return 0, fmt.Errorf("token reference %q is not a number: %v", decodedToken, err) - } - var i int - for i = 0; i < idx && dec.More(); i++ { - tk, err := dec.Token() - if err != nil { - return 0, err - } - - if delim, isDelim := tk.(json.Delim); isDelim { - switch delim { - case '{': - if err = drainSingle(dec); err != nil { - return 0, err - } - case '[': - if err = drainSingle(dec); err != nil { - return 0, err - } - } - } - } - - if !dec.More() { - return 0, fmt.Errorf("token reference %q not found", decodedToken) - } - return dec.InputOffset(), nil -} - -// drainSingle drains a single level of object or array. -// The decoder has to guarantee the beginning delim (i.e. '{' or '[') has been consumed. -func drainSingle(dec *json.Decoder) error { - for dec.More() { - tk, err := dec.Token() - if err != nil { - return err - } - if delim, isDelim := tk.(json.Delim); isDelim { - switch delim { - case '{': - if err = drainSingle(dec); err != nil { - return err - } - case '[': - if err = drainSingle(dec); err != nil { - return err - } - } - } - } - - // Consumes the ending delim - if _, err := dec.Token(); err != nil { - return err - } - return nil -} - -// Specific JSON pointer encoding here -// ~0 => ~ -// ~1 => / -// ... and vice versa - -const ( - encRefTok0 = `~0` - encRefTok1 = `~1` - decRefTok0 = `~` - decRefTok1 = `/` -) - -// Unescape unescapes a json pointer reference token string to the original representation -func Unescape(token string) string { - step1 := strings.ReplaceAll(token, encRefTok1, decRefTok1) - step2 := strings.ReplaceAll(step1, encRefTok0, decRefTok0) - return step2 -} - -// Escape escapes a pointer reference token string -func Escape(token string) string { - step1 := strings.ReplaceAll(token, decRefTok0, encRefTok0) - step2 := strings.ReplaceAll(step1, decRefTok1, encRefTok1) - return step2 -} diff --git a/vendor/github.com/go-openapi/swag/.editorconfig b/vendor/github.com/go-openapi/swag/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/swag/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/swag/.gitattributes b/vendor/github.com/go-openapi/swag/.gitattributes deleted file mode 100644 index 49ad52766..000000000 --- a/vendor/github.com/go-openapi/swag/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# gofmt always uses LF, whereas Git uses CRLF on Windows. -*.go text eol=lf diff --git a/vendor/github.com/go-openapi/swag/.gitignore b/vendor/github.com/go-openapi/swag/.gitignore deleted file mode 100644 index c4b1b64f0..000000000 --- a/vendor/github.com/go-openapi/swag/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -secrets.yml -vendor -Godeps -.idea -*.out diff --git a/vendor/github.com/go-openapi/swag/.golangci.yml b/vendor/github.com/go-openapi/swag/.golangci.yml deleted file mode 100644 index 80e2be004..000000000 --- a/vendor/github.com/go-openapi/swag/.golangci.yml +++ /dev/null @@ -1,60 +0,0 @@ -linters-settings: - govet: - check-shadowing: true - golint: - min-confidence: 0 - gocyclo: - min-complexity: 45 - maligned: - suggest-new: true - dupl: - threshold: 200 - goconst: - min-len: 3 - min-occurrences: 3 - -linters: - enable-all: true - disable: - - maligned - - lll - - gochecknoinits - - gochecknoglobals - - funlen - - godox - - gocognit - - whitespace - - wsl - - wrapcheck - - testpackage - - nlreturn - - gomnd - - exhaustivestruct - - goerr113 - - errorlint - - nestif - - godot - - gofumpt - - paralleltest - - tparallel - - thelper - - ifshort - - exhaustruct - - varnamelen - - gci - - depguard - - errchkjson - - inamedparam - - nonamedreturns - - musttag - - ireturn - - forcetypeassert - - cyclop - # deprecated linters - - deadcode - - interfacer - - scopelint - - varcheck - - structcheck - - golint - - nosnakecase diff --git a/vendor/github.com/go-openapi/swag/BENCHMARK.md b/vendor/github.com/go-openapi/swag/BENCHMARK.md deleted file mode 100644 index e7f28ed6b..000000000 --- a/vendor/github.com/go-openapi/swag/BENCHMARK.md +++ /dev/null @@ -1,52 +0,0 @@ -# Benchmarks - -## Name mangling utilities - -```bash -go test -bench XXX -run XXX -benchtime 30s -``` - -### Benchmarks at b3e7a5386f996177e4808f11acb2aa93a0f660df - -``` -goos: linux -goarch: amd64 -pkg: github.com/go-openapi/swag -cpu: Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz -BenchmarkToXXXName/ToGoName-4 862623 44101 ns/op 10450 B/op 732 allocs/op -BenchmarkToXXXName/ToVarName-4 853656 40728 ns/op 10468 B/op 734 allocs/op -BenchmarkToXXXName/ToFileName-4 1268312 27813 ns/op 9785 B/op 617 allocs/op -BenchmarkToXXXName/ToCommandName-4 1276322 27903 ns/op 9785 B/op 617 allocs/op -BenchmarkToXXXName/ToHumanNameLower-4 895334 40354 ns/op 10472 B/op 731 allocs/op -BenchmarkToXXXName/ToHumanNameTitle-4 882441 40678 ns/op 10566 B/op 749 allocs/op -``` - -### Benchmarks after PR #79 - -~ x10 performance improvement and ~ /100 memory allocations. - -``` -goos: linux -goarch: amd64 -pkg: github.com/go-openapi/swag -cpu: Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz -BenchmarkToXXXName/ToGoName-4 9595830 3991 ns/op 42 B/op 5 allocs/op -BenchmarkToXXXName/ToVarName-4 9194276 3984 ns/op 62 B/op 7 allocs/op -BenchmarkToXXXName/ToFileName-4 17002711 2123 ns/op 147 B/op 7 allocs/op -BenchmarkToXXXName/ToCommandName-4 16772926 2111 ns/op 147 B/op 7 allocs/op -BenchmarkToXXXName/ToHumanNameLower-4 9788331 3749 ns/op 92 B/op 6 allocs/op -BenchmarkToXXXName/ToHumanNameTitle-4 9188260 3941 ns/op 104 B/op 6 allocs/op -``` - -``` -goos: linux -goarch: amd64 -pkg: github.com/go-openapi/swag -cpu: AMD Ryzen 7 5800X 8-Core Processor -BenchmarkToXXXName/ToGoName-16 18527378 1972 ns/op 42 B/op 5 allocs/op -BenchmarkToXXXName/ToVarName-16 15552692 2093 ns/op 62 B/op 7 allocs/op -BenchmarkToXXXName/ToFileName-16 32161176 1117 ns/op 147 B/op 7 allocs/op -BenchmarkToXXXName/ToCommandName-16 32256634 1137 ns/op 147 B/op 7 allocs/op -BenchmarkToXXXName/ToHumanNameLower-16 18599661 1946 ns/op 92 B/op 6 allocs/op -BenchmarkToXXXName/ToHumanNameTitle-16 17581353 2054 ns/op 105 B/op 6 allocs/op -``` diff --git a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/swag/LICENSE b/vendor/github.com/go-openapi/swag/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/swag/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/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md deleted file mode 100644 index a72922299..000000000 --- a/vendor/github.com/go-openapi/swag/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Swag [![Build Status](https://github.com/go-openapi/swag/actions/workflows/go-test.yml/badge.svg)](https://github.com/go-openapi/swag/actions?query=workflow%3A"go+test") [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) - -[![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) -[![Go Reference](https://pkg.go.dev/badge/github.com/go-openapi/swag.svg)](https://pkg.go.dev/github.com/go-openapi/swag) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/swag)](https://goreportcard.com/report/github.com/go-openapi/swag) - -Contains a bunch of helper functions for go-openapi and go-swagger projects. - -You may also use it standalone for your projects. - -* convert between value and pointers for builtin types -* convert from string to builtin types (wraps strconv) -* fast json concatenation -* search in path -* load from file or http -* name mangling - - -This repo has only few dependencies outside of the standard library: - -* YAML utilities depend on `gopkg.in/yaml.v3` -* `github.com/mailru/easyjson v0.7.7` diff --git a/vendor/github.com/go-openapi/swag/convert.go b/vendor/github.com/go-openapi/swag/convert.go deleted file mode 100644 index fc085aeb8..000000000 --- a/vendor/github.com/go-openapi/swag/convert.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "math" - "strconv" - "strings" -) - -// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER -const ( - maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 - minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 - epsilon float64 = 1e-9 -) - -// IsFloat64AJSONInteger allow for integers [-2^53, 2^53-1] inclusive -func IsFloat64AJSONInteger(f float64) bool { - if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { - return false - } - fa := math.Abs(f) - g := float64(uint64(f)) - ga := math.Abs(g) - - diff := math.Abs(f - g) - - // more info: https://floating-point-gui.de/errors/comparison/#look-out-for-edge-cases - switch { - case f == g: // best case - return true - case f == float64(int64(f)) || f == float64(uint64(f)): // optimistic case - return true - case f == 0 || g == 0 || diff < math.SmallestNonzeroFloat64: // very close to 0 values - return diff < (epsilon * math.SmallestNonzeroFloat64) - } - // check the relative error - return diff/math.Min(fa+ga, math.MaxFloat64) < epsilon -} - -var evaluatesAsTrue map[string]struct{} - -func init() { - evaluatesAsTrue = map[string]struct{}{ - "true": {}, - "1": {}, - "yes": {}, - "ok": {}, - "y": {}, - "on": {}, - "selected": {}, - "checked": {}, - "t": {}, - "enabled": {}, - } -} - -// ConvertBool turn a string into a boolean -func ConvertBool(str string) (bool, error) { - _, ok := evaluatesAsTrue[strings.ToLower(str)] - return ok, nil -} - -// ConvertFloat32 turn a string into a float32 -func ConvertFloat32(str string) (float32, error) { - f, err := strconv.ParseFloat(str, 32) - if err != nil { - return 0, err - } - return float32(f), nil -} - -// ConvertFloat64 turn a string into a float64 -func ConvertFloat64(str string) (float64, error) { - return strconv.ParseFloat(str, 64) -} - -// ConvertInt8 turn a string into an int8 -func ConvertInt8(str string) (int8, error) { - i, err := strconv.ParseInt(str, 10, 8) - if err != nil { - return 0, err - } - return int8(i), nil -} - -// ConvertInt16 turn a string into an int16 -func ConvertInt16(str string) (int16, error) { - i, err := strconv.ParseInt(str, 10, 16) - if err != nil { - return 0, err - } - return int16(i), nil -} - -// ConvertInt32 turn a string into an int32 -func ConvertInt32(str string) (int32, error) { - i, err := strconv.ParseInt(str, 10, 32) - if err != nil { - return 0, err - } - return int32(i), nil -} - -// ConvertInt64 turn a string into an int64 -func ConvertInt64(str string) (int64, error) { - return strconv.ParseInt(str, 10, 64) -} - -// ConvertUint8 turn a string into an uint8 -func ConvertUint8(str string) (uint8, error) { - i, err := strconv.ParseUint(str, 10, 8) - if err != nil { - return 0, err - } - return uint8(i), nil -} - -// ConvertUint16 turn a string into an uint16 -func ConvertUint16(str string) (uint16, error) { - i, err := strconv.ParseUint(str, 10, 16) - if err != nil { - return 0, err - } - return uint16(i), nil -} - -// ConvertUint32 turn a string into an uint32 -func ConvertUint32(str string) (uint32, error) { - i, err := strconv.ParseUint(str, 10, 32) - if err != nil { - return 0, err - } - return uint32(i), nil -} - -// ConvertUint64 turn a string into an uint64 -func ConvertUint64(str string) (uint64, error) { - return strconv.ParseUint(str, 10, 64) -} - -// FormatBool turns a boolean into a string -func FormatBool(value bool) string { - return strconv.FormatBool(value) -} - -// FormatFloat32 turns a float32 into a string -func FormatFloat32(value float32) string { - return strconv.FormatFloat(float64(value), 'f', -1, 32) -} - -// FormatFloat64 turns a float64 into a string -func FormatFloat64(value float64) string { - return strconv.FormatFloat(value, 'f', -1, 64) -} - -// FormatInt8 turns an int8 into a string -func FormatInt8(value int8) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt16 turns an int16 into a string -func FormatInt16(value int16) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt32 turns an int32 into a string -func FormatInt32(value int32) string { - return strconv.Itoa(int(value)) -} - -// FormatInt64 turns an int64 into a string -func FormatInt64(value int64) string { - return strconv.FormatInt(value, 10) -} - -// FormatUint8 turns an uint8 into a string -func FormatUint8(value uint8) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint16 turns an uint16 into a string -func FormatUint16(value uint16) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint32 turns an uint32 into a string -func FormatUint32(value uint32) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint64 turns an uint64 into a string -func FormatUint64(value uint64) string { - return strconv.FormatUint(value, 10) -} diff --git a/vendor/github.com/go-openapi/swag/convert_types.go b/vendor/github.com/go-openapi/swag/convert_types.go deleted file mode 100644 index c49cc473a..000000000 --- a/vendor/github.com/go-openapi/swag/convert_types.go +++ /dev/null @@ -1,730 +0,0 @@ -package swag - -import "time" - -// This file was taken from the aws go sdk - -// String returns a pointer to of the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to of the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to of the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int32 returns a pointer to of the int32 value passed in. -func Int32(v int32) *int32 { - return &v -} - -// Int32Value returns the value of the int32 pointer passed in or -// 0 if the pointer is nil. -func Int32Value(v *int32) int32 { - if v != nil { - return *v - } - return 0 -} - -// Int32Slice converts a slice of int32 values into a slice of -// int32 pointers -func Int32Slice(src []int32) []*int32 { - dst := make([]*int32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int32ValueSlice converts a slice of int32 pointers into a slice of -// int32 values -func Int32ValueSlice(src []*int32) []int32 { - dst := make([]int32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int32Map converts a string map of int32 values into a string -// map of int32 pointers -func Int32Map(src map[string]int32) map[string]*int32 { - dst := make(map[string]*int32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int32ValueMap converts a string map of int32 pointers into a string -// map of int32 values -func Int32ValueMap(src map[string]*int32) map[string]int32 { - dst := make(map[string]int32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to of the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint16 returns a pointer to of the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return &v -} - -// Uint16Value returns the value of the uint16 pointer passed in or -// 0 if the pointer is nil. -func Uint16Value(v *uint16) uint16 { - if v != nil { - return *v - } - - return 0 -} - -// Uint16Slice converts a slice of uint16 values into a slice of -// uint16 pointers -func Uint16Slice(src []uint16) []*uint16 { - dst := make([]*uint16, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - - return dst -} - -// Uint16ValueSlice converts a slice of uint16 pointers into a slice of -// uint16 values -func Uint16ValueSlice(src []*uint16) []uint16 { - dst := make([]uint16, len(src)) - - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - - return dst -} - -// Uint16Map converts a string map of uint16 values into a string -// map of uint16 pointers -func Uint16Map(src map[string]uint16) map[string]*uint16 { - dst := make(map[string]*uint16) - - for k, val := range src { - v := val - dst[k] = &v - } - - return dst -} - -// Uint16ValueMap converts a string map of uint16 pointers into a string -// map of uint16 values -func Uint16ValueMap(src map[string]*uint16) map[string]uint16 { - dst := make(map[string]uint16) - - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - - return dst -} - -// Uint returns a pointer to of the uint value passed in. -func Uint(v uint) *uint { - return &v -} - -// UintValue returns the value of the uint pointer passed in or -// 0 if the pointer is nil. -func UintValue(v *uint) uint { - if v != nil { - return *v - } - return 0 -} - -// UintSlice converts a slice of uint values into a slice of -// uint pointers -func UintSlice(src []uint) []*uint { - dst := make([]*uint, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// UintValueSlice converts a slice of uint pointers into a slice of -// uint values -func UintValueSlice(src []*uint) []uint { - dst := make([]uint, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// UintMap converts a string map of uint values into a string -// map of uint pointers -func UintMap(src map[string]uint) map[string]*uint { - dst := make(map[string]*uint) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// UintValueMap converts a string map of uint pointers into a string -// map of uint values -func UintValueMap(src map[string]*uint) map[string]uint { - dst := make(map[string]uint) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint32 returns a pointer to of the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint32Value returns the value of the uint32 pointer passed in or -// 0 if the pointer is nil. -func Uint32Value(v *uint32) uint32 { - if v != nil { - return *v - } - return 0 -} - -// Uint32Slice converts a slice of uint32 values into a slice of -// uint32 pointers -func Uint32Slice(src []uint32) []*uint32 { - dst := make([]*uint32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint32ValueSlice converts a slice of uint32 pointers into a slice of -// uint32 values -func Uint32ValueSlice(src []*uint32) []uint32 { - dst := make([]uint32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint32Map converts a string map of uint32 values into a string -// map of uint32 pointers -func Uint32Map(src map[string]uint32) map[string]*uint32 { - dst := make(map[string]*uint32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint32ValueMap converts a string map of uint32 pointers into a string -// map of uint32 values -func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { - dst := make(map[string]uint32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint64 returns a pointer to of the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return &v -} - -// Uint64Value returns the value of the uint64 pointer passed in or -// 0 if the pointer is nil. -func Uint64Value(v *uint64) uint64 { - if v != nil { - return *v - } - return 0 -} - -// Uint64Slice converts a slice of uint64 values into a slice of -// uint64 pointers -func Uint64Slice(src []uint64) []*uint64 { - dst := make([]*uint64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint64ValueSlice converts a slice of uint64 pointers into a slice of -// uint64 values -func Uint64ValueSlice(src []*uint64) []uint64 { - dst := make([]uint64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint64Map converts a string map of uint64 values into a string -// map of uint64 pointers -func Uint64Map(src map[string]uint64) map[string]*uint64 { - dst := make(map[string]*uint64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint64ValueMap converts a string map of uint64 pointers into a string -// map of uint64 values -func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { - dst := make(map[string]uint64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float32 returns a pointer to of the float32 value passed in. -func Float32(v float32) *float32 { - return &v -} - -// Float32Value returns the value of the float32 pointer passed in or -// 0 if the pointer is nil. -func Float32Value(v *float32) float32 { - if v != nil { - return *v - } - - return 0 -} - -// Float32Slice converts a slice of float32 values into a slice of -// float32 pointers -func Float32Slice(src []float32) []*float32 { - dst := make([]*float32, len(src)) - - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - - return dst -} - -// Float32ValueSlice converts a slice of float32 pointers into a slice of -// float32 values -func Float32ValueSlice(src []*float32) []float32 { - dst := make([]float32, len(src)) - - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - - return dst -} - -// Float32Map converts a string map of float32 values into a string -// map of float32 pointers -func Float32Map(src map[string]float32) map[string]*float32 { - dst := make(map[string]*float32) - - for k, val := range src { - v := val - dst[k] = &v - } - - return dst -} - -// Float32ValueMap converts a string map of float32 pointers into a string -// map of float32 values -func Float32ValueMap(src map[string]*float32) map[string]float32 { - dst := make(map[string]float32) - - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - - return dst -} - -// Float64 returns a pointer to of the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to of the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/vendor/github.com/go-openapi/swag/doc.go b/vendor/github.com/go-openapi/swag/doc.go deleted file mode 100644 index 55094cb74..000000000 --- a/vendor/github.com/go-openapi/swag/doc.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag contains a bunch of helper functions for go-openapi and go-swagger projects. - -You may also use it standalone for your projects. - - - convert between value and pointers for builtin types - - convert from string to builtin types (wraps strconv) - - fast json concatenation - - search in path - - load from file or http - - name mangling - -This repo has only few dependencies outside of the standard library: - - - YAML utilities depend on gopkg.in/yaml.v2 -*/ -package swag diff --git a/vendor/github.com/go-openapi/swag/file.go b/vendor/github.com/go-openapi/swag/file.go deleted file mode 100644 index 16accc55f..000000000 --- a/vendor/github.com/go-openapi/swag/file.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import "mime/multipart" - -// File represents an uploaded file. -type File struct { - Data multipart.File - Header *multipart.FileHeader -} - -// Read bytes from the file -func (f *File) Read(p []byte) (n int, err error) { - return f.Data.Read(p) -} - -// Close the file -func (f *File) Close() error { - return f.Data.Close() -} diff --git a/vendor/github.com/go-openapi/swag/initialism_index.go b/vendor/github.com/go-openapi/swag/initialism_index.go deleted file mode 100644 index 20a359bb6..000000000 --- a/vendor/github.com/go-openapi/swag/initialism_index.go +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "sort" - "strings" - "sync" -) - -var ( - // commonInitialisms are common acronyms that are kept as whole uppercased words. - commonInitialisms *indexOfInitialisms - - // initialisms is a slice of sorted initialisms - initialisms []string - - // a copy of initialisms pre-baked as []rune - initialismsRunes [][]rune - initialismsUpperCased [][]rune - - isInitialism func(string) bool - - maxAllocMatches int -) - -func init() { - // Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769 - configuredInitialisms := map[string]bool{ - "ACL": true, - "API": true, - "ASCII": true, - "CPU": true, - "CSS": true, - "DNS": true, - "EOF": true, - "GUID": true, - "HTML": true, - "HTTPS": true, - "HTTP": true, - "ID": true, - "IP": true, - "IPv4": true, - "IPv6": true, - "JSON": true, - "LHS": true, - "OAI": true, - "QPS": true, - "RAM": true, - "RHS": true, - "RPC": true, - "SLA": true, - "SMTP": true, - "SQL": true, - "SSH": true, - "TCP": true, - "TLS": true, - "TTL": true, - "UDP": true, - "UI": true, - "UID": true, - "UUID": true, - "URI": true, - "URL": true, - "UTF8": true, - "VM": true, - "XML": true, - "XMPP": true, - "XSRF": true, - "XSS": true, - } - - // a thread-safe index of initialisms - commonInitialisms = newIndexOfInitialisms().load(configuredInitialisms) - initialisms = commonInitialisms.sorted() - initialismsRunes = asRunes(initialisms) - initialismsUpperCased = asUpperCased(initialisms) - maxAllocMatches = maxAllocHeuristic(initialismsRunes) - - // a test function - isInitialism = commonInitialisms.isInitialism -} - -func asRunes(in []string) [][]rune { - out := make([][]rune, len(in)) - for i, initialism := range in { - out[i] = []rune(initialism) - } - - return out -} - -func asUpperCased(in []string) [][]rune { - out := make([][]rune, len(in)) - - for i, initialism := range in { - out[i] = []rune(upper(trim(initialism))) - } - - return out -} - -func maxAllocHeuristic(in [][]rune) int { - heuristic := make(map[rune]int) - for _, initialism := range in { - heuristic[initialism[0]]++ - } - - var maxAlloc int - for _, val := range heuristic { - if val > maxAlloc { - maxAlloc = val - } - } - - return maxAlloc -} - -// AddInitialisms add additional initialisms -func AddInitialisms(words ...string) { - for _, word := range words { - // commonInitialisms[upper(word)] = true - commonInitialisms.add(upper(word)) - } - // sort again - initialisms = commonInitialisms.sorted() - initialismsRunes = asRunes(initialisms) - initialismsUpperCased = asUpperCased(initialisms) -} - -// indexOfInitialisms is a thread-safe implementation of the sorted index of initialisms. -// Since go1.9, this may be implemented with sync.Map. -type indexOfInitialisms struct { - sortMutex *sync.Mutex - index *sync.Map -} - -func newIndexOfInitialisms() *indexOfInitialisms { - return &indexOfInitialisms{ - sortMutex: new(sync.Mutex), - index: new(sync.Map), - } -} - -func (m *indexOfInitialisms) load(initial map[string]bool) *indexOfInitialisms { - m.sortMutex.Lock() - defer m.sortMutex.Unlock() - for k, v := range initial { - m.index.Store(k, v) - } - return m -} - -func (m *indexOfInitialisms) isInitialism(key string) bool { - _, ok := m.index.Load(key) - return ok -} - -func (m *indexOfInitialisms) add(key string) *indexOfInitialisms { - m.index.Store(key, true) - return m -} - -func (m *indexOfInitialisms) sorted() (result []string) { - m.sortMutex.Lock() - defer m.sortMutex.Unlock() - m.index.Range(func(key, _ interface{}) bool { - k := key.(string) - result = append(result, k) - return true - }) - sort.Sort(sort.Reverse(byInitialism(result))) - return -} - -type byInitialism []string - -func (s byInitialism) Len() int { - return len(s) -} -func (s byInitialism) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s byInitialism) Less(i, j int) bool { - if len(s[i]) != len(s[j]) { - return len(s[i]) < len(s[j]) - } - - return strings.Compare(s[i], s[j]) > 0 -} diff --git a/vendor/github.com/go-openapi/swag/json.go b/vendor/github.com/go-openapi/swag/json.go deleted file mode 100644 index 7e9902ca3..000000000 --- a/vendor/github.com/go-openapi/swag/json.go +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "bytes" - "encoding/json" - "log" - "reflect" - "strings" - "sync" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" -) - -// nullJSON represents a JSON object with null type -var nullJSON = []byte("null") - -// DefaultJSONNameProvider the default cache for types -var DefaultJSONNameProvider = NewNameProvider() - -const comma = byte(',') - -var closers map[byte]byte - -func init() { - closers = map[byte]byte{ - '{': '}', - '[': ']', - } -} - -type ejMarshaler interface { - MarshalEasyJSON(w *jwriter.Writer) -} - -type ejUnmarshaler interface { - UnmarshalEasyJSON(w *jlexer.Lexer) -} - -// WriteJSON writes json data, prefers finding an appropriate interface to short-circuit the marshaler -// so it takes the fastest option available. -func WriteJSON(data interface{}) ([]byte, error) { - if d, ok := data.(ejMarshaler); ok { - jw := new(jwriter.Writer) - d.MarshalEasyJSON(jw) - return jw.BuildBytes() - } - if d, ok := data.(json.Marshaler); ok { - return d.MarshalJSON() - } - return json.Marshal(data) -} - -// ReadJSON reads json data, prefers finding an appropriate interface to short-circuit the unmarshaler -// so it takes the fastest option available -func ReadJSON(data []byte, value interface{}) error { - trimmedData := bytes.Trim(data, "\x00") - if d, ok := value.(ejUnmarshaler); ok { - jl := &jlexer.Lexer{Data: trimmedData} - d.UnmarshalEasyJSON(jl) - return jl.Error() - } - if d, ok := value.(json.Unmarshaler); ok { - return d.UnmarshalJSON(trimmedData) - } - return json.Unmarshal(trimmedData, value) -} - -// DynamicJSONToStruct converts an untyped json structure into a struct -func DynamicJSONToStruct(data interface{}, target interface{}) error { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := WriteJSON(data) - if err != nil { - return err - } - return ReadJSON(b, target) -} - -// ConcatJSON concatenates multiple json objects efficiently -func ConcatJSON(blobs ...[]byte) []byte { - if len(blobs) == 0 { - return nil - } - - last := len(blobs) - 1 - for blobs[last] == nil || bytes.Equal(blobs[last], nullJSON) { - // strips trailing null objects - last-- - if last < 0 { - // there was nothing but "null"s or nil... - return nil - } - } - if last == 0 { - return blobs[0] - } - - var opening, closing byte - var idx, a int - buf := bytes.NewBuffer(nil) - - for i, b := range blobs[:last+1] { - if b == nil || bytes.Equal(b, nullJSON) { - // a null object is in the list: skip it - continue - } - if len(b) > 0 && opening == 0 { // is this an array or an object? - opening, closing = b[0], closers[b[0]] - } - - if opening != '{' && opening != '[' { - continue // don't know how to concatenate non container objects - } - - if len(b) < 3 { // yep empty but also the last one, so closing this thing - if i == last && a > 0 { - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - continue - } - - idx = 0 - if a > 0 { // we need to join with a comma for everything beyond the first non-empty item - if err := buf.WriteByte(comma); err != nil { - log.Println(err) - } - idx = 1 // this is not the first or the last so we want to drop the leading bracket - } - - if i != last { // not the last one, strip brackets - if _, err := buf.Write(b[idx : len(b)-1]); err != nil { - log.Println(err) - } - } else { // last one, strip only the leading bracket - if _, err := buf.Write(b[idx:]); err != nil { - log.Println(err) - } - } - a++ - } - // somehow it ended up being empty, so provide a default value - if buf.Len() == 0 { - if err := buf.WriteByte(opening); err != nil { - log.Println(err) - } - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - return buf.Bytes() -} - -// ToDynamicJSON turns an object into a properly JSON typed structure -func ToDynamicJSON(data interface{}) interface{} { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - var res interface{} - if err := json.Unmarshal(b, &res); err != nil { - log.Println(err) - } - return res -} - -// FromDynamicJSON turns an object into a properly JSON typed structure -func FromDynamicJSON(data, target interface{}) error { - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - return json.Unmarshal(b, target) -} - -// NameProvider represents an object capable of translating from go property names -// to json property names -// This type is thread-safe. -type NameProvider struct { - lock *sync.Mutex - index map[reflect.Type]nameIndex -} - -type nameIndex struct { - jsonNames map[string]string - goNames map[string]string -} - -// NewNameProvider creates a new name provider -func NewNameProvider() *NameProvider { - return &NameProvider{ - lock: &sync.Mutex{}, - index: make(map[reflect.Type]nameIndex), - } -} - -func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { - for i := 0; i < tpe.NumField(); i++ { - targetDes := tpe.Field(i) - - if targetDes.PkgPath != "" { // unexported - continue - } - - if targetDes.Anonymous { // walk embedded structures tree down first - buildnameIndex(targetDes.Type, idx, reverseIdx) - continue - } - - if tag := targetDes.Tag.Get("json"); tag != "" { - - parts := strings.Split(tag, ",") - if len(parts) == 0 { - continue - } - - nm := parts[0] - if nm == "-" { - continue - } - if nm == "" { // empty string means we want to use the Go name - nm = targetDes.Name - } - - idx[nm] = targetDes.Name - reverseIdx[targetDes.Name] = nm - } - } -} - -func newNameIndex(tpe reflect.Type) nameIndex { - var idx = make(map[string]string, tpe.NumField()) - var reverseIdx = make(map[string]string, tpe.NumField()) - - buildnameIndex(tpe, idx, reverseIdx) - return nameIndex{jsonNames: idx, goNames: reverseIdx} -} - -// GetJSONNames gets all the json property names for a type -func (n *NameProvider) GetJSONNames(subject interface{}) []string { - n.lock.Lock() - defer n.lock.Unlock() - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - - res := make([]string, 0, len(names.jsonNames)) - for k := range names.jsonNames { - res = append(res, k) - } - return res -} - -// GetJSONName gets the json name for a go property name -func (n *NameProvider) GetJSONName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetJSONNameForType(tpe, name) -} - -// GetJSONNameForType gets the json name for a go property name on a given type -func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.goNames[name] - return nme, ok -} - -func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { - names := newNameIndex(tpe) - n.index[tpe] = names - return names -} - -// GetGoName gets the go name for a json property name -func (n *NameProvider) GetGoName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetGoNameForType(tpe, name) -} - -// GetGoNameForType gets the go name for a given type for a json property name -func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.jsonNames[name] - return nme, ok -} diff --git a/vendor/github.com/go-openapi/swag/loading.go b/vendor/github.com/go-openapi/swag/loading.go deleted file mode 100644 index 783442fdd..000000000 --- a/vendor/github.com/go-openapi/swag/loading.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "fmt" - "io" - "log" - "net/http" - "net/url" - "os" - "path" - "path/filepath" - "runtime" - "strings" - "time" -) - -// LoadHTTPTimeout the default timeout for load requests -var LoadHTTPTimeout = 30 * time.Second - -// LoadHTTPBasicAuthUsername the username to use when load requests require basic auth -var LoadHTTPBasicAuthUsername = "" - -// LoadHTTPBasicAuthPassword the password to use when load requests require basic auth -var LoadHTTPBasicAuthPassword = "" - -// LoadHTTPCustomHeaders an optional collection of custom HTTP headers for load requests -var LoadHTTPCustomHeaders = map[string]string{} - -// LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in -func LoadFromFileOrHTTP(pth string) ([]byte, error) { - return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(pth) -} - -// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in -// timeout arg allows for per request overriding of the request timeout -func LoadFromFileOrHTTPWithTimeout(pth string, timeout time.Duration) ([]byte, error) { - return LoadStrategy(pth, os.ReadFile, loadHTTPBytes(timeout))(pth) -} - -// LoadStrategy returns a loader function for a given path or URI. -// -// The load strategy returns the remote load for any path starting with `http`. -// So this works for any URI with a scheme `http` or `https`. -// -// The fallback strategy is to call the local loader. -// -// The local loader takes a local file system path (absolute or relative) as argument, -// or alternatively a `file://...` URI, **without host** (see also below for windows). -// -// There are a few liberalities, initially intended to be tolerant regarding the URI syntax, -// especially on windows. -// -// Before the local loader is called, the given path is transformed: -// - percent-encoded characters are unescaped -// - simple paths (e.g. `./folder/file`) are passed as-is -// - on windows, occurrences of `/` are replaced by `\`, so providing a relative path such a `folder/file` works too. -// -// For paths provided as URIs with the "file" scheme, please note that: -// - `file://` is simply stripped. -// This means that the host part of the URI is not parsed at all. -// For example, `file:///folder/file" becomes "/folder/file`, -// but `file://localhost/folder/file` becomes `localhost/folder/file` on unix systems. -// Similarly, `file://./folder/file` yields `./folder/file`. -// - on windows, `file://...` can take a host so as to specify an UNC share location. -// -// Reminder about windows-specifics: -// - `file://host/folder/file` becomes an UNC path like `\\host\folder\file` (no port specification is supported) -// - `file:///c:/folder/file` becomes `C:\folder\file` -// - `file://c:/folder/file` is tolerated (without leading `/`) and becomes `c:\folder\file` -func LoadStrategy(pth string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) { - if strings.HasPrefix(pth, "http") { - return remote - } - - return func(p string) ([]byte, error) { - upth, err := url.PathUnescape(p) - if err != nil { - return nil, err - } - - if !strings.HasPrefix(p, `file://`) { - // regular file path provided: just normalize slashes - return local(filepath.FromSlash(upth)) - } - - if runtime.GOOS != "windows" { - // crude processing: this leaves full URIs with a host with a (mostly) unexpected result - upth = strings.TrimPrefix(upth, `file://`) - - return local(filepath.FromSlash(upth)) - } - - // windows-only pre-processing of file://... URIs - - // support for canonical file URIs on windows. - u, err := url.Parse(filepath.ToSlash(upth)) - if err != nil { - return nil, err - } - - if u.Host != "" { - // assume UNC name (volume share) - // NOTE: UNC port not yet supported - - // when the "host" segment is a drive letter: - // file://C:/folder/... => C:\folder - upth = path.Clean(strings.Join([]string{u.Host, u.Path}, `/`)) - if !strings.HasSuffix(u.Host, ":") && u.Host[0] != '.' { - // tolerance: if we have a leading dot, this can't be a host - // file://host/share/folder\... ==> \\host\share\path\folder - upth = "//" + upth - } - } else { - // no host, let's figure out if this is a drive letter - upth = strings.TrimPrefix(upth, `file://`) - first, _, _ := strings.Cut(strings.TrimPrefix(u.Path, "/"), "/") - if strings.HasSuffix(first, ":") { - // drive letter in the first segment: - // file:///c:/folder/... ==> strip the leading slash - upth = strings.TrimPrefix(upth, `/`) - } - } - - return local(filepath.FromSlash(upth)) - } -} - -func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { - return func(path string) ([]byte, error) { - client := &http.Client{Timeout: timeout} - req, err := http.NewRequest(http.MethodGet, path, nil) //nolint:noctx - if err != nil { - return nil, err - } - - if LoadHTTPBasicAuthUsername != "" && LoadHTTPBasicAuthPassword != "" { - req.SetBasicAuth(LoadHTTPBasicAuthUsername, LoadHTTPBasicAuthPassword) - } - - for key, val := range LoadHTTPCustomHeaders { - req.Header.Set(key, val) - } - - resp, err := client.Do(req) - defer func() { - if resp != nil { - if e := resp.Body.Close(); e != nil { - log.Println(e) - } - } - }() - if err != nil { - return nil, err - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status) - } - - return io.ReadAll(resp.Body) - } -} diff --git a/vendor/github.com/go-openapi/swag/name_lexem.go b/vendor/github.com/go-openapi/swag/name_lexem.go deleted file mode 100644 index 8bb64ac32..000000000 --- a/vendor/github.com/go-openapi/swag/name_lexem.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "unicode" - "unicode/utf8" -) - -type ( - lexemKind uint8 - - nameLexem struct { - original string - matchedInitialism string - kind lexemKind - } -) - -const ( - lexemKindCasualName lexemKind = iota - lexemKindInitialismName -) - -func newInitialismNameLexem(original, matchedInitialism string) nameLexem { - return nameLexem{ - kind: lexemKindInitialismName, - original: original, - matchedInitialism: matchedInitialism, - } -} - -func newCasualNameLexem(original string) nameLexem { - return nameLexem{ - kind: lexemKindCasualName, - original: original, - } -} - -func (l nameLexem) GetUnsafeGoName() string { - if l.kind == lexemKindInitialismName { - return l.matchedInitialism - } - - var ( - first rune - rest string - ) - - for i, orig := range l.original { - if i == 0 { - first = orig - continue - } - - if i > 0 { - rest = l.original[i:] - break - } - } - - if len(l.original) > 1 { - b := poolOfBuffers.BorrowBuffer(utf8.UTFMax + len(rest)) - defer func() { - poolOfBuffers.RedeemBuffer(b) - }() - b.WriteRune(unicode.ToUpper(first)) - b.WriteString(lower(rest)) - return b.String() - } - - return l.original -} - -func (l nameLexem) GetOriginal() string { - return l.original -} - -func (l nameLexem) IsInitialism() bool { - return l.kind == lexemKindInitialismName -} diff --git a/vendor/github.com/go-openapi/swag/net.go b/vendor/github.com/go-openapi/swag/net.go deleted file mode 100644 index 821235f84..000000000 --- a/vendor/github.com/go-openapi/swag/net.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "net" - "strconv" -) - -// SplitHostPort splits a network address into a host and a port. -// The port is -1 when there is no port to be found -func SplitHostPort(addr string) (host string, port int, err error) { - h, p, err := net.SplitHostPort(addr) - if err != nil { - return "", -1, err - } - if p == "" { - return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} - } - - pi, err := strconv.Atoi(p) - if err != nil { - return "", -1, err - } - return h, pi, nil -} diff --git a/vendor/github.com/go-openapi/swag/path.go b/vendor/github.com/go-openapi/swag/path.go deleted file mode 100644 index 941bd0176..000000000 --- a/vendor/github.com/go-openapi/swag/path.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "os" - "path/filepath" - "runtime" - "strings" -) - -const ( - // GOPATHKey represents the env key for gopath - GOPATHKey = "GOPATH" -) - -// FindInSearchPath finds a package in a provided lists of paths -func FindInSearchPath(searchPath, pkg string) string { - pathsList := filepath.SplitList(searchPath) - for _, path := range pathsList { - if evaluatedPath, err := filepath.EvalSymlinks(filepath.Join(path, "src", pkg)); err == nil { - if _, err := os.Stat(evaluatedPath); err == nil { - return evaluatedPath - } - } - } - return "" -} - -// FindInGoSearchPath finds a package in the $GOPATH:$GOROOT -func FindInGoSearchPath(pkg string) string { - return FindInSearchPath(FullGoSearchPath(), pkg) -} - -// FullGoSearchPath gets the search paths for finding packages -func FullGoSearchPath() string { - allPaths := os.Getenv(GOPATHKey) - if allPaths == "" { - allPaths = filepath.Join(os.Getenv("HOME"), "go") - } - if allPaths != "" { - allPaths = strings.Join([]string{allPaths, runtime.GOROOT()}, ":") - } else { - allPaths = runtime.GOROOT() - } - return allPaths -} diff --git a/vendor/github.com/go-openapi/swag/split.go b/vendor/github.com/go-openapi/swag/split.go deleted file mode 100644 index 274727a86..000000000 --- a/vendor/github.com/go-openapi/swag/split.go +++ /dev/null @@ -1,508 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "bytes" - "sync" - "unicode" - "unicode/utf8" -) - -type ( - splitter struct { - initialisms []string - initialismsRunes [][]rune - initialismsUpperCased [][]rune // initialisms cached in their trimmed, upper-cased version - postSplitInitialismCheck bool - } - - splitterOption func(*splitter) - - initialismMatch struct { - body []rune - start, end int - complete bool - } - initialismMatches []initialismMatch -) - -type ( - // memory pools of temporary objects. - // - // These are used to recycle temporarily allocated objects - // and relieve the GC from undue pressure. - - matchesPool struct { - *sync.Pool - } - - buffersPool struct { - *sync.Pool - } - - lexemsPool struct { - *sync.Pool - } - - splittersPool struct { - *sync.Pool - } -) - -var ( - // poolOfMatches holds temporary slices for recycling during the initialism match process - poolOfMatches = matchesPool{ - Pool: &sync.Pool{ - New: func() any { - s := make(initialismMatches, 0, maxAllocMatches) - - return &s - }, - }, - } - - poolOfBuffers = buffersPool{ - Pool: &sync.Pool{ - New: func() any { - return new(bytes.Buffer) - }, - }, - } - - poolOfLexems = lexemsPool{ - Pool: &sync.Pool{ - New: func() any { - s := make([]nameLexem, 0, maxAllocMatches) - - return &s - }, - }, - } - - poolOfSplitters = splittersPool{ - Pool: &sync.Pool{ - New: func() any { - s := newSplitter() - - return &s - }, - }, - } -) - -// nameReplaceTable finds a word representation for special characters. -func nameReplaceTable(r rune) (string, bool) { - switch r { - case '@': - return "At ", true - case '&': - return "And ", true - case '|': - return "Pipe ", true - case '$': - return "Dollar ", true - case '!': - return "Bang ", true - case '-': - return "", true - case '_': - return "", true - default: - return "", false - } -} - -// split calls the splitter. -// -// Use newSplitter for more control and options -func split(str string) []string { - s := poolOfSplitters.BorrowSplitter() - lexems := s.split(str) - result := make([]string, 0, len(*lexems)) - - for _, lexem := range *lexems { - result = append(result, lexem.GetOriginal()) - } - poolOfLexems.RedeemLexems(lexems) - poolOfSplitters.RedeemSplitter(s) - - return result - -} - -func newSplitter(options ...splitterOption) splitter { - s := splitter{ - postSplitInitialismCheck: false, - initialisms: initialisms, - initialismsRunes: initialismsRunes, - initialismsUpperCased: initialismsUpperCased, - } - - for _, option := range options { - option(&s) - } - - return s -} - -// withPostSplitInitialismCheck allows to catch initialisms after main split process -func withPostSplitInitialismCheck(s *splitter) { - s.postSplitInitialismCheck = true -} - -func (p matchesPool) BorrowMatches() *initialismMatches { - s := p.Get().(*initialismMatches) - *s = (*s)[:0] // reset slice, keep allocated capacity - - return s -} - -func (p buffersPool) BorrowBuffer(size int) *bytes.Buffer { - s := p.Get().(*bytes.Buffer) - s.Reset() - - if s.Cap() < size { - s.Grow(size) - } - - return s -} - -func (p lexemsPool) BorrowLexems() *[]nameLexem { - s := p.Get().(*[]nameLexem) - *s = (*s)[:0] // reset slice, keep allocated capacity - - return s -} - -func (p splittersPool) BorrowSplitter(options ...splitterOption) *splitter { - s := p.Get().(*splitter) - s.postSplitInitialismCheck = false // reset options - for _, apply := range options { - apply(s) - } - - return s -} - -func (p matchesPool) RedeemMatches(s *initialismMatches) { - p.Put(s) -} - -func (p buffersPool) RedeemBuffer(s *bytes.Buffer) { - p.Put(s) -} - -func (p lexemsPool) RedeemLexems(s *[]nameLexem) { - p.Put(s) -} - -func (p splittersPool) RedeemSplitter(s *splitter) { - p.Put(s) -} - -func (m initialismMatch) isZero() bool { - return m.start == 0 && m.end == 0 -} - -func (s splitter) split(name string) *[]nameLexem { - nameRunes := []rune(name) - matches := s.gatherInitialismMatches(nameRunes) - if matches == nil { - return poolOfLexems.BorrowLexems() - } - - return s.mapMatchesToNameLexems(nameRunes, matches) -} - -func (s splitter) gatherInitialismMatches(nameRunes []rune) *initialismMatches { - var matches *initialismMatches - - for currentRunePosition, currentRune := range nameRunes { - // recycle these allocations as we loop over runes - // with such recycling, only 2 slices should be allocated per call - // instead of o(n). - newMatches := poolOfMatches.BorrowMatches() - - // check current initialism matches - if matches != nil { // skip first iteration - for _, match := range *matches { - if keepCompleteMatch := match.complete; keepCompleteMatch { - *newMatches = append(*newMatches, match) - continue - } - - // drop failed match - currentMatchRune := match.body[currentRunePosition-match.start] - if currentMatchRune != currentRune { - continue - } - - // try to complete ongoing match - if currentRunePosition-match.start == len(match.body)-1 { - // we are close; the next step is to check the symbol ahead - // if it is a small letter, then it is not the end of match - // but beginning of the next word - - if currentRunePosition < len(nameRunes)-1 { - nextRune := nameRunes[currentRunePosition+1] - if newWord := unicode.IsLower(nextRune); newWord { - // oh ok, it was the start of a new word - continue - } - } - - match.complete = true - match.end = currentRunePosition - } - - *newMatches = append(*newMatches, match) - } - } - - // check for new initialism matches - for i := range s.initialisms { - initialismRunes := s.initialismsRunes[i] - if initialismRunes[0] == currentRune { - *newMatches = append(*newMatches, initialismMatch{ - start: currentRunePosition, - body: initialismRunes, - complete: false, - }) - } - } - - if matches != nil { - poolOfMatches.RedeemMatches(matches) - } - matches = newMatches - } - - // up to the caller to redeem this last slice - return matches -} - -func (s splitter) mapMatchesToNameLexems(nameRunes []rune, matches *initialismMatches) *[]nameLexem { - nameLexems := poolOfLexems.BorrowLexems() - - var lastAcceptedMatch initialismMatch - for _, match := range *matches { - if !match.complete { - continue - } - - if firstMatch := lastAcceptedMatch.isZero(); firstMatch { - s.appendBrokenDownCasualString(nameLexems, nameRunes[:match.start]) - *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) - - lastAcceptedMatch = match - - continue - } - - if overlappedMatch := match.start <= lastAcceptedMatch.end; overlappedMatch { - continue - } - - middle := nameRunes[lastAcceptedMatch.end+1 : match.start] - s.appendBrokenDownCasualString(nameLexems, middle) - *nameLexems = append(*nameLexems, s.breakInitialism(string(match.body))) - - lastAcceptedMatch = match - } - - // we have not found any accepted matches - if lastAcceptedMatch.isZero() { - *nameLexems = (*nameLexems)[:0] - s.appendBrokenDownCasualString(nameLexems, nameRunes) - } else if lastAcceptedMatch.end+1 != len(nameRunes) { - rest := nameRunes[lastAcceptedMatch.end+1:] - s.appendBrokenDownCasualString(nameLexems, rest) - } - - poolOfMatches.RedeemMatches(matches) - - return nameLexems -} - -func (s splitter) breakInitialism(original string) nameLexem { - return newInitialismNameLexem(original, original) -} - -func (s splitter) appendBrokenDownCasualString(segments *[]nameLexem, str []rune) { - currentSegment := poolOfBuffers.BorrowBuffer(len(str)) // unlike strings.Builder, bytes.Buffer initial storage can reused - defer func() { - poolOfBuffers.RedeemBuffer(currentSegment) - }() - - addCasualNameLexem := func(original string) { - *segments = append(*segments, newCasualNameLexem(original)) - } - - addInitialismNameLexem := func(original, match string) { - *segments = append(*segments, newInitialismNameLexem(original, match)) - } - - var addNameLexem func(string) - if s.postSplitInitialismCheck { - addNameLexem = func(original string) { - for i := range s.initialisms { - if isEqualFoldIgnoreSpace(s.initialismsUpperCased[i], original) { - addInitialismNameLexem(original, s.initialisms[i]) - - return - } - } - - addCasualNameLexem(original) - } - } else { - addNameLexem = addCasualNameLexem - } - - for _, rn := range str { - if replace, found := nameReplaceTable(rn); found { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - currentSegment.Reset() - } - - if replace != "" { - addNameLexem(replace) - } - - continue - } - - if !unicode.In(rn, unicode.L, unicode.M, unicode.N, unicode.Pc) { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - currentSegment.Reset() - } - - continue - } - - if unicode.IsUpper(rn) { - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - } - currentSegment.Reset() - } - - currentSegment.WriteRune(rn) - } - - if currentSegment.Len() > 0 { - addNameLexem(currentSegment.String()) - } -} - -// isEqualFoldIgnoreSpace is the same as strings.EqualFold, but -// it ignores leading and trailing blank spaces in the compared -// string. -// -// base is assumed to be composed of upper-cased runes, and be already -// trimmed. -// -// This code is heavily inspired from strings.EqualFold. -func isEqualFoldIgnoreSpace(base []rune, str string) bool { - var i, baseIndex int - // equivalent to b := []byte(str), but without data copy - b := hackStringBytes(str) - - for i < len(b) { - if c := b[i]; c < utf8.RuneSelf { - // fast path for ASCII - if c != ' ' && c != '\t' { - break - } - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if !unicode.IsSpace(r) { - break - } - i += size - } - - if i >= len(b) { - return len(base) == 0 - } - - for _, baseRune := range base { - if i >= len(b) { - break - } - - if c := b[i]; c < utf8.RuneSelf { - // single byte rune case (ASCII) - if baseRune >= utf8.RuneSelf { - return false - } - - baseChar := byte(baseRune) - if c != baseChar && - !('a' <= c && c <= 'z' && c-'a'+'A' == baseChar) { - return false - } - - baseIndex++ - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if unicode.ToUpper(r) != baseRune { - return false - } - baseIndex++ - i += size - } - - if baseIndex != len(base) { - return false - } - - // all passed: now we should only have blanks - for i < len(b) { - if c := b[i]; c < utf8.RuneSelf { - // fast path for ASCII - if c != ' ' && c != '\t' { - return false - } - i++ - - continue - } - - // unicode case - r, size := utf8.DecodeRune(b[i:]) - if !unicode.IsSpace(r) { - return false - } - - i += size - } - - return true -} diff --git a/vendor/github.com/go-openapi/swag/string_bytes.go b/vendor/github.com/go-openapi/swag/string_bytes.go deleted file mode 100644 index 90745d5ca..000000000 --- a/vendor/github.com/go-openapi/swag/string_bytes.go +++ /dev/null @@ -1,8 +0,0 @@ -package swag - -import "unsafe" - -// hackStringBytes returns the (unsafe) underlying bytes slice of a string. -func hackStringBytes(str string) []byte { - return unsafe.Slice(unsafe.StringData(str), len(str)) -} diff --git a/vendor/github.com/go-openapi/swag/util.go b/vendor/github.com/go-openapi/swag/util.go deleted file mode 100644 index 5051401c4..000000000 --- a/vendor/github.com/go-openapi/swag/util.go +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "reflect" - "strings" - "unicode" - "unicode/utf8" -) - -// GoNamePrefixFunc sets an optional rule to prefix go names -// which do not start with a letter. -// -// The prefix function is assumed to return a string that starts with an upper case letter. -// -// e.g. to help convert "123" into "{prefix}123" -// -// The default is to prefix with "X" -var GoNamePrefixFunc func(string) string - -func prefixFunc(name, in string) string { - if GoNamePrefixFunc == nil { - return "X" + in - } - - return GoNamePrefixFunc(name) + in -} - -const ( - // collectionFormatComma = "csv" - collectionFormatSpace = "ssv" - collectionFormatTab = "tsv" - collectionFormatPipe = "pipes" - collectionFormatMulti = "multi" -) - -// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute): -// -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func JoinByFormat(data []string, format string) []string { - if len(data) == 0 { - return data - } - var sep string - switch format { - case collectionFormatSpace: - sep = " " - case collectionFormatTab: - sep = "\t" - case collectionFormatPipe: - sep = "|" - case collectionFormatMulti: - return data - default: - sep = "," - } - return []string{strings.Join(data, sep)} -} - -// SplitByFormat splits a string by a known format: -// -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func SplitByFormat(data, format string) []string { - if data == "" { - return nil - } - var sep string - switch format { - case collectionFormatSpace: - sep = " " - case collectionFormatTab: - sep = "\t" - case collectionFormatPipe: - sep = "|" - case collectionFormatMulti: - return nil - default: - sep = "," - } - var result []string - for _, s := range strings.Split(data, sep) { - if ts := strings.TrimSpace(s); ts != "" { - result = append(result, ts) - } - } - return result -} - -// Removes leading whitespaces -func trim(str string) string { - return strings.TrimSpace(str) -} - -// Shortcut to strings.ToUpper() -func upper(str string) string { - return strings.ToUpper(trim(str)) -} - -// Shortcut to strings.ToLower() -func lower(str string) string { - return strings.ToLower(trim(str)) -} - -// Camelize an uppercased word -func Camelize(word string) string { - camelized := poolOfBuffers.BorrowBuffer(len(word)) - defer func() { - poolOfBuffers.RedeemBuffer(camelized) - }() - - for pos, ru := range []rune(word) { - if pos > 0 { - camelized.WriteRune(unicode.ToLower(ru)) - } else { - camelized.WriteRune(unicode.ToUpper(ru)) - } - } - return camelized.String() -} - -// ToFileName lowercases and underscores a go type name -func ToFileName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for _, w := range in { - out = append(out, lower(w)) - } - - return strings.Join(out, "_") -} - -// ToCommandName lowercases and underscores a go type name -func ToCommandName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for _, w := range in { - out = append(out, lower(w)) - } - return strings.Join(out, "-") -} - -// ToHumanNameLower represents a code name as a human series of words -func ToHumanNameLower(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - in := s.split(name) - poolOfSplitters.RedeemSplitter(s) - out := make([]string, 0, len(*in)) - - for _, w := range *in { - if !w.IsInitialism() { - out = append(out, lower(w.GetOriginal())) - } else { - out = append(out, trim(w.GetOriginal())) - } - } - poolOfLexems.RedeemLexems(in) - - return strings.Join(out, " ") -} - -// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized -func ToHumanNameTitle(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - in := s.split(name) - poolOfSplitters.RedeemSplitter(s) - - out := make([]string, 0, len(*in)) - for _, w := range *in { - original := trim(w.GetOriginal()) - if !w.IsInitialism() { - out = append(out, Camelize(original)) - } else { - out = append(out, original) - } - } - poolOfLexems.RedeemLexems(in) - - return strings.Join(out, " ") -} - -// ToJSONName camelcases a name which can be underscored or pascal cased -func ToJSONName(name string) string { - in := split(name) - out := make([]string, 0, len(in)) - - for i, w := range in { - if i == 0 { - out = append(out, lower(w)) - continue - } - out = append(out, Camelize(trim(w))) - } - return strings.Join(out, "") -} - -// ToVarName camelcases a name which can be underscored or pascal cased -func ToVarName(name string) string { - res := ToGoName(name) - if isInitialism(res) { - return lower(res) - } - if len(res) <= 1 { - return lower(res) - } - return lower(res[:1]) + res[1:] -} - -// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes -func ToGoName(name string) string { - s := poolOfSplitters.BorrowSplitter(withPostSplitInitialismCheck) - lexems := s.split(name) - poolOfSplitters.RedeemSplitter(s) - defer func() { - poolOfLexems.RedeemLexems(lexems) - }() - lexemes := *lexems - - if len(lexemes) == 0 { - return "" - } - - result := poolOfBuffers.BorrowBuffer(len(name)) - defer func() { - poolOfBuffers.RedeemBuffer(result) - }() - - // check if not starting with a letter, upper case - firstPart := lexemes[0].GetUnsafeGoName() - if lexemes[0].IsInitialism() { - firstPart = upper(firstPart) - } - - if c := firstPart[0]; c < utf8.RuneSelf { - // ASCII - switch { - case 'A' <= c && c <= 'Z': - result.WriteString(firstPart) - case 'a' <= c && c <= 'z': - result.WriteByte(c - 'a' + 'A') - result.WriteString(firstPart[1:]) - default: - result.WriteString(prefixFunc(name, firstPart)) - // NOTE: no longer check if prefixFunc returns a string that starts with uppercase: - // assume this is always the case - } - } else { - // unicode - firstRune, _ := utf8.DecodeRuneInString(firstPart) - switch { - case !unicode.IsLetter(firstRune): - result.WriteString(prefixFunc(name, firstPart)) - case !unicode.IsUpper(firstRune): - result.WriteString(prefixFunc(name, firstPart)) - /* - result.WriteRune(unicode.ToUpper(firstRune)) - result.WriteString(firstPart[offset:]) - */ - default: - result.WriteString(firstPart) - } - } - - for _, lexem := range lexemes[1:] { - goName := lexem.GetUnsafeGoName() - - // to support old behavior - if lexem.IsInitialism() { - goName = upper(goName) - } - result.WriteString(goName) - } - - return result.String() -} - -// ContainsStrings searches a slice of strings for a case-sensitive match -func ContainsStrings(coll []string, item string) bool { - for _, a := range coll { - if a == item { - return true - } - } - return false -} - -// ContainsStringsCI searches a slice of strings for a case-insensitive match -func ContainsStringsCI(coll []string, item string) bool { - for _, a := range coll { - if strings.EqualFold(a, item) { - return true - } - } - return false -} - -type zeroable interface { - IsZero() bool -} - -// IsZero returns true when the value passed into the function is a zero value. -// This allows for safer checking of interface values. -func IsZero(data interface{}) bool { - v := reflect.ValueOf(data) - // check for nil data - switch v.Kind() { //nolint:exhaustive - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - if v.IsNil() { - return true - } - } - - // check for things that have an IsZero method instead - if vv, ok := data.(zeroable); ok { - return vv.IsZero() - } - - // continue with slightly more complex reflection - switch v.Kind() { //nolint:exhaustive - case reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Struct, reflect.Array: - return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) - case reflect.Invalid: - return true - default: - return false - } -} - -// CommandLineOptionsGroup represents a group of user-defined command line options -type CommandLineOptionsGroup struct { - ShortDescription string - LongDescription string - Options interface{} -} diff --git a/vendor/github.com/go-openapi/swag/yaml.go b/vendor/github.com/go-openapi/swag/yaml.go deleted file mode 100644 index f59e02593..000000000 --- a/vendor/github.com/go-openapi/swag/yaml.go +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT 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 swag - -import ( - "encoding/json" - "errors" - "fmt" - "path/filepath" - "reflect" - "sort" - "strconv" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" - yaml "gopkg.in/yaml.v3" -) - -// YAMLMatcher matches yaml -func YAMLMatcher(path string) bool { - ext := filepath.Ext(path) - return ext == ".yaml" || ext == ".yml" -} - -// YAMLToJSON converts YAML unmarshaled data into json compatible data -func YAMLToJSON(data interface{}) (json.RawMessage, error) { - jm, err := transformData(data) - if err != nil { - return nil, err - } - b, err := WriteJSON(jm) - return json.RawMessage(b), err -} - -// BytesToYAMLDoc converts a byte slice into a YAML document -func BytesToYAMLDoc(data []byte) (interface{}, error) { - var document yaml.Node // preserve order that is present in the document - if err := yaml.Unmarshal(data, &document); err != nil { - return nil, err - } - if document.Kind != yaml.DocumentNode || len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { - return nil, errors.New("only YAML documents that are objects are supported") - } - return &document, nil -} - -func yamlNode(root *yaml.Node) (interface{}, error) { - switch root.Kind { - case yaml.DocumentNode: - return yamlDocument(root) - case yaml.SequenceNode: - return yamlSequence(root) - case yaml.MappingNode: - return yamlMapping(root) - case yaml.ScalarNode: - return yamlScalar(root) - case yaml.AliasNode: - return yamlNode(root.Alias) - default: - return nil, fmt.Errorf("unsupported YAML node type: %v", root.Kind) - } -} - -func yamlDocument(node *yaml.Node) (interface{}, error) { - if len(node.Content) != 1 { - return nil, fmt.Errorf("unexpected YAML Document node content length: %d", len(node.Content)) - } - return yamlNode(node.Content[0]) -} - -func yamlMapping(node *yaml.Node) (interface{}, error) { - m := make(JSONMapSlice, len(node.Content)/2) - - var j int - for i := 0; i < len(node.Content); i += 2 { - var nmi JSONMapItem - k, err := yamlStringScalarC(node.Content[i]) - if err != nil { - return nil, fmt.Errorf("unable to decode YAML map key: %w", err) - } - nmi.Key = k - v, err := yamlNode(node.Content[i+1]) - if err != nil { - return nil, fmt.Errorf("unable to process YAML map value for key %q: %w", k, err) - } - nmi.Value = v - m[j] = nmi - j++ - } - return m, nil -} - -func yamlSequence(node *yaml.Node) (interface{}, error) { - s := make([]interface{}, 0) - - for i := 0; i < len(node.Content); i++ { - - v, err := yamlNode(node.Content[i]) - if err != nil { - return nil, fmt.Errorf("unable to decode YAML sequence value: %w", err) - } - s = append(s, v) - } - return s, nil -} - -const ( // See https://yaml.org/type/ - yamlStringScalar = "tag:yaml.org,2002:str" - yamlIntScalar = "tag:yaml.org,2002:int" - yamlBoolScalar = "tag:yaml.org,2002:bool" - yamlFloatScalar = "tag:yaml.org,2002:float" - yamlTimestamp = "tag:yaml.org,2002:timestamp" - yamlNull = "tag:yaml.org,2002:null" -) - -func yamlScalar(node *yaml.Node) (interface{}, error) { - switch node.LongTag() { - case yamlStringScalar: - return node.Value, nil - case yamlBoolScalar: - b, err := strconv.ParseBool(node.Value) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting bool content: %w", node.Value, err) - } - return b, nil - case yamlIntScalar: - i, err := strconv.ParseInt(node.Value, 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting integer content: %w", node.Value, err) - } - return i, nil - case yamlFloatScalar: - f, err := strconv.ParseFloat(node.Value, 64) - if err != nil { - return nil, fmt.Errorf("unable to process scalar node. Got %q. Expecting float content: %w", node.Value, err) - } - return f, nil - case yamlTimestamp: - return node.Value, nil - case yamlNull: - return nil, nil //nolint:nilnil - default: - return nil, fmt.Errorf("YAML tag %q is not supported", node.LongTag()) - } -} - -func yamlStringScalarC(node *yaml.Node) (string, error) { - if node.Kind != yaml.ScalarNode { - return "", fmt.Errorf("expecting a string scalar but got %q", node.Kind) - } - switch node.LongTag() { - case yamlStringScalar, yamlIntScalar, yamlFloatScalar: - return node.Value, nil - default: - return "", fmt.Errorf("YAML tag %q is not supported as map key", node.LongTag()) - } -} - -// JSONMapSlice represent a JSON object, with the order of keys maintained -type JSONMapSlice []JSONMapItem - -// MarshalJSON renders a JSONMapSlice as JSON -func (s JSONMapSlice) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -// MarshalEasyJSON renders a JSONMapSlice as JSON, using easyJSON -func (s JSONMapSlice) MarshalEasyJSON(w *jwriter.Writer) { - w.RawByte('{') - - ln := len(s) - last := ln - 1 - for i := 0; i < ln; i++ { - s[i].MarshalEasyJSON(w) - if i != last { // last item - w.RawByte(',') - } - } - - w.RawByte('}') -} - -// UnmarshalJSON makes a JSONMapSlice from JSON -func (s *JSONMapSlice) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON makes a JSONMapSlice from JSON, using easyJSON -func (s *JSONMapSlice) UnmarshalEasyJSON(in *jlexer.Lexer) { - if in.IsNull() { - in.Skip() - return - } - - var result JSONMapSlice - in.Delim('{') - for !in.IsDelim('}') { - var mi JSONMapItem - mi.UnmarshalEasyJSON(in) - result = append(result, mi) - } - *s = result -} - -func (s JSONMapSlice) MarshalYAML() (interface{}, error) { - var n yaml.Node - n.Kind = yaml.DocumentNode - var nodes []*yaml.Node - for _, item := range s { - nn, err := json2yaml(item.Value) - if err != nil { - return nil, err - } - ns := []*yaml.Node{ - { - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: item.Key, - }, - nn, - } - nodes = append(nodes, ns...) - } - - n.Content = []*yaml.Node{ - { - Kind: yaml.MappingNode, - Content: nodes, - }, - } - - return yaml.Marshal(&n) -} - -func isNil(input interface{}) bool { - if input == nil { - return true - } - kind := reflect.TypeOf(input).Kind() - switch kind { //nolint:exhaustive - case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan: - return reflect.ValueOf(input).IsNil() - default: - return false - } -} - -func json2yaml(item interface{}) (*yaml.Node, error) { - if isNil(item) { - return &yaml.Node{ - Kind: yaml.ScalarNode, - Value: "null", - }, nil - } - - switch val := item.(type) { - case JSONMapSlice: - var n yaml.Node - n.Kind = yaml.MappingNode - for i := range val { - childNode, err := json2yaml(&val[i].Value) - if err != nil { - return nil, err - } - n.Content = append(n.Content, &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: val[i].Key, - }, childNode) - } - return &n, nil - case map[string]interface{}: - var n yaml.Node - n.Kind = yaml.MappingNode - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - v := val[k] - childNode, err := json2yaml(v) - if err != nil { - return nil, err - } - n.Content = append(n.Content, &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: k, - }, childNode) - } - return &n, nil - case []interface{}: - var n yaml.Node - n.Kind = yaml.SequenceNode - for i := range val { - childNode, err := json2yaml(val[i]) - if err != nil { - return nil, err - } - n.Content = append(n.Content, childNode) - } - return &n, nil - case string: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlStringScalar, - Value: val, - }, nil - case float64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlFloatScalar, - Value: strconv.FormatFloat(val, 'f', -1, 64), - }, nil - case int64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlIntScalar, - Value: strconv.FormatInt(val, 10), - }, nil - case uint64: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlIntScalar, - Value: strconv.FormatUint(val, 10), - }, nil - case bool: - return &yaml.Node{ - Kind: yaml.ScalarNode, - Tag: yamlBoolScalar, - Value: strconv.FormatBool(val), - }, nil - default: - return nil, fmt.Errorf("unhandled type: %T", val) - } -} - -// JSONMapItem represents the value of a key in a JSON object held by JSONMapSlice -type JSONMapItem struct { - Key string - Value interface{} -} - -// MarshalJSON renders a JSONMapItem as JSON -func (s JSONMapItem) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -// MarshalEasyJSON renders a JSONMapItem as JSON, using easyJSON -func (s JSONMapItem) MarshalEasyJSON(w *jwriter.Writer) { - w.String(s.Key) - w.RawByte(':') - w.Raw(WriteJSON(s.Value)) -} - -// UnmarshalJSON makes a JSONMapItem from JSON -func (s *JSONMapItem) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON makes a JSONMapItem from JSON, using easyJSON -func (s *JSONMapItem) UnmarshalEasyJSON(in *jlexer.Lexer) { - key := in.UnsafeString() - in.WantColon() - value := in.Interface() - in.WantComma() - s.Key = key - s.Value = value -} - -func transformData(input interface{}) (out interface{}, err error) { - format := func(t interface{}) (string, error) { - switch k := t.(type) { - case string: - return k, nil - case uint: - return strconv.FormatUint(uint64(k), 10), nil - case uint8: - return strconv.FormatUint(uint64(k), 10), nil - case uint16: - return strconv.FormatUint(uint64(k), 10), nil - case uint32: - return strconv.FormatUint(uint64(k), 10), nil - case uint64: - return strconv.FormatUint(k, 10), nil - case int: - return strconv.Itoa(k), nil - case int8: - return strconv.FormatInt(int64(k), 10), nil - case int16: - return strconv.FormatInt(int64(k), 10), nil - case int32: - return strconv.FormatInt(int64(k), 10), nil - case int64: - return strconv.FormatInt(k, 10), nil - default: - return "", fmt.Errorf("unexpected map key type, got: %T", k) - } - } - - switch in := input.(type) { - case yaml.Node: - return yamlNode(&in) - case *yaml.Node: - return yamlNode(in) - case map[interface{}]interface{}: - o := make(JSONMapSlice, 0, len(in)) - for ke, va := range in { - var nmi JSONMapItem - if nmi.Key, err = format(ke); err != nil { - return nil, err - } - - v, ert := transformData(va) - if ert != nil { - return nil, ert - } - nmi.Value = v - o = append(o, nmi) - } - return o, nil - case []interface{}: - len1 := len(in) - o := make([]interface{}, len1) - for i := 0; i < len1; i++ { - o[i], err = transformData(in[i]) - if err != nil { - return nil, err - } - } - return o, nil - } - return input, nil -} - -// YAMLDoc loads a yaml document from either http or a file and converts it to json -func YAMLDoc(path string) (json.RawMessage, error) { - yamlDoc, err := YAMLData(path) - if err != nil { - return nil, err - } - - data, err := YAMLToJSON(yamlDoc) - if err != nil { - return nil, err - } - - return data, nil -} - -// YAMLData loads a yaml document from either http or a file -func YAMLData(path string) (interface{}, error) { - data, err := LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - - return BytesToYAMLDoc(data) -} diff --git a/vendor/github.com/google/uuid/CHANGELOG.md b/vendor/github.com/google/uuid/CHANGELOG.md deleted file mode 100644 index 7ec5ac7ea..000000000 --- a/vendor/github.com/google/uuid/CHANGELOG.md +++ /dev/null @@ -1,41 +0,0 @@ -# Changelog - -## [1.6.0](https://github.com/google/uuid/compare/v1.5.0...v1.6.0) (2024-01-16) - - -### Features - -* add Max UUID constant ([#149](https://github.com/google/uuid/issues/149)) ([c58770e](https://github.com/google/uuid/commit/c58770eb495f55fe2ced6284f93c5158a62e53e3)) - - -### Bug Fixes - -* fix typo in version 7 uuid documentation ([#153](https://github.com/google/uuid/issues/153)) ([016b199](https://github.com/google/uuid/commit/016b199544692f745ffc8867b914129ecb47ef06)) -* Monotonicity in UUIDv7 ([#150](https://github.com/google/uuid/issues/150)) ([a2b2b32](https://github.com/google/uuid/commit/a2b2b32373ff0b1a312b7fdf6d38a977099698a6)) - -## [1.5.0](https://github.com/google/uuid/compare/v1.4.0...v1.5.0) (2023-12-12) - - -### Features - -* Validate UUID without creating new UUID ([#141](https://github.com/google/uuid/issues/141)) ([9ee7366](https://github.com/google/uuid/commit/9ee7366e66c9ad96bab89139418a713dc584ae29)) - -## [1.4.0](https://github.com/google/uuid/compare/v1.3.1...v1.4.0) (2023-10-26) - - -### Features - -* UUIDs slice type with Strings() convenience method ([#133](https://github.com/google/uuid/issues/133)) ([cd5fbbd](https://github.com/google/uuid/commit/cd5fbbdd02f3e3467ac18940e07e062be1f864b4)) - -### Fixes - -* Clarify that Parse's job is to parse but not necessarily validate strings. (Documents current behavior) - -## [1.3.1](https://github.com/google/uuid/compare/v1.3.0...v1.3.1) (2023-08-18) - - -### Bug Fixes - -* Use .EqualFold() to parse urn prefixed UUIDs ([#118](https://github.com/google/uuid/issues/118)) ([574e687](https://github.com/google/uuid/commit/574e6874943741fb99d41764c705173ada5293f0)) - -## Changelog diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md deleted file mode 100644 index a502fdc51..000000000 --- a/vendor/github.com/google/uuid/CONTRIBUTING.md +++ /dev/null @@ -1,26 +0,0 @@ -# How to contribute - -We definitely welcome patches and contribution to this project! - -### Tips - -Commits must be formatted according to the [Conventional Commits Specification](https://www.conventionalcommits.org). - -Always try to include a test case! If it is not possible or not necessary, -please explain why in the pull request description. - -### Releasing - -Commits that would precipitate a SemVer change, as described in the Conventional -Commits Specification, will trigger [`release-please`](https://github.com/google-github-actions/release-please-action) -to create a release candidate pull request. Once submitted, `release-please` -will create a release. - -For tips on how to work with `release-please`, see its documentation. - -### Legal requirements - -In order to protect both you and ourselves, you will need to sign the -[Contributor License Agreement](https://cla.developers.google.com/clas). - -You may have already signed it for other Google projects. diff --git a/vendor/github.com/google/uuid/CONTRIBUTORS b/vendor/github.com/google/uuid/CONTRIBUTORS deleted file mode 100644 index b4bb97f6b..000000000 --- a/vendor/github.com/google/uuid/CONTRIBUTORS +++ /dev/null @@ -1,9 +0,0 @@ -Paul Borman -bmatsuo -shawnps -theory -jboverfelt -dsymonds -cd1 -wallclockbuilder -dansouza diff --git a/vendor/github.com/google/uuid/LICENSE b/vendor/github.com/google/uuid/LICENSE deleted file mode 100644 index 5dc68268d..000000000 --- a/vendor/github.com/google/uuid/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009,2014 Google 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 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/vendor/github.com/google/uuid/README.md b/vendor/github.com/google/uuid/README.md deleted file mode 100644 index 3e9a61889..000000000 --- a/vendor/github.com/google/uuid/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# uuid -The uuid package generates and inspects UUIDs based on -[RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) -and DCE 1.1: Authentication and Security Services. - -This package is based on the github.com/pborman/uuid package (previously named -code.google.com/p/go-uuid). It differs from these earlier packages in that -a UUID is a 16 byte array rather than a byte slice. One loss due to this -change is the ability to represent an invalid UUID (vs a NIL UUID). - -###### Install -```sh -go get github.com/google/uuid -``` - -###### Documentation -[![Go Reference](https://pkg.go.dev/badge/github.com/google/uuid.svg)](https://pkg.go.dev/github.com/google/uuid) - -Full `go doc` style documentation for the package can be viewed online without -installing this package by using the GoDoc site here: -http://pkg.go.dev/github.com/google/uuid diff --git a/vendor/github.com/google/uuid/dce.go b/vendor/github.com/google/uuid/dce.go deleted file mode 100644 index fa820b9d3..000000000 --- a/vendor/github.com/google/uuid/dce.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" - "fmt" - "os" -) - -// A Domain represents a Version 2 domain -type Domain byte - -// Domain constants for DCE Security (Version 2) UUIDs. -const ( - Person = Domain(0) - Group = Domain(1) - Org = Domain(2) -) - -// NewDCESecurity returns a DCE Security (Version 2) UUID. -// -// The domain should be one of Person, Group or Org. -// On a POSIX system the id should be the users UID for the Person -// domain and the users GID for the Group. The meaning of id for -// the domain Org or on non-POSIX systems is site defined. -// -// For a given domain/id pair the same token may be returned for up to -// 7 minutes and 10 seconds. -func NewDCESecurity(domain Domain, id uint32) (UUID, error) { - uuid, err := NewUUID() - if err == nil { - uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 - uuid[9] = byte(domain) - binary.BigEndian.PutUint32(uuid[0:], id) - } - return uuid, err -} - -// NewDCEPerson returns a DCE Security (Version 2) UUID in the person -// domain with the id returned by os.Getuid. -// -// NewDCESecurity(Person, uint32(os.Getuid())) -func NewDCEPerson() (UUID, error) { - return NewDCESecurity(Person, uint32(os.Getuid())) -} - -// NewDCEGroup returns a DCE Security (Version 2) UUID in the group -// domain with the id returned by os.Getgid. -// -// NewDCESecurity(Group, uint32(os.Getgid())) -func NewDCEGroup() (UUID, error) { - return NewDCESecurity(Group, uint32(os.Getgid())) -} - -// Domain returns the domain for a Version 2 UUID. Domains are only defined -// for Version 2 UUIDs. -func (uuid UUID) Domain() Domain { - return Domain(uuid[9]) -} - -// ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 -// UUIDs. -func (uuid UUID) ID() uint32 { - return binary.BigEndian.Uint32(uuid[0:4]) -} - -func (d Domain) String() string { - switch d { - case Person: - return "Person" - case Group: - return "Group" - case Org: - return "Org" - } - return fmt.Sprintf("Domain%d", int(d)) -} diff --git a/vendor/github.com/google/uuid/doc.go b/vendor/github.com/google/uuid/doc.go deleted file mode 100644 index 5b8a4b9af..000000000 --- a/vendor/github.com/google/uuid/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package uuid generates and inspects UUIDs. -// -// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security -// Services. -// -// A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to -// maps or compared directly. -package uuid diff --git a/vendor/github.com/google/uuid/hash.go b/vendor/github.com/google/uuid/hash.go deleted file mode 100644 index dc60082d3..000000000 --- a/vendor/github.com/google/uuid/hash.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "crypto/md5" - "crypto/sha1" - "hash" -) - -// Well known namespace IDs and UUIDs -var ( - NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) - Nil UUID // empty UUID, all zeros - - // The Max UUID is special form of UUID that is specified to have all 128 bits set to 1. - Max = UUID{ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - } -) - -// NewHash returns a new UUID derived from the hash of space concatenated with -// data generated by h. The hash should be at least 16 byte in length. The -// first 16 bytes of the hash are used to form the UUID. The version of the -// UUID will be the lower 4 bits of version. NewHash is used to implement -// NewMD5 and NewSHA1. -func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { - h.Reset() - h.Write(space[:]) //nolint:errcheck - h.Write(data) //nolint:errcheck - s := h.Sum(nil) - var uuid UUID - copy(uuid[:], s) - uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) - uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant - return uuid -} - -// NewMD5 returns a new MD5 (Version 3) UUID based on the -// supplied name space and data. It is the same as calling: -// -// NewHash(md5.New(), space, data, 3) -func NewMD5(space UUID, data []byte) UUID { - return NewHash(md5.New(), space, data, 3) -} - -// NewSHA1 returns a new SHA1 (Version 5) UUID based on the -// supplied name space and data. It is the same as calling: -// -// NewHash(sha1.New(), space, data, 5) -func NewSHA1(space UUID, data []byte) UUID { - return NewHash(sha1.New(), space, data, 5) -} diff --git a/vendor/github.com/google/uuid/marshal.go b/vendor/github.com/google/uuid/marshal.go deleted file mode 100644 index 14bd34072..000000000 --- a/vendor/github.com/google/uuid/marshal.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import "fmt" - -// MarshalText implements encoding.TextMarshaler. -func (uuid UUID) MarshalText() ([]byte, error) { - var js [36]byte - encodeHex(js[:], uuid) - return js[:], nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (uuid *UUID) UnmarshalText(data []byte) error { - id, err := ParseBytes(data) - if err != nil { - return err - } - *uuid = id - return nil -} - -// MarshalBinary implements encoding.BinaryMarshaler. -func (uuid UUID) MarshalBinary() ([]byte, error) { - return uuid[:], nil -} - -// UnmarshalBinary implements encoding.BinaryUnmarshaler. -func (uuid *UUID) UnmarshalBinary(data []byte) error { - if len(data) != 16 { - return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) - } - copy(uuid[:], data) - return nil -} diff --git a/vendor/github.com/google/uuid/node.go b/vendor/github.com/google/uuid/node.go deleted file mode 100644 index d651a2b06..000000000 --- a/vendor/github.com/google/uuid/node.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "sync" -) - -var ( - nodeMu sync.Mutex - ifname string // name of interface being used - nodeID [6]byte // hardware for version 1 UUIDs - zeroID [6]byte // nodeID with only 0's -) - -// NodeInterface returns the name of the interface from which the NodeID was -// derived. The interface "user" is returned if the NodeID was set by -// SetNodeID. -func NodeInterface() string { - defer nodeMu.Unlock() - nodeMu.Lock() - return ifname -} - -// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. -// If name is "" then the first usable interface found will be used or a random -// Node ID will be generated. If a named interface cannot be found then false -// is returned. -// -// SetNodeInterface never fails when name is "". -func SetNodeInterface(name string) bool { - defer nodeMu.Unlock() - nodeMu.Lock() - return setNodeInterface(name) -} - -func setNodeInterface(name string) bool { - iname, addr := getHardwareInterface(name) // null implementation for js - if iname != "" && addr != nil { - ifname = iname - copy(nodeID[:], addr) - return true - } - - // We found no interfaces with a valid hardware address. If name - // does not specify a specific interface generate a random Node ID - // (section 4.1.6) - if name == "" { - ifname = "random" - randomBits(nodeID[:]) - return true - } - return false -} - -// NodeID returns a slice of a copy of the current Node ID, setting the Node ID -// if not already set. -func NodeID() []byte { - defer nodeMu.Unlock() - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - nid := nodeID - return nid[:] -} - -// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes -// of id are used. If id is less than 6 bytes then false is returned and the -// Node ID is not set. -func SetNodeID(id []byte) bool { - if len(id) < 6 { - return false - } - defer nodeMu.Unlock() - nodeMu.Lock() - copy(nodeID[:], id) - ifname = "user" - return true -} - -// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is -// not valid. The NodeID is only well defined for version 1 and 2 UUIDs. -func (uuid UUID) NodeID() []byte { - var node [6]byte - copy(node[:], uuid[10:]) - return node[:] -} diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go deleted file mode 100644 index b2a0bc871..000000000 --- a/vendor/github.com/google/uuid/node_js.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017 Google Inc. 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 - -package uuid - -// getHardwareInterface returns nil values for the JS version of the code. -// This removes the "net" dependency, because it is not used in the browser. -// Using the "net" library inflates the size of the transpiled JS code by 673k bytes. -func getHardwareInterface(name string) (string, []byte) { return "", nil } diff --git a/vendor/github.com/google/uuid/node_net.go b/vendor/github.com/google/uuid/node_net.go deleted file mode 100644 index 0cbbcddbd..000000000 --- a/vendor/github.com/google/uuid/node_net.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017 Google Inc. 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 - -package uuid - -import "net" - -var interfaces []net.Interface // cached list of interfaces - -// getHardwareInterface returns the name and hardware address of interface name. -// If name is "" then the name and hardware address of one of the system's -// interfaces is returned. If no interfaces are found (name does not exist or -// there are no interfaces) then "", nil is returned. -// -// Only addresses of at least 6 bytes are returned. -func getHardwareInterface(name string) (string, []byte) { - if interfaces == nil { - var err error - interfaces, err = net.Interfaces() - if err != nil { - return "", nil - } - } - for _, ifs := range interfaces { - if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { - return ifs.Name, ifs.HardwareAddr - } - } - return "", nil -} diff --git a/vendor/github.com/google/uuid/null.go b/vendor/github.com/google/uuid/null.go deleted file mode 100644 index d7fcbf286..000000000 --- a/vendor/github.com/google/uuid/null.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2021 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "database/sql/driver" - "encoding/json" - "fmt" -) - -var jsonNull = []byte("null") - -// NullUUID represents a UUID that may be null. -// NullUUID implements the SQL driver.Scanner interface so -// it can be used as a scan destination: -// -// var u uuid.NullUUID -// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u) -// ... -// if u.Valid { -// // use u.UUID -// } else { -// // NULL value -// } -// -type NullUUID struct { - UUID UUID - Valid bool // Valid is true if UUID is not NULL -} - -// Scan implements the SQL driver.Scanner interface. -func (nu *NullUUID) Scan(value interface{}) error { - if value == nil { - nu.UUID, nu.Valid = Nil, false - return nil - } - - err := nu.UUID.Scan(value) - if err != nil { - nu.Valid = false - return err - } - - nu.Valid = true - return nil -} - -// Value implements the driver Valuer interface. -func (nu NullUUID) Value() (driver.Value, error) { - if !nu.Valid { - return nil, nil - } - // Delegate to UUID Value function - return nu.UUID.Value() -} - -// MarshalBinary implements encoding.BinaryMarshaler. -func (nu NullUUID) MarshalBinary() ([]byte, error) { - if nu.Valid { - return nu.UUID[:], nil - } - - return []byte(nil), nil -} - -// UnmarshalBinary implements encoding.BinaryUnmarshaler. -func (nu *NullUUID) UnmarshalBinary(data []byte) error { - if len(data) != 16 { - return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) - } - copy(nu.UUID[:], data) - nu.Valid = true - return nil -} - -// MarshalText implements encoding.TextMarshaler. -func (nu NullUUID) MarshalText() ([]byte, error) { - if nu.Valid { - return nu.UUID.MarshalText() - } - - return jsonNull, nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (nu *NullUUID) UnmarshalText(data []byte) error { - id, err := ParseBytes(data) - if err != nil { - nu.Valid = false - return err - } - nu.UUID = id - nu.Valid = true - return nil -} - -// MarshalJSON implements json.Marshaler. -func (nu NullUUID) MarshalJSON() ([]byte, error) { - if nu.Valid { - return json.Marshal(nu.UUID) - } - - return jsonNull, nil -} - -// UnmarshalJSON implements json.Unmarshaler. -func (nu *NullUUID) UnmarshalJSON(data []byte) error { - if bytes.Equal(data, jsonNull) { - *nu = NullUUID{} - return nil // valid null UUID - } - err := json.Unmarshal(data, &nu.UUID) - nu.Valid = err == nil - return err -} diff --git a/vendor/github.com/google/uuid/sql.go b/vendor/github.com/google/uuid/sql.go deleted file mode 100644 index 2e02ec06c..000000000 --- a/vendor/github.com/google/uuid/sql.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "database/sql/driver" - "fmt" -) - -// Scan implements sql.Scanner so UUIDs can be read from databases transparently. -// Currently, database types that map to string and []byte are supported. Please -// consult database-specific driver documentation for matching types. -func (uuid *UUID) Scan(src interface{}) error { - switch src := src.(type) { - case nil: - return nil - - case string: - // if an empty UUID comes from a table, we return a null UUID - if src == "" { - return nil - } - - // see Parse for required string format - u, err := Parse(src) - if err != nil { - return fmt.Errorf("Scan: %v", err) - } - - *uuid = u - - case []byte: - // if an empty UUID comes from a table, we return a null UUID - if len(src) == 0 { - return nil - } - - // assumes a simple slice of bytes if 16 bytes - // otherwise attempts to parse - if len(src) != 16 { - return uuid.Scan(string(src)) - } - copy((*uuid)[:], src) - - default: - return fmt.Errorf("Scan: unable to scan type %T into UUID", src) - } - - return nil -} - -// Value implements sql.Valuer so that UUIDs can be written to databases -// transparently. Currently, UUIDs map to strings. Please consult -// database-specific driver documentation for matching types. -func (uuid UUID) Value() (driver.Value, error) { - return uuid.String(), nil -} diff --git a/vendor/github.com/google/uuid/time.go b/vendor/github.com/google/uuid/time.go deleted file mode 100644 index c35112927..000000000 --- a/vendor/github.com/google/uuid/time.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" - "sync" - "time" -) - -// A Time represents a time as the number of 100's of nanoseconds since 15 Oct -// 1582. -type Time int64 - -const ( - lillian = 2299160 // Julian day of 15 Oct 1582 - unix = 2440587 // Julian day of 1 Jan 1970 - epoch = unix - lillian // Days between epochs - g1582 = epoch * 86400 // seconds between epochs - g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs -) - -var ( - timeMu sync.Mutex - lasttime uint64 // last time we returned - clockSeq uint16 // clock sequence for this run - - timeNow = time.Now // for testing -) - -// UnixTime converts t the number of seconds and nanoseconds using the Unix -// epoch of 1 Jan 1970. -func (t Time) UnixTime() (sec, nsec int64) { - sec = int64(t - g1582ns100) - nsec = (sec % 10000000) * 100 - sec /= 10000000 - return sec, nsec -} - -// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and -// clock sequence as well as adjusting the clock sequence as needed. An error -// is returned if the current time cannot be determined. -func GetTime() (Time, uint16, error) { - defer timeMu.Unlock() - timeMu.Lock() - return getTime() -} - -func getTime() (Time, uint16, error) { - t := timeNow() - - // If we don't have a clock sequence already, set one. - if clockSeq == 0 { - setClockSequence(-1) - } - now := uint64(t.UnixNano()/100) + g1582ns100 - - // If time has gone backwards with this clock sequence then we - // increment the clock sequence - if now <= lasttime { - clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000 - } - lasttime = now - return Time(now), clockSeq, nil -} - -// ClockSequence returns the current clock sequence, generating one if not -// already set. The clock sequence is only used for Version 1 UUIDs. -// -// The uuid package does not use global static storage for the clock sequence or -// the last time a UUID was generated. Unless SetClockSequence is used, a new -// random clock sequence is generated the first time a clock sequence is -// requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) -func ClockSequence() int { - defer timeMu.Unlock() - timeMu.Lock() - return clockSequence() -} - -func clockSequence() int { - if clockSeq == 0 { - setClockSequence(-1) - } - return int(clockSeq & 0x3fff) -} - -// SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to -// -1 causes a new sequence to be generated. -func SetClockSequence(seq int) { - defer timeMu.Unlock() - timeMu.Lock() - setClockSequence(seq) -} - -func setClockSequence(seq int) { - if seq == -1 { - var b [2]byte - randomBits(b[:]) // clock sequence - seq = int(b[0])<<8 | int(b[1]) - } - oldSeq := clockSeq - clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant - if oldSeq != clockSeq { - lasttime = 0 - } -} - -// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in -// uuid. The time is only defined for version 1, 2, 6 and 7 UUIDs. -func (uuid UUID) Time() Time { - var t Time - switch uuid.Version() { - case 6: - time := binary.BigEndian.Uint64(uuid[:8]) // Ignore uuid[6] version b0110 - t = Time(time) - case 7: - time := binary.BigEndian.Uint64(uuid[:8]) - t = Time((time>>16)*10000 + g1582ns100) - default: // forward compatible - time := int64(binary.BigEndian.Uint32(uuid[0:4])) - time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 - time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 - t = Time(time) - } - return t -} - -// ClockSequence returns the clock sequence encoded in uuid. -// The clock sequence is only well defined for version 1 and 2 UUIDs. -func (uuid UUID) ClockSequence() int { - return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff -} diff --git a/vendor/github.com/google/uuid/util.go b/vendor/github.com/google/uuid/util.go deleted file mode 100644 index 5ea6c7378..000000000 --- a/vendor/github.com/google/uuid/util.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "io" -) - -// randomBits completely fills slice b with random data. -func randomBits(b []byte) { - if _, err := io.ReadFull(rander, b); err != nil { - panic(err.Error()) // rand should never fail - } -} - -// xvalues returns the value of a byte as a hexadecimal digit or 255. -var xvalues = [256]byte{ - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, -} - -// xtob converts hex characters x1 and x2 into a byte. -func xtob(x1, x2 byte) (byte, bool) { - b1 := xvalues[x1] - b2 := xvalues[x2] - return (b1 << 4) | b2, b1 != 255 && b2 != 255 -} diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go deleted file mode 100644 index 5232b4867..000000000 --- a/vendor/github.com/google/uuid/uuid.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "crypto/rand" - "encoding/hex" - "errors" - "fmt" - "io" - "strings" - "sync" -) - -// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC -// 4122. -type UUID [16]byte - -// A Version represents a UUID's version. -type Version byte - -// A Variant represents a UUID's variant. -type Variant byte - -// Constants returned by Variant. -const ( - Invalid = Variant(iota) // Invalid UUID - RFC4122 // The variant specified in RFC4122 - Reserved // Reserved, NCS backward compatibility. - Microsoft // Reserved, Microsoft Corporation backward compatibility. - Future // Reserved for future definition. -) - -const randPoolSize = 16 * 16 - -var ( - rander = rand.Reader // random function - poolEnabled = false - poolMu sync.Mutex - poolPos = randPoolSize // protected with poolMu - pool [randPoolSize]byte // protected with poolMu -) - -type invalidLengthError struct{ len int } - -func (err invalidLengthError) Error() string { - return fmt.Sprintf("invalid UUID length: %d", err.len) -} - -// IsInvalidLengthError is matcher function for custom error invalidLengthError -func IsInvalidLengthError(err error) bool { - _, ok := err.(invalidLengthError) - return ok -} - -// Parse decodes s into a UUID or returns an error if it cannot be parsed. Both -// the standard UUID forms defined in RFC 4122 -// (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, -// Parse accepts non-standard strings such as the raw hex encoding -// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, -// e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are -// examined in the latter case. Parse should not be used to validate strings as -// it parses non-standard encodings as indicated above. -func Parse(s string) (UUID, error) { - var uuid UUID - switch len(s) { - // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36: - - // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36 + 9: - if !strings.EqualFold(s[:9], "urn:uuid:") { - return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) - } - s = s[9:] - - // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - case 36 + 2: - s = s[1:] - - // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - case 32: - var ok bool - for i := range uuid { - uuid[i], ok = xtob(s[i*2], s[i*2+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - } - return uuid, nil - default: - return uuid, invalidLengthError{len(s)} - } - // s is now at least 36 bytes long - // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return uuid, errors.New("invalid UUID format") - } - for i, x := range [16]int{ - 0, 2, 4, 6, - 9, 11, - 14, 16, - 19, 21, - 24, 26, 28, 30, 32, 34, - } { - v, ok := xtob(s[x], s[x+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - uuid[i] = v - } - return uuid, nil -} - -// ParseBytes is like Parse, except it parses a byte slice instead of a string. -func ParseBytes(b []byte) (UUID, error) { - var uuid UUID - switch len(b) { - case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if !bytes.EqualFold(b[:9], []byte("urn:uuid:")) { - return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9]) - } - b = b[9:] - case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - b = b[1:] - case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - var ok bool - for i := 0; i < 32; i += 2 { - uuid[i/2], ok = xtob(b[i], b[i+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - } - return uuid, nil - default: - return uuid, invalidLengthError{len(b)} - } - // s is now at least 36 bytes long - // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' { - return uuid, errors.New("invalid UUID format") - } - for i, x := range [16]int{ - 0, 2, 4, 6, - 9, 11, - 14, 16, - 19, 21, - 24, 26, 28, 30, 32, 34, - } { - v, ok := xtob(b[x], b[x+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - uuid[i] = v - } - return uuid, nil -} - -// MustParse is like Parse but panics if the string cannot be parsed. -// It simplifies safe initialization of global variables holding compiled UUIDs. -func MustParse(s string) UUID { - uuid, err := Parse(s) - if err != nil { - panic(`uuid: Parse(` + s + `): ` + err.Error()) - } - return uuid -} - -// FromBytes creates a new UUID from a byte slice. Returns an error if the slice -// does not have a length of 16. The bytes are copied from the slice. -func FromBytes(b []byte) (uuid UUID, err error) { - err = uuid.UnmarshalBinary(b) - return uuid, err -} - -// Must returns uuid if err is nil and panics otherwise. -func Must(uuid UUID, err error) UUID { - if err != nil { - panic(err) - } - return uuid -} - -// Validate returns an error if s is not a properly formatted UUID in one of the following formats: -// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} -// It returns an error if the format is invalid, otherwise nil. -func Validate(s string) error { - switch len(s) { - // Standard UUID format - case 36: - - // UUID with "urn:uuid:" prefix - case 36 + 9: - if !strings.EqualFold(s[:9], "urn:uuid:") { - return fmt.Errorf("invalid urn prefix: %q", s[:9]) - } - s = s[9:] - - // UUID enclosed in braces - case 36 + 2: - if s[0] != '{' || s[len(s)-1] != '}' { - return fmt.Errorf("invalid bracketed UUID format") - } - s = s[1 : len(s)-1] - - // UUID without hyphens - case 32: - for i := 0; i < len(s); i += 2 { - _, ok := xtob(s[i], s[i+1]) - if !ok { - return errors.New("invalid UUID format") - } - } - - default: - return invalidLengthError{len(s)} - } - - // Check for standard UUID format - if len(s) == 36 { - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return errors.New("invalid UUID format") - } - for _, x := range []int{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} { - if _, ok := xtob(s[x], s[x+1]); !ok { - return errors.New("invalid UUID format") - } - } - } - - return nil -} - -// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -// , or "" if uuid is invalid. -func (uuid UUID) String() string { - var buf [36]byte - encodeHex(buf[:], uuid) - return string(buf[:]) -} - -// URN returns the RFC 2141 URN form of uuid, -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. -func (uuid UUID) URN() string { - var buf [36 + 9]byte - copy(buf[:], "urn:uuid:") - encodeHex(buf[9:], uuid) - return string(buf[:]) -} - -func encodeHex(dst []byte, uuid UUID) { - hex.Encode(dst, uuid[:4]) - dst[8] = '-' - hex.Encode(dst[9:13], uuid[4:6]) - dst[13] = '-' - hex.Encode(dst[14:18], uuid[6:8]) - dst[18] = '-' - hex.Encode(dst[19:23], uuid[8:10]) - dst[23] = '-' - hex.Encode(dst[24:], uuid[10:]) -} - -// Variant returns the variant encoded in uuid. -func (uuid UUID) Variant() Variant { - switch { - case (uuid[8] & 0xc0) == 0x80: - return RFC4122 - case (uuid[8] & 0xe0) == 0xc0: - return Microsoft - case (uuid[8] & 0xe0) == 0xe0: - return Future - default: - return Reserved - } -} - -// Version returns the version of uuid. -func (uuid UUID) Version() Version { - return Version(uuid[6] >> 4) -} - -func (v Version) String() string { - if v > 15 { - return fmt.Sprintf("BAD_VERSION_%d", v) - } - return fmt.Sprintf("VERSION_%d", v) -} - -func (v Variant) String() string { - switch v { - case RFC4122: - return "RFC4122" - case Reserved: - return "Reserved" - case Microsoft: - return "Microsoft" - case Future: - return "Future" - case Invalid: - return "Invalid" - } - return fmt.Sprintf("BadVariant%d", int(v)) -} - -// SetRand sets the random number generator to r, which implements io.Reader. -// If r.Read returns an error when the package requests random data then -// a panic will be issued. -// -// Calling SetRand with nil sets the random number generator to the default -// generator. -func SetRand(r io.Reader) { - if r == nil { - rander = rand.Reader - return - } - rander = r -} - -// EnableRandPool enables internal randomness pool used for Random -// (Version 4) UUID generation. The pool contains random bytes read from -// the random number generator on demand in batches. Enabling the pool -// may improve the UUID generation throughput significantly. -// -// Since the pool is stored on the Go heap, this feature may be a bad fit -// for security sensitive applications. -// -// Both EnableRandPool and DisableRandPool are not thread-safe and should -// only be called when there is no possibility that New or any other -// UUID Version 4 generation function will be called concurrently. -func EnableRandPool() { - poolEnabled = true -} - -// DisableRandPool disables the randomness pool if it was previously -// enabled with EnableRandPool. -// -// Both EnableRandPool and DisableRandPool are not thread-safe and should -// only be called when there is no possibility that New or any other -// UUID Version 4 generation function will be called concurrently. -func DisableRandPool() { - poolEnabled = false - defer poolMu.Unlock() - poolMu.Lock() - poolPos = randPoolSize -} - -// UUIDs is a slice of UUID types. -type UUIDs []UUID - -// Strings returns a string slice containing the string form of each UUID in uuids. -func (uuids UUIDs) Strings() []string { - var uuidStrs = make([]string, len(uuids)) - for i, uuid := range uuids { - uuidStrs[i] = uuid.String() - } - return uuidStrs -} diff --git a/vendor/github.com/google/uuid/version1.go b/vendor/github.com/google/uuid/version1.go deleted file mode 100644 index 463109629..000000000 --- a/vendor/github.com/google/uuid/version1.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" -) - -// NewUUID returns a Version 1 UUID based on the current NodeID and clock -// sequence, and the current time. If the NodeID has not been set by SetNodeID -// or SetNodeInterface then it will be set automatically. If the NodeID cannot -// be set NewUUID returns nil. If clock sequence has not been set by -// SetClockSequence then it will be set automatically. If GetTime fails to -// return the current NewUUID returns nil and an error. -// -// In most cases, New should be used. -func NewUUID() (UUID, error) { - var uuid UUID - now, seq, err := GetTime() - if err != nil { - return uuid, err - } - - timeLow := uint32(now & 0xffffffff) - timeMid := uint16((now >> 32) & 0xffff) - timeHi := uint16((now >> 48) & 0x0fff) - timeHi |= 0x1000 // Version 1 - - binary.BigEndian.PutUint32(uuid[0:], timeLow) - binary.BigEndian.PutUint16(uuid[4:], timeMid) - binary.BigEndian.PutUint16(uuid[6:], timeHi) - binary.BigEndian.PutUint16(uuid[8:], seq) - - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - copy(uuid[10:], nodeID[:]) - nodeMu.Unlock() - - return uuid, nil -} diff --git a/vendor/github.com/google/uuid/version4.go b/vendor/github.com/google/uuid/version4.go deleted file mode 100644 index 7697802e4..000000000 --- a/vendor/github.com/google/uuid/version4.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import "io" - -// New creates a new random UUID or panics. New is equivalent to -// the expression -// -// uuid.Must(uuid.NewRandom()) -func New() UUID { - return Must(NewRandom()) -} - -// NewString creates a new random UUID and returns it as a string or panics. -// NewString is equivalent to the expression -// -// uuid.New().String() -func NewString() string { - return Must(NewRandom()).String() -} - -// NewRandom returns a Random (Version 4) UUID. -// -// The strength of the UUIDs is based on the strength of the crypto/rand -// package. -// -// Uses the randomness pool if it was enabled with EnableRandPool. -// -// A note about uniqueness derived from the UUID Wikipedia entry: -// -// Randomly generated UUIDs have 122 random bits. One's annual risk of being -// hit by a meteorite is estimated to be one chance in 17 billion, that -// means the probability is about 0.00000000006 (6 × 10−11), -// equivalent to the odds of creating a few tens of trillions of UUIDs in a -// year and having one duplicate. -func NewRandom() (UUID, error) { - if !poolEnabled { - return NewRandomFromReader(rander) - } - return newRandomFromPool() -} - -// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader. -func NewRandomFromReader(r io.Reader) (UUID, error) { - var uuid UUID - _, err := io.ReadFull(r, uuid[:]) - if err != nil { - return Nil, err - } - uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 - uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 - return uuid, nil -} - -func newRandomFromPool() (UUID, error) { - var uuid UUID - poolMu.Lock() - if poolPos == randPoolSize { - _, err := io.ReadFull(rander, pool[:]) - if err != nil { - poolMu.Unlock() - return Nil, err - } - poolPos = 0 - } - copy(uuid[:], pool[poolPos:(poolPos+16)]) - poolPos += 16 - poolMu.Unlock() - - uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 - uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 - return uuid, nil -} diff --git a/vendor/github.com/google/uuid/version6.go b/vendor/github.com/google/uuid/version6.go deleted file mode 100644 index 339a959a7..000000000 --- a/vendor/github.com/google/uuid/version6.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2023 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import "encoding/binary" - -// UUID version 6 is a field-compatible version of UUIDv1, reordered for improved DB locality. -// It is expected that UUIDv6 will primarily be used in contexts where there are existing v1 UUIDs. -// Systems that do not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead. -// -// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#uuidv6 -// -// NewV6 returns a Version 6 UUID based on the current NodeID and clock -// sequence, and the current time. If the NodeID has not been set by SetNodeID -// or SetNodeInterface then it will be set automatically. If the NodeID cannot -// be set NewV6 set NodeID is random bits automatically . If clock sequence has not been set by -// SetClockSequence then it will be set automatically. If GetTime fails to -// return the current NewV6 returns Nil and an error. -func NewV6() (UUID, error) { - var uuid UUID - now, seq, err := GetTime() - if err != nil { - return uuid, err - } - - /* - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | time_high | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | time_mid | time_low_and_version | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - |clk_seq_hi_res | clk_seq_low | node (0-1) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | node (2-5) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - - binary.BigEndian.PutUint64(uuid[0:], uint64(now)) - binary.BigEndian.PutUint16(uuid[8:], seq) - - uuid[6] = 0x60 | (uuid[6] & 0x0F) - uuid[8] = 0x80 | (uuid[8] & 0x3F) - - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - copy(uuid[10:], nodeID[:]) - nodeMu.Unlock() - - return uuid, nil -} diff --git a/vendor/github.com/google/uuid/version7.go b/vendor/github.com/google/uuid/version7.go deleted file mode 100644 index 3167b643d..000000000 --- a/vendor/github.com/google/uuid/version7.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2023 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "io" -) - -// UUID version 7 features a time-ordered value field derived from the widely -// implemented and well known Unix Epoch timestamp source, -// the number of milliseconds seconds since midnight 1 Jan 1970 UTC, leap seconds excluded. -// As well as improved entropy characteristics over versions 1 or 6. -// -// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#name-uuid-version-7 -// -// Implementations SHOULD utilize UUID version 7 over UUID version 1 and 6 if possible. -// -// NewV7 returns a Version 7 UUID based on the current time(Unix Epoch). -// Uses the randomness pool if it was enabled with EnableRandPool. -// On error, NewV7 returns Nil and an error -func NewV7() (UUID, error) { - uuid, err := NewRandom() - if err != nil { - return uuid, err - } - makeV7(uuid[:]) - return uuid, nil -} - -// NewV7FromReader returns a Version 7 UUID based on the current time(Unix Epoch). -// it use NewRandomFromReader fill random bits. -// On error, NewV7FromReader returns Nil and an error. -func NewV7FromReader(r io.Reader) (UUID, error) { - uuid, err := NewRandomFromReader(r) - if err != nil { - return uuid, err - } - - makeV7(uuid[:]) - return uuid, nil -} - -// makeV7 fill 48 bits time (uuid[0] - uuid[5]), set version b0111 (uuid[6]) -// uuid[8] already has the right version number (Variant is 10) -// see function NewV7 and NewV7FromReader -func makeV7(uuid []byte) { - /* - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | unix_ts_ms | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | unix_ts_ms | ver | rand_a (12 bit seq) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - |var| rand_b | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | rand_b | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - _ = uuid[15] // bounds check - - t, s := getV7Time() - - uuid[0] = byte(t >> 40) - uuid[1] = byte(t >> 32) - uuid[2] = byte(t >> 24) - uuid[3] = byte(t >> 16) - uuid[4] = byte(t >> 8) - uuid[5] = byte(t) - - uuid[6] = 0x70 | (0x0F & byte(s>>8)) - uuid[7] = byte(s) -} - -// lastV7time is the last time we returned stored as: -// -// 52 bits of time in milliseconds since epoch -// 12 bits of (fractional nanoseconds) >> 8 -var lastV7time int64 - -const nanoPerMilli = 1000000 - -// getV7Time returns the time in milliseconds and nanoseconds / 256. -// The returned (milli << 12 + seq) is guarenteed to be greater than -// (milli << 12 + seq) returned by any previous call to getV7Time. -func getV7Time() (milli, seq int64) { - timeMu.Lock() - defer timeMu.Unlock() - - nano := timeNow().UnixNano() - milli = nano / nanoPerMilli - // Sequence number is between 0 and 3906 (nanoPerMilli>>8) - seq = (nano - milli*nanoPerMilli) >> 8 - now := milli<<12 + seq - if now <= lastV7time { - now = lastV7time + 1 - milli = now >> 12 - seq = now & 0xfff - } - lastV7time = now - return milli, seq -} diff --git a/vendor/github.com/hashicorp/go-cleanhttp/LICENSE b/vendor/github.com/hashicorp/go-cleanhttp/LICENSE deleted file mode 100644 index e87a115e4..000000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-cleanhttp/README.md b/vendor/github.com/hashicorp/go-cleanhttp/README.md deleted file mode 100644 index 036e5313f..000000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# cleanhttp - -Functions for accessing "clean" Go http.Client values - -------------- - -The Go standard library contains a default `http.Client` called -`http.DefaultClient`. It is a common idiom in Go code to start with -`http.DefaultClient` and tweak it as necessary, and in fact, this is -encouraged; from the `http` package documentation: - -> The Client's Transport typically has internal state (cached TCP connections), -so Clients should be reused instead of created as needed. Clients are safe for -concurrent use by multiple goroutines. - -Unfortunately, this is a shared value, and it is not uncommon for libraries to -assume that they are free to modify it at will. With enough dependencies, it -can be very easy to encounter strange problems and race conditions due to -manipulation of this shared value across libraries and goroutines (clients are -safe for concurrent use, but writing values to the client struct itself is not -protected). - -Making things worse is the fact that a bare `http.Client` will use a default -`http.Transport` called `http.DefaultTransport`, which is another global value -that behaves the same way. So it is not simply enough to replace -`http.DefaultClient` with `&http.Client{}`. - -This repository provides some simple functions to get a "clean" `http.Client` --- one that uses the same default values as the Go standard library, but -returns a client that does not share any state with other clients. diff --git a/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go b/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go deleted file mode 100644 index fe28d15b6..000000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/cleanhttp.go +++ /dev/null @@ -1,58 +0,0 @@ -package cleanhttp - -import ( - "net" - "net/http" - "runtime" - "time" -) - -// DefaultTransport returns a new http.Transport with similar default values to -// http.DefaultTransport, but with idle connections and keepalives disabled. -func DefaultTransport() *http.Transport { - transport := DefaultPooledTransport() - transport.DisableKeepAlives = true - transport.MaxIdleConnsPerHost = -1 - return transport -} - -// DefaultPooledTransport returns a new http.Transport with similar default -// values to http.DefaultTransport. Do not use this for transient transports as -// it can leak file descriptors over time. Only use this for transports that -// will be re-used for the same host(s). -func DefaultPooledTransport() *http.Transport { - transport := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - ForceAttemptHTTP2: true, - MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1, - } - return transport -} - -// DefaultClient returns a new http.Client with similar default values to -// http.Client, but with a non-shared Transport, idle connections disabled, and -// keepalives disabled. -func DefaultClient() *http.Client { - return &http.Client{ - Transport: DefaultTransport(), - } -} - -// DefaultPooledClient returns a new http.Client with similar default values to -// http.Client, but with a shared Transport. Do not use this function for -// transient clients as it can leak file descriptors over time. Only use this -// for clients that will be re-used for the same host(s). -func DefaultPooledClient() *http.Client { - return &http.Client{ - Transport: DefaultPooledTransport(), - } -} diff --git a/vendor/github.com/hashicorp/go-cleanhttp/doc.go b/vendor/github.com/hashicorp/go-cleanhttp/doc.go deleted file mode 100644 index 05841092a..000000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package cleanhttp offers convenience utilities for acquiring "clean" -// http.Transport and http.Client structs. -// -// Values set on http.DefaultClient and http.DefaultTransport affect all -// callers. This can have detrimental effects, esepcially in TLS contexts, -// where client or root certificates set to talk to multiple endpoints can end -// up displacing each other, leading to hard-to-debug issues. This package -// provides non-shared http.Client and http.Transport structs to ensure that -// the configuration will not be overwritten by other parts of the application -// or dependencies. -// -// The DefaultClient and DefaultTransport functions disable idle connections -// and keepalives. Without ensuring that idle connections are closed before -// garbage collection, short-term clients/transports can leak file descriptors, -// eventually leading to "too many open files" errors. If you will be -// connecting to the same hosts repeatedly from the same client, you can use -// DefaultPooledClient to receive a client that has connection pooling -// semantics similar to http.DefaultClient. -// -package cleanhttp diff --git a/vendor/github.com/hashicorp/go-cleanhttp/handlers.go b/vendor/github.com/hashicorp/go-cleanhttp/handlers.go deleted file mode 100644 index 3c845dc0d..000000000 --- a/vendor/github.com/hashicorp/go-cleanhttp/handlers.go +++ /dev/null @@ -1,48 +0,0 @@ -package cleanhttp - -import ( - "net/http" - "strings" - "unicode" -) - -// HandlerInput provides input options to cleanhttp's handlers -type HandlerInput struct { - ErrStatus int -} - -// PrintablePathCheckHandler is a middleware that ensures the request path -// contains only printable runes. -func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler { - // Nil-check on input to make it optional - if input == nil { - input = &HandlerInput{ - ErrStatus: http.StatusBadRequest, - } - } - - // Default to http.StatusBadRequest on error - if input.ErrStatus == 0 { - input.ErrStatus = http.StatusBadRequest - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r != nil { - // Check URL path for non-printable characters - idx := strings.IndexFunc(r.URL.Path, func(c rune) bool { - return !unicode.IsPrint(c) - }) - - if idx != -1 { - w.WriteHeader(input.ErrStatus) - return - } - - if next != nil { - next.ServeHTTP(w, r) - } - } - - return - }) -} diff --git a/vendor/github.com/hashicorp/go-retryablehttp/.gitignore b/vendor/github.com/hashicorp/go-retryablehttp/.gitignore deleted file mode 100644 index 4e309e0b3..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.idea/ -*.iml -*.test -.vscode/ \ No newline at end of file diff --git a/vendor/github.com/hashicorp/go-retryablehttp/.go-version b/vendor/github.com/hashicorp/go-retryablehttp/.go-version deleted file mode 100644 index 6fee2fedb..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/.go-version +++ /dev/null @@ -1 +0,0 @@ -1.22.2 diff --git a/vendor/github.com/hashicorp/go-retryablehttp/CHANGELOG.md b/vendor/github.com/hashicorp/go-retryablehttp/CHANGELOG.md deleted file mode 100644 index 68a627c6d..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/CHANGELOG.md +++ /dev/null @@ -1,33 +0,0 @@ -## 0.7.7 (May 30, 2024) - -BUG FIXES: - -- client: avoid potentially leaking URL-embedded basic authentication credentials in logs (#158) - -## 0.7.6 (May 9, 2024) - -ENHANCEMENTS: - -- client: support a `RetryPrepare` function for modifying the request before retrying (#216) -- client: support HTTP-date values for `Retry-After` header value (#138) -- client: avoid reading entire body when the body is a `*bytes.Reader` (#197) - -BUG FIXES: - -- client: fix a broken check for invalid server certificate in go 1.20+ (#210) - -## 0.7.5 (Nov 8, 2023) - -BUG FIXES: - -- client: fixes an issue where the request body is not preserved on temporary redirects or re-established HTTP/2 connections (#207) - -## 0.7.4 (Jun 6, 2023) - -BUG FIXES: - -- client: fixing an issue where the Content-Type header wouldn't be sent with an empty payload when using HTTP/2 (#194) - -## 0.7.3 (May 15, 2023) - -Initial release diff --git a/vendor/github.com/hashicorp/go-retryablehttp/CODEOWNERS b/vendor/github.com/hashicorp/go-retryablehttp/CODEOWNERS deleted file mode 100644 index d6dd78a2d..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/CODEOWNERS +++ /dev/null @@ -1 +0,0 @@ -* @hashicorp/go-retryablehttp-maintainers diff --git a/vendor/github.com/hashicorp/go-retryablehttp/LICENSE b/vendor/github.com/hashicorp/go-retryablehttp/LICENSE deleted file mode 100644 index f4f97ee58..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/LICENSE +++ /dev/null @@ -1,365 +0,0 @@ -Copyright (c) 2015 HashiCorp, Inc. - -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. "Contributor" - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. "Contributor Version" - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the terms of - a Secondary License. - -1.6. "Executable Form" - - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - - means a work that combines Covered Software with other material, in a - separate file or files, that is not Covered Software. - -1.8. "License" - - means this document. - -1.9. "Licensable" - - means having the right to grant, to the maximum extent possible, whether - at the time of the initial grant or subsequently, any and all of the - rights conveyed by this License. - -1.10. "Modifications" - - means any of the following: - - a. any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. "Patent Claims" of a Contributor - - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the License, - by the making, using, selling, offering for sale, having made, import, - or transfer of either its Contributions or its Contributor Version. - -1.12. "Secondary License" - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. "Source Code Form" - - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, "control" means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution - become effective for each Contribution on the date the Contributor first - distributes such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under - this License. No additional rights or licenses will be implied from the - distribution or licensing of Covered Software under this License. - Notwithstanding Section 2.1(b) above, no patent license is granted by a - Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of - its Contributions. - - This License does not grant any rights in the trademarks, service marks, - or logos of any Contributor (except as may be necessary to comply with - the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this - License (see Section 10.2) or under the terms of a Secondary License (if - permitted under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its - Contributions are its original creation(s) or it has sufficient rights to - grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under - applicable copyright doctrines of fair use, fair dealing, or other - equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under - the terms of this License. You must inform recipients that the Source - Code Form of the Covered Software is governed by the terms of this - License, and how they can obtain a copy of this License. You may not - attempt to alter or restrict the recipients' rights in the Source Code - Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter the - recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for - the Covered Software. If the Larger Work is a combination of Covered - Software with a work governed by one or more Secondary Licenses, and the - Covered Software is not Incompatible With Secondary Licenses, this - License permits You to additionally distribute such Covered Software - under the terms of such Secondary License(s), so that the recipient of - the Larger Work may, at their option, further distribute the Covered - Software under the terms of either this License or such Secondary - License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices - (including copyright notices, patent notices, disclaimers of warranty, or - limitations of liability) contained within the Source Code Form of the - Covered Software, except that You may alter any license notices to the - extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on - behalf of any Contributor. You must make it absolutely clear that any - such warranty, support, indemnity, or liability obligation is offered by - You alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, - judicial order, or regulation then You must: (a) comply with the terms of - this License to the maximum extent possible; and (b) describe the - limitations and the code they affect. Such description must be placed in a - text file included with all distributions of the Covered Software under - this License. Except to the extent prohibited by statute or regulation, - such description must be sufficiently detailed for a recipient of ordinary - skill to be able to understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing - basis, if such Contributor fails to notify You of the non-compliance by - some reasonable means prior to 60 days after You have come back into - compliance. Moreover, Your grants from a particular Contributor are - reinstated on an ongoing basis if such Contributor notifies You of the - non-compliance by some reasonable means, this is the first time You have - received notice of non-compliance with this License from such - Contributor, and You become compliant prior to 30 days after Your receipt - of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, - counter-claims, and cross-claims) alleging that a Contributor Version - directly or indirectly infringes any patent, then the rights granted to - You by any and all Contributors for the Covered Software under Section - 2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an "as is" basis, - without warranty of any kind, either expressed, implied, or statutory, - including, without limitation, warranties that the Covered Software is free - of defects, merchantable, fit for a particular purpose or non-infringing. - The entire risk as to the quality and performance of the Covered Software - is with You. Should any Covered Software prove defective in any respect, - You (not any Contributor) assume the cost of any necessary servicing, - repair, or correction. This disclaimer of warranty constitutes an essential - part of this License. No use of any Covered Software is authorized under - this License except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from - such party's negligence to the extent applicable law prohibits such - limitation. Some jurisdictions do not allow the exclusion or limitation of - incidental or consequential damages, so this exclusion and limitation may - not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts - of a jurisdiction where the defendant maintains its principal place of - business and such litigation shall be governed by laws of that - jurisdiction, without reference to its conflict-of-law provisions. Nothing - in this Section shall prevent a party's ability to bring cross-claims or - counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. Any law or regulation which provides that - the language of a contract shall be construed against the drafter shall not - be used to construe this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version - of the License under which You originally received the Covered Software, - or under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a - modified version of this License if you rename the license and remove - any references to the name of the license steward (except to note that - such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary - Licenses If You choose to distribute Source Code Form that is - Incompatible With Secondary Licenses under the terms of this version of - the License, the notice described in Exhibit B of this License must be - attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, -then You may include the notice in a location (such as a LICENSE file in a -relevant directory) where a recipient would be likely to look for such a -notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice - - This Source Code Form is "Incompatible - With Secondary Licenses", as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/go-retryablehttp/Makefile b/vendor/github.com/hashicorp/go-retryablehttp/Makefile deleted file mode 100644 index 525524196..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -default: test - -test: - go vet ./... - go test -v -race ./... - -updatedeps: - go get -f -t -u ./... - go get -f -u ./... - -.PHONY: default test updatedeps diff --git a/vendor/github.com/hashicorp/go-retryablehttp/README.md b/vendor/github.com/hashicorp/go-retryablehttp/README.md deleted file mode 100644 index 145a62f21..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/README.md +++ /dev/null @@ -1,62 +0,0 @@ -go-retryablehttp -================ - -[![Build Status](http://img.shields.io/travis/hashicorp/go-retryablehttp.svg?style=flat-square)][travis] -[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] - -[travis]: http://travis-ci.org/hashicorp/go-retryablehttp -[godocs]: http://godoc.org/github.com/hashicorp/go-retryablehttp - -The `retryablehttp` package provides a familiar HTTP client interface with -automatic retries and exponential backoff. It is a thin wrapper over the -standard `net/http` client library and exposes nearly the same public API. This -makes `retryablehttp` very easy to drop into existing programs. - -`retryablehttp` performs automatic retries under certain conditions. Mainly, if -an error is returned by the client (connection errors, etc.), or if a 500-range -response code is received (except 501), then a retry is invoked after a wait -period. Otherwise, the response is returned and left to the caller to -interpret. - -The main difference from `net/http` is that requests which take a request body -(POST/PUT et. al) can have the body provided in a number of ways (some more or -less efficient) that allow "rewinding" the request body if the initial request -fails so that the full request can be attempted again. See the -[godoc](http://godoc.org/github.com/hashicorp/go-retryablehttp) for more -details. - -Version 0.6.0 and before are compatible with Go prior to 1.12. From 0.6.1 onward, Go 1.12+ is required. -From 0.6.7 onward, Go 1.13+ is required. - -Example Use -=========== - -Using this library should look almost identical to what you would do with -`net/http`. The most simple example of a GET request is shown below: - -```go -resp, err := retryablehttp.Get("/foo") -if err != nil { - panic(err) -} -``` - -The returned response object is an `*http.Response`, the same thing you would -usually get from `net/http`. Had the request failed one or more times, the above -call would block and retry with exponential backoff. - -## Getting a stdlib `*http.Client` with retries - -It's possible to convert a `*retryablehttp.Client` directly to a `*http.Client`. -This makes use of retryablehttp broadly applicable with minimal effort. Simply -configure a `*retryablehttp.Client` as you wish, and then call `StandardClient()`: - -```go -retryClient := retryablehttp.NewClient() -retryClient.RetryMax = 10 - -standardClient := retryClient.StandardClient() // *http.Client -``` - -For more usage and examples see the -[pkg.go.dev](https://pkg.go.dev/github.com/hashicorp/go-retryablehttp). diff --git a/vendor/github.com/hashicorp/go-retryablehttp/cert_error_go119.go b/vendor/github.com/hashicorp/go-retryablehttp/cert_error_go119.go deleted file mode 100644 index b2b27e872..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/cert_error_go119.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -//go:build !go1.20 -// +build !go1.20 - -package retryablehttp - -import "crypto/x509" - -func isCertError(err error) bool { - _, ok := err.(x509.UnknownAuthorityError) - return ok -} diff --git a/vendor/github.com/hashicorp/go-retryablehttp/cert_error_go120.go b/vendor/github.com/hashicorp/go-retryablehttp/cert_error_go120.go deleted file mode 100644 index a3cd315a2..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/cert_error_go120.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -//go:build go1.20 -// +build go1.20 - -package retryablehttp - -import "crypto/tls" - -func isCertError(err error) bool { - _, ok := err.(*tls.CertificateVerificationError) - return ok -} diff --git a/vendor/github.com/hashicorp/go-retryablehttp/client.go b/vendor/github.com/hashicorp/go-retryablehttp/client.go deleted file mode 100644 index efee53c40..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/client.go +++ /dev/null @@ -1,919 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -// Package retryablehttp provides a familiar HTTP client interface with -// automatic retries and exponential backoff. It is a thin wrapper over the -// standard net/http client library and exposes nearly the same public API. -// This makes retryablehttp very easy to drop into existing programs. -// -// retryablehttp performs automatic retries under certain conditions. Mainly, if -// an error is returned by the client (connection errors etc), or if a 500-range -// response is received, then a retry is invoked. Otherwise, the response is -// returned and left to the caller to interpret. -// -// Requests which take a request body should provide a non-nil function -// parameter. The best choice is to provide either a function satisfying -// ReaderFunc which provides multiple io.Readers in an efficient manner, a -// *bytes.Buffer (the underlying raw byte slice will be used) or a raw byte -// slice. As it is a reference type, and we will wrap it as needed by readers, -// we can efficiently re-use the request body without needing to copy it. If an -// io.Reader (such as a *bytes.Reader) is provided, the full body will be read -// prior to the first request, and will be efficiently re-used for any retries. -// ReadSeeker can be used, but some users have observed occasional data races -// between the net/http library and the Seek functionality of some -// implementations of ReadSeeker, so should be avoided if possible. -package retryablehttp - -import ( - "bytes" - "context" - "fmt" - "io" - "log" - "math" - "math/rand" - "net/http" - "net/url" - "os" - "regexp" - "strconv" - "strings" - "sync" - "time" - - cleanhttp "github.com/hashicorp/go-cleanhttp" -) - -var ( - // Default retry configuration - defaultRetryWaitMin = 1 * time.Second - defaultRetryWaitMax = 30 * time.Second - defaultRetryMax = 4 - - // defaultLogger is the logger provided with defaultClient - defaultLogger = log.New(os.Stderr, "", log.LstdFlags) - - // defaultClient is used for performing requests without explicitly making - // a new client. It is purposely private to avoid modifications. - defaultClient = NewClient() - - // We need to consume response bodies to maintain http connections, but - // limit the size we consume to respReadLimit. - respReadLimit = int64(4096) - - // timeNow sets the function that returns the current time. - // This defaults to time.Now. Changes to this should only be done in tests. - timeNow = time.Now - - // A regular expression to match the error returned by net/http when the - // configured number of redirects is exhausted. This error isn't typed - // specifically so we resort to matching on the error string. - redirectsErrorRe = regexp.MustCompile(`stopped after \d+ redirects\z`) - - // A regular expression to match the error returned by net/http when the - // scheme specified in the URL is invalid. This error isn't typed - // specifically so we resort to matching on the error string. - schemeErrorRe = regexp.MustCompile(`unsupported protocol scheme`) - - // A regular expression to match the error returned by net/http when a - // request header or value is invalid. This error isn't typed - // specifically so we resort to matching on the error string. - invalidHeaderErrorRe = regexp.MustCompile(`invalid header`) - - // A regular expression to match the error returned by net/http when the - // TLS certificate is not trusted. This error isn't typed - // specifically so we resort to matching on the error string. - notTrustedErrorRe = regexp.MustCompile(`certificate is not trusted`) -) - -// ReaderFunc is the type of function that can be given natively to NewRequest -type ReaderFunc func() (io.Reader, error) - -// ResponseHandlerFunc is a type of function that takes in a Response, and does something with it. -// The ResponseHandlerFunc is called when the HTTP client successfully receives a response and the -// CheckRetry function indicates that a retry of the base request is not necessary. -// If an error is returned from this function, the CheckRetry policy will be used to determine -// whether to retry the whole request (including this handler). -// -// Make sure to check status codes! Even if the request was completed it may have a non-2xx status code. -// -// The response body is not automatically closed. It must be closed either by the ResponseHandlerFunc or -// by the caller out-of-band. Failure to do so will result in a memory leak. -type ResponseHandlerFunc func(*http.Response) error - -// LenReader is an interface implemented by many in-memory io.Reader's. Used -// for automatically sending the right Content-Length header when possible. -type LenReader interface { - Len() int -} - -// Request wraps the metadata needed to create HTTP requests. -type Request struct { - // body is a seekable reader over the request body payload. This is - // used to rewind the request data in between retries. - body ReaderFunc - - responseHandler ResponseHandlerFunc - - // Embed an HTTP request directly. This makes a *Request act exactly - // like an *http.Request so that all meta methods are supported. - *http.Request -} - -// WithContext returns wrapped Request with a shallow copy of underlying *http.Request -// with its context changed to ctx. The provided ctx must be non-nil. -func (r *Request) WithContext(ctx context.Context) *Request { - return &Request{ - body: r.body, - responseHandler: r.responseHandler, - Request: r.Request.WithContext(ctx), - } -} - -// SetResponseHandler allows setting the response handler. -func (r *Request) SetResponseHandler(fn ResponseHandlerFunc) { - r.responseHandler = fn -} - -// BodyBytes allows accessing the request body. It is an analogue to -// http.Request's Body variable, but it returns a copy of the underlying data -// rather than consuming it. -// -// This function is not thread-safe; do not call it at the same time as another -// call, or at the same time this request is being used with Client.Do. -func (r *Request) BodyBytes() ([]byte, error) { - if r.body == nil { - return nil, nil - } - body, err := r.body() - if err != nil { - return nil, err - } - buf := new(bytes.Buffer) - _, err = buf.ReadFrom(body) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// SetBody allows setting the request body. -// -// It is useful if a new body needs to be set without constructing a new Request. -func (r *Request) SetBody(rawBody interface{}) error { - bodyReader, contentLength, err := getBodyReaderAndContentLength(rawBody) - if err != nil { - return err - } - r.body = bodyReader - r.ContentLength = contentLength - if bodyReader != nil { - r.GetBody = func() (io.ReadCloser, error) { - body, err := bodyReader() - if err != nil { - return nil, err - } - if rc, ok := body.(io.ReadCloser); ok { - return rc, nil - } - return io.NopCloser(body), nil - } - } else { - r.GetBody = func() (io.ReadCloser, error) { return http.NoBody, nil } - } - return nil -} - -// WriteTo allows copying the request body into a writer. -// -// It writes data to w until there's no more data to write or -// when an error occurs. The return int64 value is the number of bytes -// written. Any error encountered during the write is also returned. -// The signature matches io.WriterTo interface. -func (r *Request) WriteTo(w io.Writer) (int64, error) { - body, err := r.body() - if err != nil { - return 0, err - } - if c, ok := body.(io.Closer); ok { - defer c.Close() - } - return io.Copy(w, body) -} - -func getBodyReaderAndContentLength(rawBody interface{}) (ReaderFunc, int64, error) { - var bodyReader ReaderFunc - var contentLength int64 - - switch body := rawBody.(type) { - // If they gave us a function already, great! Use it. - case ReaderFunc: - bodyReader = body - tmp, err := body() - if err != nil { - return nil, 0, err - } - if lr, ok := tmp.(LenReader); ok { - contentLength = int64(lr.Len()) - } - if c, ok := tmp.(io.Closer); ok { - c.Close() - } - - case func() (io.Reader, error): - bodyReader = body - tmp, err := body() - if err != nil { - return nil, 0, err - } - if lr, ok := tmp.(LenReader); ok { - contentLength = int64(lr.Len()) - } - if c, ok := tmp.(io.Closer); ok { - c.Close() - } - - // If a regular byte slice, we can read it over and over via new - // readers - case []byte: - buf := body - bodyReader = func() (io.Reader, error) { - return bytes.NewReader(buf), nil - } - contentLength = int64(len(buf)) - - // If a bytes.Buffer we can read the underlying byte slice over and - // over - case *bytes.Buffer: - buf := body - bodyReader = func() (io.Reader, error) { - return bytes.NewReader(buf.Bytes()), nil - } - contentLength = int64(buf.Len()) - - // We prioritize *bytes.Reader here because we don't really want to - // deal with it seeking so want it to match here instead of the - // io.ReadSeeker case. - case *bytes.Reader: - snapshot := *body - bodyReader = func() (io.Reader, error) { - r := snapshot - return &r, nil - } - contentLength = int64(body.Len()) - - // Compat case - case io.ReadSeeker: - raw := body - bodyReader = func() (io.Reader, error) { - _, err := raw.Seek(0, 0) - return io.NopCloser(raw), err - } - if lr, ok := raw.(LenReader); ok { - contentLength = int64(lr.Len()) - } - - // Read all in so we can reset - case io.Reader: - buf, err := io.ReadAll(body) - if err != nil { - return nil, 0, err - } - if len(buf) == 0 { - bodyReader = func() (io.Reader, error) { - return http.NoBody, nil - } - contentLength = 0 - } else { - bodyReader = func() (io.Reader, error) { - return bytes.NewReader(buf), nil - } - contentLength = int64(len(buf)) - } - - // No body provided, nothing to do - case nil: - - // Unrecognized type - default: - return nil, 0, fmt.Errorf("cannot handle type %T", rawBody) - } - return bodyReader, contentLength, nil -} - -// FromRequest wraps an http.Request in a retryablehttp.Request -func FromRequest(r *http.Request) (*Request, error) { - bodyReader, _, err := getBodyReaderAndContentLength(r.Body) - if err != nil { - return nil, err - } - // Could assert contentLength == r.ContentLength - return &Request{body: bodyReader, Request: r}, nil -} - -// NewRequest creates a new wrapped request. -func NewRequest(method, url string, rawBody interface{}) (*Request, error) { - return NewRequestWithContext(context.Background(), method, url, rawBody) -} - -// NewRequestWithContext creates a new wrapped request with the provided context. -// -// The context controls the entire lifetime of a request and its response: -// obtaining a connection, sending the request, and reading the response headers and body. -func NewRequestWithContext(ctx context.Context, method, url string, rawBody interface{}) (*Request, error) { - httpReq, err := http.NewRequestWithContext(ctx, method, url, nil) - if err != nil { - return nil, err - } - - req := &Request{ - Request: httpReq, - } - if err := req.SetBody(rawBody); err != nil { - return nil, err - } - - return req, nil -} - -// Logger interface allows to use other loggers than -// standard log.Logger. -type Logger interface { - Printf(string, ...interface{}) -} - -// LeveledLogger is an interface that can be implemented by any logger or a -// logger wrapper to provide leveled logging. The methods accept a message -// string and a variadic number of key-value pairs. For log.Printf style -// formatting where message string contains a format specifier, use Logger -// interface. -type LeveledLogger interface { - Error(msg string, keysAndValues ...interface{}) - Info(msg string, keysAndValues ...interface{}) - Debug(msg string, keysAndValues ...interface{}) - Warn(msg string, keysAndValues ...interface{}) -} - -// hookLogger adapts an LeveledLogger to Logger for use by the existing hook functions -// without changing the API. -type hookLogger struct { - LeveledLogger -} - -func (h hookLogger) Printf(s string, args ...interface{}) { - h.Info(fmt.Sprintf(s, args...)) -} - -// RequestLogHook allows a function to run before each retry. The HTTP -// request which will be made, and the retry number (0 for the initial -// request) are available to users. The internal logger is exposed to -// consumers. -type RequestLogHook func(Logger, *http.Request, int) - -// ResponseLogHook is like RequestLogHook, but allows running a function -// on each HTTP response. This function will be invoked at the end of -// every HTTP request executed, regardless of whether a subsequent retry -// needs to be performed or not. If the response body is read or closed -// from this method, this will affect the response returned from Do(). -type ResponseLogHook func(Logger, *http.Response) - -// CheckRetry specifies a policy for handling retries. It is called -// following each request with the response and error values returned by -// the http.Client. If CheckRetry returns false, the Client stops retrying -// and returns the response to the caller. If CheckRetry returns an error, -// that error value is returned in lieu of the error from the request. The -// Client will close any response body when retrying, but if the retry is -// aborted it is up to the CheckRetry callback to properly close any -// response body before returning. -type CheckRetry func(ctx context.Context, resp *http.Response, err error) (bool, error) - -// Backoff specifies a policy for how long to wait between retries. -// It is called after a failing request to determine the amount of time -// that should pass before trying again. -type Backoff func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration - -// ErrorHandler is called if retries are expired, containing the last status -// from the http library. If not specified, default behavior for the library is -// to close the body and return an error indicating how many tries were -// attempted. If overriding this, be sure to close the body if needed. -type ErrorHandler func(resp *http.Response, err error, numTries int) (*http.Response, error) - -// PrepareRetry is called before retry operation. It can be used for example to re-sign the request -type PrepareRetry func(req *http.Request) error - -// Client is used to make HTTP requests. It adds additional functionality -// like automatic retries to tolerate minor outages. -type Client struct { - HTTPClient *http.Client // Internal HTTP client. - Logger interface{} // Customer logger instance. Can be either Logger or LeveledLogger - - RetryWaitMin time.Duration // Minimum time to wait - RetryWaitMax time.Duration // Maximum time to wait - RetryMax int // Maximum number of retries - - // RequestLogHook allows a user-supplied function to be called - // before each retry. - RequestLogHook RequestLogHook - - // ResponseLogHook allows a user-supplied function to be called - // with the response from each HTTP request executed. - ResponseLogHook ResponseLogHook - - // CheckRetry specifies the policy for handling retries, and is called - // after each request. The default policy is DefaultRetryPolicy. - CheckRetry CheckRetry - - // Backoff specifies the policy for how long to wait between retries - Backoff Backoff - - // ErrorHandler specifies the custom error handler to use, if any - ErrorHandler ErrorHandler - - // PrepareRetry can prepare the request for retry operation, for example re-sign it - PrepareRetry PrepareRetry - - loggerInit sync.Once - clientInit sync.Once -} - -// NewClient creates a new Client with default settings. -func NewClient() *Client { - return &Client{ - HTTPClient: cleanhttp.DefaultPooledClient(), - Logger: defaultLogger, - RetryWaitMin: defaultRetryWaitMin, - RetryWaitMax: defaultRetryWaitMax, - RetryMax: defaultRetryMax, - CheckRetry: DefaultRetryPolicy, - Backoff: DefaultBackoff, - } -} - -func (c *Client) logger() interface{} { - c.loggerInit.Do(func() { - if c.Logger == nil { - return - } - - switch c.Logger.(type) { - case Logger, LeveledLogger: - // ok - default: - // This should happen in dev when they are setting Logger and work on code, not in prod. - panic(fmt.Sprintf("invalid logger type passed, must be Logger or LeveledLogger, was %T", c.Logger)) - } - }) - - return c.Logger -} - -// DefaultRetryPolicy provides a default callback for Client.CheckRetry, which -// will retry on connection errors and server errors. -func DefaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) { - // do not retry on context.Canceled or context.DeadlineExceeded - if ctx.Err() != nil { - return false, ctx.Err() - } - - // don't propagate other errors - shouldRetry, _ := baseRetryPolicy(resp, err) - return shouldRetry, nil -} - -// ErrorPropagatedRetryPolicy is the same as DefaultRetryPolicy, except it -// propagates errors back instead of returning nil. This allows you to inspect -// why it decided to retry or not. -func ErrorPropagatedRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) { - // do not retry on context.Canceled or context.DeadlineExceeded - if ctx.Err() != nil { - return false, ctx.Err() - } - - return baseRetryPolicy(resp, err) -} - -func baseRetryPolicy(resp *http.Response, err error) (bool, error) { - if err != nil { - if v, ok := err.(*url.Error); ok { - // Don't retry if the error was due to too many redirects. - if redirectsErrorRe.MatchString(v.Error()) { - return false, v - } - - // Don't retry if the error was due to an invalid protocol scheme. - if schemeErrorRe.MatchString(v.Error()) { - return false, v - } - - // Don't retry if the error was due to an invalid header. - if invalidHeaderErrorRe.MatchString(v.Error()) { - return false, v - } - - // Don't retry if the error was due to TLS cert verification failure. - if notTrustedErrorRe.MatchString(v.Error()) { - return false, v - } - if isCertError(v.Err) { - return false, v - } - } - - // The error is likely recoverable so retry. - return true, nil - } - - // 429 Too Many Requests is recoverable. Sometimes the server puts - // a Retry-After response header to indicate when the server is - // available to start processing request from client. - if resp.StatusCode == http.StatusTooManyRequests { - return true, nil - } - - // Check the response code. We retry on 500-range responses to allow - // the server time to recover, as 500's are typically not permanent - // errors and may relate to outages on the server side. This will catch - // invalid response codes as well, like 0 and 999. - if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != http.StatusNotImplemented) { - return true, fmt.Errorf("unexpected HTTP status %s", resp.Status) - } - - return false, nil -} - -// DefaultBackoff provides a default callback for Client.Backoff which -// will perform exponential backoff based on the attempt number and limited -// by the provided minimum and maximum durations. -// -// It also tries to parse Retry-After response header when a http.StatusTooManyRequests -// (HTTP Code 429) is found in the resp parameter. Hence it will return the number of -// seconds the server states it may be ready to process more requests from this client. -func DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { - if resp != nil { - if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable { - if sleep, ok := parseRetryAfterHeader(resp.Header["Retry-After"]); ok { - return sleep - } - } - } - - mult := math.Pow(2, float64(attemptNum)) * float64(min) - sleep := time.Duration(mult) - if float64(sleep) != mult || sleep > max { - sleep = max - } - return sleep -} - -// parseRetryAfterHeader parses the Retry-After header and returns the -// delay duration according to the spec: https://httpwg.org/specs/rfc7231.html#header.retry-after -// The bool returned will be true if the header was successfully parsed. -// Otherwise, the header was either not present, or was not parseable according to the spec. -// -// Retry-After headers come in two flavors: Seconds or HTTP-Date -// -// Examples: -// * Retry-After: Fri, 31 Dec 1999 23:59:59 GMT -// * Retry-After: 120 -func parseRetryAfterHeader(headers []string) (time.Duration, bool) { - if len(headers) == 0 || headers[0] == "" { - return 0, false - } - header := headers[0] - // Retry-After: 120 - if sleep, err := strconv.ParseInt(header, 10, 64); err == nil { - if sleep < 0 { // a negative sleep doesn't make sense - return 0, false - } - return time.Second * time.Duration(sleep), true - } - - // Retry-After: Fri, 31 Dec 1999 23:59:59 GMT - retryTime, err := time.Parse(time.RFC1123, header) - if err != nil { - return 0, false - } - if until := retryTime.Sub(timeNow()); until > 0 { - return until, true - } - // date is in the past - return 0, true -} - -// LinearJitterBackoff provides a callback for Client.Backoff which will -// perform linear backoff based on the attempt number and with jitter to -// prevent a thundering herd. -// -// min and max here are *not* absolute values. The number to be multiplied by -// the attempt number will be chosen at random from between them, thus they are -// bounding the jitter. -// -// For instance: -// * To get strictly linear backoff of one second increasing each retry, set -// both to one second (1s, 2s, 3s, 4s, ...) -// * To get a small amount of jitter centered around one second increasing each -// retry, set to around one second, such as a min of 800ms and max of 1200ms -// (892ms, 2102ms, 2945ms, 4312ms, ...) -// * To get extreme jitter, set to a very wide spread, such as a min of 100ms -// and a max of 20s (15382ms, 292ms, 51321ms, 35234ms, ...) -func LinearJitterBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { - // attemptNum always starts at zero but we want to start at 1 for multiplication - attemptNum++ - - if max <= min { - // Unclear what to do here, or they are the same, so return min * - // attemptNum - return min * time.Duration(attemptNum) - } - - // Seed rand; doing this every time is fine - source := rand.New(rand.NewSource(int64(time.Now().Nanosecond()))) - - // Pick a random number that lies somewhere between the min and max and - // multiply by the attemptNum. attemptNum starts at zero so we always - // increment here. We first get a random percentage, then apply that to the - // difference between min and max, and add to min. - jitter := source.Float64() * float64(max-min) - jitterMin := int64(jitter) + int64(min) - return time.Duration(jitterMin * int64(attemptNum)) -} - -// PassthroughErrorHandler is an ErrorHandler that directly passes through the -// values from the net/http library for the final request. The body is not -// closed. -func PassthroughErrorHandler(resp *http.Response, err error, _ int) (*http.Response, error) { - return resp, err -} - -// Do wraps calling an HTTP method with retries. -func (c *Client) Do(req *Request) (*http.Response, error) { - c.clientInit.Do(func() { - if c.HTTPClient == nil { - c.HTTPClient = cleanhttp.DefaultPooledClient() - } - }) - - logger := c.logger() - - if logger != nil { - switch v := logger.(type) { - case LeveledLogger: - v.Debug("performing request", "method", req.Method, "url", redactURL(req.URL)) - case Logger: - v.Printf("[DEBUG] %s %s", req.Method, redactURL(req.URL)) - } - } - - var resp *http.Response - var attempt int - var shouldRetry bool - var doErr, respErr, checkErr, prepareErr error - - for i := 0; ; i++ { - doErr, respErr, prepareErr = nil, nil, nil - attempt++ - - // Always rewind the request body when non-nil. - if req.body != nil { - body, err := req.body() - if err != nil { - c.HTTPClient.CloseIdleConnections() - return resp, err - } - if c, ok := body.(io.ReadCloser); ok { - req.Body = c - } else { - req.Body = io.NopCloser(body) - } - } - - if c.RequestLogHook != nil { - switch v := logger.(type) { - case LeveledLogger: - c.RequestLogHook(hookLogger{v}, req.Request, i) - case Logger: - c.RequestLogHook(v, req.Request, i) - default: - c.RequestLogHook(nil, req.Request, i) - } - } - - // Attempt the request - resp, doErr = c.HTTPClient.Do(req.Request) - - // Check if we should continue with retries. - shouldRetry, checkErr = c.CheckRetry(req.Context(), resp, doErr) - if !shouldRetry && doErr == nil && req.responseHandler != nil { - respErr = req.responseHandler(resp) - shouldRetry, checkErr = c.CheckRetry(req.Context(), resp, respErr) - } - - err := doErr - if respErr != nil { - err = respErr - } - if err != nil { - switch v := logger.(type) { - case LeveledLogger: - v.Error("request failed", "error", err, "method", req.Method, "url", redactURL(req.URL)) - case Logger: - v.Printf("[ERR] %s %s request failed: %v", req.Method, redactURL(req.URL), err) - } - } else { - // Call this here to maintain the behavior of logging all requests, - // even if CheckRetry signals to stop. - if c.ResponseLogHook != nil { - // Call the response logger function if provided. - switch v := logger.(type) { - case LeveledLogger: - c.ResponseLogHook(hookLogger{v}, resp) - case Logger: - c.ResponseLogHook(v, resp) - default: - c.ResponseLogHook(nil, resp) - } - } - } - - if !shouldRetry { - break - } - - // We do this before drainBody because there's no need for the I/O if - // we're breaking out - remain := c.RetryMax - i - if remain <= 0 { - break - } - - // We're going to retry, consume any response to reuse the connection. - if doErr == nil { - c.drainBody(resp.Body) - } - - wait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp) - if logger != nil { - desc := fmt.Sprintf("%s %s", req.Method, redactURL(req.URL)) - if resp != nil { - desc = fmt.Sprintf("%s (status: %d)", desc, resp.StatusCode) - } - switch v := logger.(type) { - case LeveledLogger: - v.Debug("retrying request", "request", desc, "timeout", wait, "remaining", remain) - case Logger: - v.Printf("[DEBUG] %s: retrying in %s (%d left)", desc, wait, remain) - } - } - timer := time.NewTimer(wait) - select { - case <-req.Context().Done(): - timer.Stop() - c.HTTPClient.CloseIdleConnections() - return nil, req.Context().Err() - case <-timer.C: - } - - // Make shallow copy of http Request so that we can modify its body - // without racing against the closeBody call in persistConn.writeLoop. - httpreq := *req.Request - req.Request = &httpreq - - if c.PrepareRetry != nil { - if err := c.PrepareRetry(req.Request); err != nil { - prepareErr = err - break - } - } - } - - // this is the closest we have to success criteria - if doErr == nil && respErr == nil && checkErr == nil && prepareErr == nil && !shouldRetry { - return resp, nil - } - - defer c.HTTPClient.CloseIdleConnections() - - var err error - if prepareErr != nil { - err = prepareErr - } else if checkErr != nil { - err = checkErr - } else if respErr != nil { - err = respErr - } else { - err = doErr - } - - if c.ErrorHandler != nil { - return c.ErrorHandler(resp, err, attempt) - } - - // By default, we close the response body and return an error without - // returning the response - if resp != nil { - c.drainBody(resp.Body) - } - - // this means CheckRetry thought the request was a failure, but didn't - // communicate why - if err == nil { - return nil, fmt.Errorf("%s %s giving up after %d attempt(s)", - req.Method, redactURL(req.URL), attempt) - } - - return nil, fmt.Errorf("%s %s giving up after %d attempt(s): %w", - req.Method, redactURL(req.URL), attempt, err) -} - -// Try to read the response body so we can reuse this connection. -func (c *Client) drainBody(body io.ReadCloser) { - defer body.Close() - _, err := io.Copy(io.Discard, io.LimitReader(body, respReadLimit)) - if err != nil { - if c.logger() != nil { - switch v := c.logger().(type) { - case LeveledLogger: - v.Error("error reading response body", "error", err) - case Logger: - v.Printf("[ERR] error reading response body: %v", err) - } - } - } -} - -// Get is a shortcut for doing a GET request without making a new client. -func Get(url string) (*http.Response, error) { - return defaultClient.Get(url) -} - -// Get is a convenience helper for doing simple GET requests. -func (c *Client) Get(url string) (*http.Response, error) { - req, err := NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return c.Do(req) -} - -// Head is a shortcut for doing a HEAD request without making a new client. -func Head(url string) (*http.Response, error) { - return defaultClient.Head(url) -} - -// Head is a convenience method for doing simple HEAD requests. -func (c *Client) Head(url string) (*http.Response, error) { - req, err := NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return c.Do(req) -} - -// Post is a shortcut for doing a POST request without making a new client. -func Post(url, bodyType string, body interface{}) (*http.Response, error) { - return defaultClient.Post(url, bodyType, body) -} - -// Post is a convenience method for doing simple POST requests. -func (c *Client) Post(url, bodyType string, body interface{}) (*http.Response, error) { - req, err := NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return c.Do(req) -} - -// PostForm is a shortcut to perform a POST with form data without creating -// a new client. -func PostForm(url string, data url.Values) (*http.Response, error) { - return defaultClient.PostForm(url, data) -} - -// PostForm is a convenience method for doing simple POST operations using -// pre-filled url.Values form data. -func (c *Client) PostForm(url string, data url.Values) (*http.Response, error) { - return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} - -// StandardClient returns a stdlib *http.Client with a custom Transport, which -// shims in a *retryablehttp.Client for added retries. -func (c *Client) StandardClient() *http.Client { - return &http.Client{ - Transport: &RoundTripper{Client: c}, - } -} - -// Taken from url.URL#Redacted() which was introduced in go 1.15. -// We can switch to using it directly if we'll bump the minimum required go version. -func redactURL(u *url.URL) string { - if u == nil { - return "" - } - - ru := *u - if _, has := ru.User.Password(); has { - ru.User = url.UserPassword(ru.User.Username(), "xxxxx") - } - return ru.String() -} diff --git a/vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go b/vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go deleted file mode 100644 index 8c407adb3..000000000 --- a/vendor/github.com/hashicorp/go-retryablehttp/roundtripper.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package retryablehttp - -import ( - "errors" - "net/http" - "net/url" - "sync" -) - -// RoundTripper implements the http.RoundTripper interface, using a retrying -// HTTP client to execute requests. -// -// It is important to note that retryablehttp doesn't always act exactly as a -// RoundTripper should. This is highly dependent on the retryable client's -// configuration. -type RoundTripper struct { - // The client to use during requests. If nil, the default retryablehttp - // client and settings will be used. - Client *Client - - // once ensures that the logic to initialize the default client runs at - // most once, in a single thread. - once sync.Once -} - -// init initializes the underlying retryable client. -func (rt *RoundTripper) init() { - if rt.Client == nil { - rt.Client = NewClient() - } -} - -// RoundTrip satisfies the http.RoundTripper interface. -func (rt *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - rt.once.Do(rt.init) - - // Convert the request to be retryable. - retryableReq, err := FromRequest(req) - if err != nil { - return nil, err - } - - // Execute the request. - resp, err := rt.Client.Do(retryableReq) - // If we got an error returned by standard library's `Do` method, unwrap it - // otherwise we will wind up erroneously re-nesting the error. - if _, ok := err.(*url.Error); ok { - return resp, errors.Unwrap(err) - } - - return resp, err -} diff --git a/vendor/github.com/invopop/yaml/.gitignore b/vendor/github.com/invopop/yaml/.gitignore deleted file mode 100644 index e256a31e0..000000000 --- a/vendor/github.com/invopop/yaml/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -# OSX leaves these everywhere on SMB shares -._* - -# Eclipse files -.classpath -.project -.settings/** - -# Emacs save files -*~ - -# Vim-related files -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -*.un~ -Session.vim -.netrwhist - -# Go test binaries -*.test diff --git a/vendor/github.com/invopop/yaml/.golangci.toml b/vendor/github.com/invopop/yaml/.golangci.toml deleted file mode 100644 index 61b2b79a2..000000000 --- a/vendor/github.com/invopop/yaml/.golangci.toml +++ /dev/null @@ -1,16 +0,0 @@ -[run] -timeout = "120s" - -[output] -format = "colored-line-number" - -[linters] -enable = [ - "gocyclo", "unconvert", "goimports", "unused", "unused", - "vetshadow", "nakedret", "errcheck", "revive", "ineffassign", - "goconst", "vet", "unparam", "gofmt" -] - -[issues] -exclude-use-default = false - diff --git a/vendor/github.com/invopop/yaml/LICENSE b/vendor/github.com/invopop/yaml/LICENSE deleted file mode 100644 index 7805d36de..000000000 --- a/vendor/github.com/invopop/yaml/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Sam Ghods - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - -Copyright (c) 2012 The Go Authors. 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 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/vendor/github.com/invopop/yaml/README.md b/vendor/github.com/invopop/yaml/README.md deleted file mode 100644 index 2c33dfe59..000000000 --- a/vendor/github.com/invopop/yaml/README.md +++ /dev/null @@ -1,128 +0,0 @@ -# YAML marshaling and unmarshaling support for Go - -[![Lint](https://github.com/invopop/yaml/actions/workflows/lint.yaml/badge.svg)](https://github.com/invopop/yaml/actions/workflows/lint.yaml) -[![Test Go](https://github.com/invopop/yaml/actions/workflows/test.yaml/badge.svg)](https://github.com/invopop/yaml/actions/workflows/test.yaml) -[![Go Report Card](https://goreportcard.com/badge/github.com/invopop/yaml)](https://goreportcard.com/report/github.com/invopop/yaml) -![Latest Tag](https://img.shields.io/github/v/tag/invopop/yaml) - -## Introduction - -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. - -This is a fork and split of the original [ghodss/yaml](https://github.com/ghodss/yaml) repository which no longer appears to be maintained. - -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](https://web.archive.org/web/20150812020634/http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). - -## Compatibility - -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). - -Tested against Go versions 1.14 and onwards. - -## Caveats - -**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: - -``` -BAD: - exampleKey: !!binary gIGC - -GOOD: - exampleKey: gIGC -... and decode the base64 data in your code. -``` - -**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. - -## Installation and usage - -To install, run: - -``` -$ go get github.com/invopop/yaml -``` - -And import using: - -``` -import "github.com/invopop/yaml" -``` - -Usage is very similar to the JSON library: - -```go -package main - -import ( - "fmt" - - "github.com/invopop/yaml" -) - -type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` -} - -func main() { - // Marshal a Person struct to YAML. - p := Person{"John", 30} - y, err := yaml.Marshal(p) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - age: 30 - name: John - */ - - // Unmarshal the YAML back into a Person struct. - var p2 Person - err = yaml.Unmarshal(y, &p2) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(p2) - /* Output: - {John 30} - */ -} -``` - -`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: - -```go -package main - -import ( - "fmt" - - "github.com/invopop/yaml" -) - -func main() { - j := []byte(`{"name": "John", "age": 30}`) - y, err := yaml.JSONToYAML(j) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - name: John - age: 30 - */ - j2, err := yaml.YAMLToJSON(y) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(j2)) - /* Output: - {"age":30,"name":"John"} - */ -} -``` diff --git a/vendor/github.com/invopop/yaml/fields.go b/vendor/github.com/invopop/yaml/fields.go deleted file mode 100644 index 3fe5f12fd..000000000 --- a/vendor/github.com/invopop/yaml/fields.go +++ /dev/null @@ -1,499 +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. - -package yaml - -import ( - "bytes" - "encoding" - "encoding/json" - "reflect" - "sort" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } else { - v = reflect.New(v.Type().Elem()) - } - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(json.Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// A field represents a single field found in a struct. -type field struct { - name string - nameBytes []byte // []byte(name) - equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - - tag bool - index []int - typ reflect.Type - omitEmpty bool - quoted bool -} - -func fillField(f field) field { - f.nameBytes = []byte(f.name) - f.equalFold = foldFunc(f.nameBytes) - return f -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from json tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that JSON should recognize for the given type. -// The algorithm is breadth-first search over the set of structs to include - the top struct -// and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - var count, nextCount map[reflect.Type]int - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" { // unexported - continue - } - tag := sf.Tag.Get("json") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if !isValidTag(name) { - name = "" - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := name != "" - if name == "" { - name = sf.Name - } - fields = append(fields, fillField(field{ - name: name, - tag: tagged, - index: index, - typ: ft, - omitEmpty: opts.Contains("omitempty"), - quoted: opts.Contains("string"), - })) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with JSON tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// JSON tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -const ( - caseMask = ^byte(0x20) // Mask to ignore case in ASCII. - kelvin = '\u212a' - smallLongEss = '\u017f' -) - -// foldFunc returns one of four different case folding equivalence -// functions, from most general (and slow) to fastest: -// -// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 -// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') -// 3) asciiEqualFold, no special, but includes non-letters (including _) -// 4) simpleLetterEqualFold, no specials, no non-letters. -// -// The letters S and K are special because they map to 3 runes, not just 2: -// - S maps to s and to U+017F 'ſ' Latin small letter long s -// - k maps to K and to U+212A 'K' Kelvin sign -// -// See http://play.golang.org/p/tTxjOc0OGo -// -// The returned function is specialized for matching against s and -// should only be given s. It's not curried for performance reasons. -func foldFunc(s []byte) func(s, t []byte) bool { - nonLetter := false - special := false // special letter - for _, b := range s { - if b >= utf8.RuneSelf { - return bytes.EqualFold - } - upper := b & caseMask - if upper < 'A' || upper > 'Z' { - nonLetter = true - } else if upper == 'K' || upper == 'S' { - // See above for why these letters are special. - special = true - } - } - if special { - return equalFoldRight - } - if nonLetter { - return asciiEqualFold - } - return simpleLetterEqualFold -} - -// equalFoldRight is a specialization of bytes.EqualFold when s is -// known to be all ASCII (including punctuation), but contains an 's', -// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. -// See comments on foldFunc. -func equalFoldRight(s, t []byte) bool { - for _, sb := range s { - if len(t) == 0 { - return false - } - tb := t[0] - if tb < utf8.RuneSelf { - if sb != tb { - sbUpper := sb & caseMask - if 'A' <= sbUpper && sbUpper <= 'Z' { - if sbUpper != tb&caseMask { - return false - } - } else { - return false - } - } - t = t[1:] - continue - } - // sb is ASCII and t is not. t must be either kelvin - // sign or long s; sb must be s, S, k, or K. - tr, size := utf8.DecodeRune(t) - switch sb { - case 's', 'S': - if tr != smallLongEss { - return false - } - case 'k', 'K': - if tr != kelvin { - return false - } - default: - return false - } - t = t[size:] - - } - return len(t) <= 0 -} - -// asciiEqualFold is a specialization of bytes.EqualFold for use when -// s is all ASCII (but may contain non-letters) and contains no -// special-folding letters. -// See comments on foldFunc. -func asciiEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, sb := range s { - tb := t[i] - if sb == tb { - continue - } - if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { - if sb&caseMask != tb&caseMask { - return false - } - } else { - return false - } - } - return true -} - -// simpleLetterEqualFold is a specialization of bytes.EqualFold for -// use when s is all ASCII letters (no underscores, etc) and also -// doesn't contain 'k', 'K', 's', or 'S'. -// See comments on foldFunc. -func simpleLetterEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, b := range s { - if b&caseMask != t[i]&caseMask { - return false - } - } - return true -} - -// tagOptions is the string following a comma in a struct field's "json" -// tag, or the empty string. It does not include the leading comma. -type tagOptions string - -// parseTag splits a struct field's json tag into its name and -// comma-separated options. -func parseTag(tag string) (string, tagOptions) { - if idx := strings.Index(tag, ","); idx != -1 { - return tag[:idx], tagOptions(tag[idx+1:]) - } - return tag, tagOptions("") -} - -// Contains reports whether a comma-separated list of options -// contains a particular substr flag. substr must be surrounded by a -// string boundary or commas. -func (o tagOptions) Contains(optionName string) bool { - if len(o) == 0 { - return false - } - s := string(o) - for s != "" { - var next string - i := strings.Index(s, ",") - if i >= 0 { - s, next = s[:i], s[i+1:] - } - if s == optionName { - return true - } - s = next - } - return false -} diff --git a/vendor/github.com/invopop/yaml/yaml.go b/vendor/github.com/invopop/yaml/yaml.go deleted file mode 100644 index d57dfb10b..000000000 --- a/vendor/github.com/invopop/yaml/yaml.go +++ /dev/null @@ -1,312 +0,0 @@ -// Package yaml provides a wrapper around go-yaml designed to enable a better -// way of handling YAML when marshaling to and from structs. -// -// In short, this package first converts YAML to JSON using go-yaml and then -// uses json.Marshal and json.Unmarshal to convert to or from the struct. This -// means that it effectively reuses the JSON struct tags as well as the custom -// JSON methods MarshalJSON and UnmarshalJSON unlike go-yaml. -package yaml // import "github.com/invopop/yaml" - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "reflect" - "strconv" - - "gopkg.in/yaml.v3" -) - -// Marshal the object into JSON then converts JSON to YAML and returns the -// YAML. -func Marshal(o interface{}) ([]byte, error) { - j, err := json.Marshal(o) - if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) - } - - y, err := JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) - } - - return y, nil -} - -// JSONOpt is a decoding option for decoding from JSON format. -type JSONOpt func(*json.Decoder) *json.Decoder - -// Unmarshal converts YAML to JSON then uses JSON to unmarshal into an object, -// optionally configuring the behavior of the JSON unmarshal. -func Unmarshal(y []byte, o interface{}, opts ...JSONOpt) error { - dec := yaml.NewDecoder(bytes.NewReader(y)) - return unmarshal(dec, o, opts) -} - -func unmarshal(dec *yaml.Decoder, o interface{}, opts []JSONOpt) error { - vo := reflect.ValueOf(o) - j, err := yamlToJSON(dec, &vo) - if err != nil { - return fmt.Errorf("error converting YAML to JSON: %v", err) - } - - err = jsonUnmarshal(bytes.NewReader(j), o, opts...) - if err != nil { - return fmt.Errorf("error unmarshaling JSON: %v", err) - } - - return nil -} - -// jsonUnmarshal unmarshals the JSON byte stream from the given reader into the -// object, optionally applying decoder options prior to decoding. We are not -// using json.Unmarshal directly as we want the chance to pass in non-default -// options. -func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error { - d := json.NewDecoder(r) - for _, opt := range opts { - d = opt(d) - } - if err := d.Decode(&o); err != nil { - return fmt.Errorf("while decoding JSON: %v", err) - } - return nil -} - -// JSONToYAML converts JSON to YAML. -func JSONToYAML(j []byte) ([]byte, error) { - // Convert the JSON to an object. - var jsonObj interface{} - // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the - // Go JSON library doesn't try to pick the right number type (int, float, - // etc.) when unmarshalling to interface{}, it just picks float64 - // universally. go-yaml does go through the effort of picking the right - // number type, so we can preserve number type throughout this process. - err := yaml.Unmarshal(j, &jsonObj) - if err != nil { - return nil, err - } - - // Marshal this object into YAML. - return yaml.Marshal(jsonObj) -} - -// YAMLToJSON converts YAML to JSON. Since JSON is a subset of YAML, -// passing JSON through this method should be a no-op. -// -// Things YAML can do that are not supported by JSON: -// - In YAML you can have binary and null keys in your maps. These are invalid -// in JSON. (int and float keys are converted to strings.) -// - Binary data in YAML with the !!binary tag is not supported. If you want to -// use binary data with this library, encode the data as base64 as usual but do -// not use the !!binary tag in your YAML. This will ensure the original base64 -// encoded data makes it all the way through to the JSON. -func YAMLToJSON(y []byte) ([]byte, error) { //nolint:revive - dec := yaml.NewDecoder(bytes.NewReader(y)) - return yamlToJSON(dec, nil) -} - -func yamlToJSON(dec *yaml.Decoder, jsonTarget *reflect.Value) ([]byte, error) { - // Convert the YAML to an object. - var yamlObj interface{} - if err := dec.Decode(&yamlObj); err != nil { - // Functionality changed in v3 which means we need to ignore EOF error. - // See https://github.com/go-yaml/yaml/issues/639 - if !errors.Is(err, io.EOF) { - return nil, err - } - } - - // YAML objects are not completely compatible with JSON objects (e.g. you - // can have non-string keys in YAML). So, convert the YAML-compatible object - // to a JSON-compatible object, failing with an error if irrecoverable - // incompatibilities happen along the way. - jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) - if err != nil { - return nil, err - } - - // Convert this object to JSON and return the data. - return json.Marshal(jsonObj) -} - -func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { //nolint:gocyclo - var err error - - // Resolve jsonTarget to a concrete value (i.e. not a pointer or an - // interface). We pass decodingNull as false because we're not actually - // decoding into the value, we're just checking if the ultimate target is a - // string. - if jsonTarget != nil { - ju, tu, pv := indirect(*jsonTarget, false) - // We have a JSON or Text Umarshaler at this level, so we can't be trying - // to decode into a string. - if ju != nil || tu != nil { - jsonTarget = nil - } else { - jsonTarget = &pv - } - } - - // go-yaml v3 changed from v2 and now will provide map[string]interface{} by - // default and map[interface{}]interface{} when none of the keys strings. - // To get around this, we run a pre-loop to convert the map. - // JSON only supports strings as keys, so we must convert. - - switch typedYAMLObj := yamlObj.(type) { - case map[interface{}]interface{}: - // From my reading of go-yaml v2 (specifically the resolve function), - // keys can only have the types string, int, int64, float64, binary - // (unsupported), or null (unsupported). - strMap := make(map[string]interface{}) - for k, v := range typedYAMLObj { - // Resolve the key to a string first. - var keyString string - switch typedKey := k.(type) { - case string: - keyString = typedKey - case int: - keyString = strconv.Itoa(typedKey) - case int64: - // go-yaml will only return an int64 as a key if the system - // architecture is 32-bit and the key's value is between 32-bit - // and 64-bit. Otherwise the key type will simply be int. - keyString = strconv.FormatInt(typedKey, 10) - case float64: - // Float64 is now supported in keys - keyString = strconv.FormatFloat(typedKey, 'g', -1, 64) - case bool: - if typedKey { - keyString = "true" - } else { - keyString = "false" - } - default: - return nil, fmt.Errorf("unsupported map key of type: %s, key: %+#v, value: %+#v", - reflect.TypeOf(k), k, v) - } - strMap[keyString] = v - } - // replace yamlObj with our new string map - yamlObj = strMap - } - - // If yamlObj is a number or a boolean, check if jsonTarget is a string - - // if so, coerce. Else return normal. - // If yamlObj is a map or array, find the field that each key is - // unmarshaling to, and when you recurse pass the reflect.Value for that - // field back into this function. - switch typedYAMLObj := yamlObj.(type) { - case map[string]interface{}: - for k, v := range typedYAMLObj { - - // jsonTarget should be a struct or a map. If it's a struct, find - // the field it's going to map to and pass its reflect.Value. If - // it's a map, find the element type of the map and pass the - // reflect.Value created from that type. If it's neither, just pass - // nil - JSON conversion will error for us if it's a real issue. - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Struct { - keyBytes := []byte(k) - // Find the field that the JSON library would use. - var f *field - fields := cachedTypeFields(t.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, keyBytes) { - f = ff - break - } - // Do case-insensitive comparison. - if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { - f = ff - } - } - if f != nil { - // Find the reflect.Value of the most preferential - // struct field. - jtf := t.Field(f.index[0]) - typedYAMLObj[k], err = convertToJSONableObject(v, &jtf) - if err != nil { - return nil, err - } - continue - } - } else if t.Kind() == reflect.Map { - // Create a zero value of the map's element type to use as - // the JSON target. - jtv := reflect.Zero(t.Type().Elem()) - typedYAMLObj[k], err = convertToJSONableObject(v, &jtv) - if err != nil { - return nil, err - } - continue - } - } - typedYAMLObj[k], err = convertToJSONableObject(v, nil) - if err != nil { - return nil, err - } - } - return typedYAMLObj, nil - case []interface{}: - // We need to recurse into arrays in case there are any - // map[interface{}]interface{}'s inside and to convert any - // numbers to strings. - - // If jsonTarget is a slice (which it really should be), find the - // thing it's going to map to. If it's not a slice, just pass nil - // - JSON conversion will error for us if it's a real issue. - var jsonSliceElemValue *reflect.Value - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Slice { - // By default slices point to nil, but we need a reflect.Value - // pointing to a value of the slice type, so we create one here. - ev := reflect.Indirect(reflect.New(t.Type().Elem())) - jsonSliceElemValue = &ev - } - } - - // Make and use a new array. - arr := make([]interface{}, len(typedYAMLObj)) - for i, v := range typedYAMLObj { - arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) - if err != nil { - return nil, err - } - } - return arr, nil - default: - // If the target type is a string and the YAML type is a number, - // convert the YAML type to a string. - if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { - // Based on my reading of go-yaml, it may return int, int64, - // float64, or uint64. - var s string - switch typedVal := typedYAMLObj.(type) { - case int: - s = strconv.FormatInt(int64(typedVal), 10) - case int64: - s = strconv.FormatInt(typedVal, 10) - case float64: - s = strconv.FormatFloat(typedVal, 'g', -1, 64) - case uint64: - s = strconv.FormatUint(typedVal, 10) - case bool: - if typedVal { - s = "true" - } else { - s = "false" - } - } - if len(s) > 0 { - yamlObj = interface{}(s) - } - } - return yamlObj, nil - } -} diff --git a/vendor/github.com/jackc/pgerrcode/LICENSE b/vendor/github.com/jackc/pgerrcode/LICENSE deleted file mode 100644 index 9aeb1f331..000000000 --- a/vendor/github.com/jackc/pgerrcode/LICENSE +++ /dev/null @@ -1,46 +0,0 @@ -Copyright (c) 2019 Jack Christensen - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---- - -Underlying Data Under PostgreSQL License: - -PostgreSQL Database Management System -(formerly known as Postgres, then as Postgres95) - -Portions Copyright © 1996-2019, The PostgreSQL Global Development Group - -Portions Copyright © 1994, The Regents of the University of California - -Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and -without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the -following two paragraphs appear in all copies. - -IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR -CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF -THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" -BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR -MODIFICATIONS. diff --git a/vendor/github.com/jackc/pgerrcode/README.md b/vendor/github.com/jackc/pgerrcode/README.md deleted file mode 100644 index 536f5e5ea..000000000 --- a/vendor/github.com/jackc/pgerrcode/README.md +++ /dev/null @@ -1,9 +0,0 @@ -[![](https://godoc.org/github.com/jackc/pgerrcode?status.svg)](https://godoc.org/github.com/jackc/pgerrcode) - -# pgerrcode - -Package pgerrcode contains constants for PostgreSQL error codes. - -## License - -MIT for this package's code and PostgreSQL License for the underlying data. diff --git a/vendor/github.com/jackc/pgerrcode/errcode.go b/vendor/github.com/jackc/pgerrcode/errcode.go deleted file mode 100644 index e2683502e..000000000 --- a/vendor/github.com/jackc/pgerrcode/errcode.go +++ /dev/null @@ -1,741 +0,0 @@ -// Package pgerrcode contains constants for PostgreSQL error codes. -package pgerrcode - -// Source: https://www.postgresql.org/docs/16/errcodes-appendix.html -// See gen.rb for script that can convert the error code table to Go code. - -const ( - - // Class 00 — Successful Completion - SuccessfulCompletion = "00000" - - // Class 01 — Warning - Warning = "01000" - DynamicResultSetsReturned = "0100C" - ImplicitZeroBitPadding = "01008" - NullValueEliminatedInSetFunction = "01003" - PrivilegeNotGranted = "01007" - PrivilegeNotRevoked = "01006" - StringDataRightTruncationWarning = "01004" - DeprecatedFeature = "01P01" - - // Class 02 — No Data (this is also a warning class per the SQL standard) - NoData = "02000" - NoAdditionalDynamicResultSetsReturned = "02001" - - // Class 03 — SQL Statement Not Yet Complete - SQLStatementNotYetComplete = "03000" - - // Class 08 — Connection Exception - ConnectionException = "08000" - ConnectionDoesNotExist = "08003" - ConnectionFailure = "08006" - SQLClientUnableToEstablishSQLConnection = "08001" - SQLServerRejectedEstablishmentOfSQLConnection = "08004" - TransactionResolutionUnknown = "08007" - ProtocolViolation = "08P01" - - // Class 09 — Triggered Action Exception - TriggeredActionException = "09000" - - // Class 0A — Feature Not Supported - FeatureNotSupported = "0A000" - - // Class 0B — Invalid Transaction Initiation - InvalidTransactionInitiation = "0B000" - - // Class 0F — Locator Exception - LocatorException = "0F000" - InvalidLocatorSpecification = "0F001" - - // Class 0L — Invalid Grantor - InvalidGrantor = "0L000" - InvalidGrantOperation = "0LP01" - - // Class 0P — Invalid Role Specification - InvalidRoleSpecification = "0P000" - - // Class 0Z — Diagnostics Exception - DiagnosticsException = "0Z000" - StackedDiagnosticsAccessedWithoutActiveHandler = "0Z002" - - // Class 20 — Case Not Found - CaseNotFound = "20000" - - // Class 21 — Cardinality Violation - CardinalityViolation = "21000" - - // Class 22 — Data Exception - DataException = "22000" - ArraySubscriptError = "2202E" - CharacterNotInRepertoire = "22021" - DatetimeFieldOverflow = "22008" - DivisionByZero = "22012" - ErrorInAssignment = "22005" - EscapeCharacterConflict = "2200B" - IndicatorOverflow = "22022" - IntervalFieldOverflow = "22015" - InvalidArgumentForLogarithm = "2201E" - InvalidArgumentForNtileFunction = "22014" - InvalidArgumentForNthValueFunction = "22016" - InvalidArgumentForPowerFunction = "2201F" - InvalidArgumentForWidthBucketFunction = "2201G" - InvalidCharacterValueForCast = "22018" - InvalidDatetimeFormat = "22007" - InvalidEscapeCharacter = "22019" - InvalidEscapeOctet = "2200D" - InvalidEscapeSequence = "22025" - NonstandardUseOfEscapeCharacter = "22P06" - InvalidIndicatorParameterValue = "22010" - InvalidParameterValue = "22023" - InvalidPrecedingOrFollowingSize = "22013" - InvalidRegularExpression = "2201B" - InvalidRowCountInLimitClause = "2201W" - InvalidRowCountInResultOffsetClause = "2201X" - InvalidTablesampleArgument = "2202H" - InvalidTablesampleRepeat = "2202G" - InvalidTimeZoneDisplacementValue = "22009" - InvalidUseOfEscapeCharacter = "2200C" - MostSpecificTypeMismatch = "2200G" - NullValueNotAllowedDataException = "22004" - NullValueNoIndicatorParameter = "22002" - NumericValueOutOfRange = "22003" - SequenceGeneratorLimitExceeded = "2200H" - StringDataLengthMismatch = "22026" - StringDataRightTruncationDataException = "22001" - SubstringError = "22011" - TrimError = "22027" - UnterminatedCString = "22024" - ZeroLengthCharacterString = "2200F" - FloatingPointException = "22P01" - InvalidTextRepresentation = "22P02" - InvalidBinaryRepresentation = "22P03" - BadCopyFileFormat = "22P04" - UntranslatableCharacter = "22P05" - NotAnXMLDocument = "2200L" - InvalidXMLDocument = "2200M" - InvalidXMLContent = "2200N" - InvalidXMLComment = "2200S" - InvalidXMLProcessingInstruction = "2200T" - DuplicateJSONObjectKeyValue = "22030" - InvalidArgumentForSQLJSONDatetimeFunction = "22031" - InvalidJSONText = "22032" - InvalidSQLJSONSubscript = "22033" - MoreThanOneSQLJSONItem = "22034" - NoSQLJSONItem = "22035" - NonNumericSQLJSONItem = "22036" - NonUniqueKeysInAJSONObject = "22037" - SingletonSQLJSONItemRequired = "22038" - SQLJSONArrayNotFound = "22039" - SQLJSONMemberNotFound = "2203A" - SQLJSONNumberNotFound = "2203B" - SQLJSONObjectNotFound = "2203C" - TooManyJSONArrayElements = "2203D" - TooManyJSONObjectMembers = "2203E" - SQLJSONScalarRequired = "2203F" - SQLJSONItemCannotBeCastToTargetType = "2203G" - - // Class 23 — Integrity Constraint Violation - IntegrityConstraintViolation = "23000" - RestrictViolation = "23001" - NotNullViolation = "23502" - ForeignKeyViolation = "23503" - UniqueViolation = "23505" - CheckViolation = "23514" - ExclusionViolation = "23P01" - - // Class 24 — Invalid Cursor State - InvalidCursorState = "24000" - - // Class 25 — Invalid Transaction State - InvalidTransactionState = "25000" - ActiveSQLTransaction = "25001" - BranchTransactionAlreadyActive = "25002" - HeldCursorRequiresSameIsolationLevel = "25008" - InappropriateAccessModeForBranchTransaction = "25003" - InappropriateIsolationLevelForBranchTransaction = "25004" - NoActiveSQLTransactionForBranchTransaction = "25005" - ReadOnlySQLTransaction = "25006" - SchemaAndDataStatementMixingNotSupported = "25007" - NoActiveSQLTransaction = "25P01" - InFailedSQLTransaction = "25P02" - IdleInTransactionSessionTimeout = "25P03" - - // Class 26 — Invalid SQL Statement Name - InvalidSQLStatementName = "26000" - - // Class 27 — Triggered Data Change Violation - TriggeredDataChangeViolation = "27000" - - // Class 28 — Invalid Authorization Specification - InvalidAuthorizationSpecification = "28000" - InvalidPassword = "28P01" - - // Class 2B — Dependent Privilege Descriptors Still Exist - DependentPrivilegeDescriptorsStillExist = "2B000" - DependentObjectsStillExist = "2BP01" - - // Class 2D — Invalid Transaction Termination - InvalidTransactionTermination = "2D000" - - // Class 2F — SQL Routine Exception - SQLRoutineException = "2F000" - FunctionExecutedNoReturnStatement = "2F005" - ModifyingSQLDataNotPermittedSQLRoutineException = "2F002" - ProhibitedSQLStatementAttemptedSQLRoutineException = "2F003" - ReadingSQLDataNotPermittedSQLRoutineException = "2F004" - - // Class 34 — Invalid Cursor Name - InvalidCursorName = "34000" - - // Class 38 — External Routine Exception - ExternalRoutineException = "38000" - ContainingSQLNotPermitted = "38001" - ModifyingSQLDataNotPermittedExternalRoutineException = "38002" - ProhibitedSQLStatementAttemptedExternalRoutineException = "38003" - ReadingSQLDataNotPermittedExternalRoutineException = "38004" - - // Class 39 — External Routine Invocation Exception - ExternalRoutineInvocationException = "39000" - InvalidSQLstateReturned = "39001" - NullValueNotAllowedExternalRoutineInvocationException = "39004" - TriggerProtocolViolated = "39P01" - SRFProtocolViolated = "39P02" - EventTriggerProtocolViolated = "39P03" - - // Class 3B — Savepoint Exception - SavepointException = "3B000" - InvalidSavepointSpecification = "3B001" - - // Class 3D — Invalid Catalog Name - InvalidCatalogName = "3D000" - - // Class 3F — Invalid Schema Name - InvalidSchemaName = "3F000" - - // Class 40 — Transaction Rollback - TransactionRollback = "40000" - TransactionIntegrityConstraintViolation = "40002" - SerializationFailure = "40001" - StatementCompletionUnknown = "40003" - DeadlockDetected = "40P01" - - // Class 42 — Syntax Error or Access Rule Violation - SyntaxErrorOrAccessRuleViolation = "42000" - SyntaxError = "42601" - InsufficientPrivilege = "42501" - CannotCoerce = "42846" - GroupingError = "42803" - WindowingError = "42P20" - InvalidRecursion = "42P19" - InvalidForeignKey = "42830" - InvalidName = "42602" - NameTooLong = "42622" - ReservedName = "42939" - DatatypeMismatch = "42804" - IndeterminateDatatype = "42P18" - CollationMismatch = "42P21" - IndeterminateCollation = "42P22" - WrongObjectType = "42809" - GeneratedAlways = "428C9" - UndefinedColumn = "42703" - UndefinedFunction = "42883" - UndefinedTable = "42P01" - UndefinedParameter = "42P02" - UndefinedObject = "42704" - DuplicateColumn = "42701" - DuplicateCursor = "42P03" - DuplicateDatabase = "42P04" - DuplicateFunction = "42723" - DuplicatePreparedStatement = "42P05" - DuplicateSchema = "42P06" - DuplicateTable = "42P07" - DuplicateAlias = "42712" - DuplicateObject = "42710" - AmbiguousColumn = "42702" - AmbiguousFunction = "42725" - AmbiguousParameter = "42P08" - AmbiguousAlias = "42P09" - InvalidColumnReference = "42P10" - InvalidColumnDefinition = "42611" - InvalidCursorDefinition = "42P11" - InvalidDatabaseDefinition = "42P12" - InvalidFunctionDefinition = "42P13" - InvalidPreparedStatementDefinition = "42P14" - InvalidSchemaDefinition = "42P15" - InvalidTableDefinition = "42P16" - InvalidObjectDefinition = "42P17" - - // Class 44 — WITH CHECK OPTION Violation - WithCheckOptionViolation = "44000" - - // Class 53 — Insufficient Resources - InsufficientResources = "53000" - DiskFull = "53100" - OutOfMemory = "53200" - TooManyConnections = "53300" - ConfigurationLimitExceeded = "53400" - - // Class 54 — Program Limit Exceeded - ProgramLimitExceeded = "54000" - StatementTooComplex = "54001" - TooManyColumns = "54011" - TooManyArguments = "54023" - - // Class 55 — Object Not In Prerequisite State - ObjectNotInPrerequisiteState = "55000" - ObjectInUse = "55006" - CantChangeRuntimeParam = "55P02" - LockNotAvailable = "55P03" - UnsafeNewEnumValueUsage = "55P04" - - // Class 57 — Operator Intervention - OperatorIntervention = "57000" - QueryCanceled = "57014" - AdminShutdown = "57P01" - CrashShutdown = "57P02" - CannotConnectNow = "57P03" - DatabaseDropped = "57P04" - IdleSessionTimeout = "57P05" - - // Class 58 — System Error (errors external to PostgreSQL itself) - SystemError = "58000" - IOError = "58030" - UndefinedFile = "58P01" - DuplicateFile = "58P02" - - // Class 72 — Snapshot Failure - SnapshotTooOld = "72000" - - // Class F0 — Configuration File Error - ConfigFileError = "F0000" - LockFileExists = "F0001" - - // Class HV — Foreign Data Wrapper Error (SQL/MED) - FDWError = "HV000" - FDWColumnNameNotFound = "HV005" - FDWDynamicParameterValueNeeded = "HV002" - FDWFunctionSequenceError = "HV010" - FDWInconsistentDescriptorInformation = "HV021" - FDWInvalidAttributeValue = "HV024" - FDWInvalidColumnName = "HV007" - FDWInvalidColumnNumber = "HV008" - FDWInvalidDataType = "HV004" - FDWInvalidDataTypeDescriptors = "HV006" - FDWInvalidDescriptorFieldIdentifier = "HV091" - FDWInvalidHandle = "HV00B" - FDWInvalidOptionIndex = "HV00C" - FDWInvalidOptionName = "HV00D" - FDWInvalidStringLengthOrBufferLength = "HV090" - FDWInvalidStringFormat = "HV00A" - FDWInvalidUseOfNullPointer = "HV009" - FDWTooManyHandles = "HV014" - FDWOutOfMemory = "HV001" - FDWNoSchemas = "HV00P" - FDWOptionNameNotFound = "HV00J" - FDWReplyHandle = "HV00K" - FDWSchemaNotFound = "HV00Q" - FDWTableNotFound = "HV00R" - FDWUnableToCreateExecution = "HV00L" - FDWUnableToCreateReply = "HV00M" - FDWUnableToEstablishConnection = "HV00N" - - // Class P0 — PL/pgSQL Error - PLpgSQLError = "P0000" - RaiseException = "P0001" - NoDataFound = "P0002" - TooManyRows = "P0003" - AssertFailure = "P0004" - - // Class XX — Internal Error - InternalError = "XX000" - DataCorrupted = "XX001" - IndexCorrupted = "XX002" -) - -// IsSuccessfulCompletion asserts the error code class is Class 00 — Successful Completion -func IsSuccessfulCompletion(code string) bool { - switch code { - case SuccessfulCompletion: - return true - } - return false -} - -// IsWarning asserts the error code class is Class 01 — Warning -func IsWarning(code string) bool { - switch code { - case Warning, DynamicResultSetsReturned, ImplicitZeroBitPadding, NullValueEliminatedInSetFunction, PrivilegeNotGranted, PrivilegeNotRevoked, StringDataRightTruncationWarning, DeprecatedFeature: - return true - } - return false -} - -// IsNoData asserts the error code class is Class 02 — No Data (this is also a warning class per the SQL standard) -func IsNoData(code string) bool { - switch code { - case NoData, NoAdditionalDynamicResultSetsReturned: - return true - } - return false -} - -// IsSQLStatementNotYetComplete asserts the error code class is Class 03 — SQL Statement Not Yet Complete -func IsSQLStatementNotYetComplete(code string) bool { - switch code { - case SQLStatementNotYetComplete: - return true - } - return false -} - -// IsConnectionException asserts the error code class is Class 08 — Connection Exception -func IsConnectionException(code string) bool { - switch code { - case ConnectionException, ConnectionDoesNotExist, ConnectionFailure, SQLClientUnableToEstablishSQLConnection, SQLServerRejectedEstablishmentOfSQLConnection, TransactionResolutionUnknown, ProtocolViolation: - return true - } - return false -} - -// IsTriggeredActionException asserts the error code class is Class 09 — Triggered Action Exception -func IsTriggeredActionException(code string) bool { - switch code { - case TriggeredActionException: - return true - } - return false -} - -// IsFeatureNotSupported asserts the error code class is Class 0A — Feature Not Supported -func IsFeatureNotSupported(code string) bool { - switch code { - case FeatureNotSupported: - return true - } - return false -} - -// IsInvalidTransactionInitiation asserts the error code class is Class 0B — Invalid Transaction Initiation -func IsInvalidTransactionInitiation(code string) bool { - switch code { - case InvalidTransactionInitiation: - return true - } - return false -} - -// IsLocatorException asserts the error code class is Class 0F — Locator Exception -func IsLocatorException(code string) bool { - switch code { - case LocatorException, InvalidLocatorSpecification: - return true - } - return false -} - -// IsInvalidGrantor asserts the error code class is Class 0L — Invalid Grantor -func IsInvalidGrantor(code string) bool { - switch code { - case InvalidGrantor, InvalidGrantOperation: - return true - } - return false -} - -// IsInvalidRoleSpecification asserts the error code class is Class 0P — Invalid Role Specification -func IsInvalidRoleSpecification(code string) bool { - switch code { - case InvalidRoleSpecification: - return true - } - return false -} - -// IsDiagnosticsException asserts the error code class is Class 0Z — Diagnostics Exception -func IsDiagnosticsException(code string) bool { - switch code { - case DiagnosticsException, StackedDiagnosticsAccessedWithoutActiveHandler: - return true - } - return false -} - -// IsCaseNotFound asserts the error code class is Class 20 — Case Not Found -func IsCaseNotFound(code string) bool { - switch code { - case CaseNotFound: - return true - } - return false -} - -// IsCardinalityViolation asserts the error code class is Class 21 — Cardinality Violation -func IsCardinalityViolation(code string) bool { - switch code { - case CardinalityViolation: - return true - } - return false -} - -// IsDataException asserts the error code class is Class 22 — Data Exception -func IsDataException(code string) bool { - switch code { - case DataException, ArraySubscriptError, CharacterNotInRepertoire, DatetimeFieldOverflow, DivisionByZero, ErrorInAssignment, EscapeCharacterConflict, IndicatorOverflow, IntervalFieldOverflow, InvalidArgumentForLogarithm, InvalidArgumentForNtileFunction, InvalidArgumentForNthValueFunction, InvalidArgumentForPowerFunction, InvalidArgumentForWidthBucketFunction, InvalidCharacterValueForCast, InvalidDatetimeFormat, InvalidEscapeCharacter, InvalidEscapeOctet, InvalidEscapeSequence, NonstandardUseOfEscapeCharacter, InvalidIndicatorParameterValue, InvalidParameterValue, InvalidPrecedingOrFollowingSize, InvalidRegularExpression, InvalidRowCountInLimitClause, InvalidRowCountInResultOffsetClause, InvalidTablesampleArgument, InvalidTablesampleRepeat, InvalidTimeZoneDisplacementValue, InvalidUseOfEscapeCharacter, MostSpecificTypeMismatch, NullValueNotAllowedDataException, NullValueNoIndicatorParameter, NumericValueOutOfRange, SequenceGeneratorLimitExceeded, StringDataLengthMismatch, StringDataRightTruncationDataException, SubstringError, TrimError, UnterminatedCString, ZeroLengthCharacterString, FloatingPointException, InvalidTextRepresentation, InvalidBinaryRepresentation, BadCopyFileFormat, UntranslatableCharacter, NotAnXMLDocument, InvalidXMLDocument, InvalidXMLContent, InvalidXMLComment, InvalidXMLProcessingInstruction, DuplicateJSONObjectKeyValue, InvalidArgumentForSQLJSONDatetimeFunction, InvalidJSONText, InvalidSQLJSONSubscript, MoreThanOneSQLJSONItem, NoSQLJSONItem, NonNumericSQLJSONItem, NonUniqueKeysInAJSONObject, SingletonSQLJSONItemRequired, SQLJSONArrayNotFound, SQLJSONMemberNotFound, SQLJSONNumberNotFound, SQLJSONObjectNotFound, TooManyJSONArrayElements, TooManyJSONObjectMembers, SQLJSONScalarRequired, SQLJSONItemCannotBeCastToTargetType: - return true - } - return false -} - -// IsIntegrityConstraintViolation asserts the error code class is Class 23 — Integrity Constraint Violation -func IsIntegrityConstraintViolation(code string) bool { - switch code { - case IntegrityConstraintViolation, RestrictViolation, NotNullViolation, ForeignKeyViolation, UniqueViolation, CheckViolation, ExclusionViolation: - return true - } - return false -} - -// IsInvalidCursorState asserts the error code class is Class 24 — Invalid Cursor State -func IsInvalidCursorState(code string) bool { - switch code { - case InvalidCursorState: - return true - } - return false -} - -// IsInvalidTransactionState asserts the error code class is Class 25 — Invalid Transaction State -func IsInvalidTransactionState(code string) bool { - switch code { - case InvalidTransactionState, ActiveSQLTransaction, BranchTransactionAlreadyActive, HeldCursorRequiresSameIsolationLevel, InappropriateAccessModeForBranchTransaction, InappropriateIsolationLevelForBranchTransaction, NoActiveSQLTransactionForBranchTransaction, ReadOnlySQLTransaction, SchemaAndDataStatementMixingNotSupported, NoActiveSQLTransaction, InFailedSQLTransaction, IdleInTransactionSessionTimeout: - return true - } - return false -} - -// IsInvalidSQLStatementName asserts the error code class is Class 26 — Invalid SQL Statement Name -func IsInvalidSQLStatementName(code string) bool { - switch code { - case InvalidSQLStatementName: - return true - } - return false -} - -// IsTriggeredDataChangeViolation asserts the error code class is Class 27 — Triggered Data Change Violation -func IsTriggeredDataChangeViolation(code string) bool { - switch code { - case TriggeredDataChangeViolation: - return true - } - return false -} - -// IsInvalidAuthorizationSpecification asserts the error code class is Class 28 — Invalid Authorization Specification -func IsInvalidAuthorizationSpecification(code string) bool { - switch code { - case InvalidAuthorizationSpecification, InvalidPassword: - return true - } - return false -} - -// IsDependentPrivilegeDescriptorsStillExist asserts the error code class is Class 2B — Dependent Privilege Descriptors Still Exist -func IsDependentPrivilegeDescriptorsStillExist(code string) bool { - switch code { - case DependentPrivilegeDescriptorsStillExist, DependentObjectsStillExist: - return true - } - return false -} - -// IsInvalidTransactionTermination asserts the error code class is Class 2D — Invalid Transaction Termination -func IsInvalidTransactionTermination(code string) bool { - switch code { - case InvalidTransactionTermination: - return true - } - return false -} - -// IsSQLRoutineException asserts the error code class is Class 2F — SQL Routine Exception -func IsSQLRoutineException(code string) bool { - switch code { - case SQLRoutineException, FunctionExecutedNoReturnStatement, ModifyingSQLDataNotPermittedSQLRoutineException, ProhibitedSQLStatementAttemptedSQLRoutineException, ReadingSQLDataNotPermittedSQLRoutineException: - return true - } - return false -} - -// IsInvalidCursorName asserts the error code class is Class 34 — Invalid Cursor Name -func IsInvalidCursorName(code string) bool { - switch code { - case InvalidCursorName: - return true - } - return false -} - -// IsExternalRoutineException asserts the error code class is Class 38 — External Routine Exception -func IsExternalRoutineException(code string) bool { - switch code { - case ExternalRoutineException, ContainingSQLNotPermitted, ModifyingSQLDataNotPermittedExternalRoutineException, ProhibitedSQLStatementAttemptedExternalRoutineException, ReadingSQLDataNotPermittedExternalRoutineException: - return true - } - return false -} - -// IsExternalRoutineInvocationException asserts the error code class is Class 39 — External Routine Invocation Exception -func IsExternalRoutineInvocationException(code string) bool { - switch code { - case ExternalRoutineInvocationException, InvalidSQLstateReturned, NullValueNotAllowedExternalRoutineInvocationException, TriggerProtocolViolated, SRFProtocolViolated, EventTriggerProtocolViolated: - return true - } - return false -} - -// IsSavepointException asserts the error code class is Class 3B — Savepoint Exception -func IsSavepointException(code string) bool { - switch code { - case SavepointException, InvalidSavepointSpecification: - return true - } - return false -} - -// IsInvalidCatalogName asserts the error code class is Class 3D — Invalid Catalog Name -func IsInvalidCatalogName(code string) bool { - switch code { - case InvalidCatalogName: - return true - } - return false -} - -// IsInvalidSchemaName asserts the error code class is Class 3F — Invalid Schema Name -func IsInvalidSchemaName(code string) bool { - switch code { - case InvalidSchemaName: - return true - } - return false -} - -// IsTransactionRollback asserts the error code class is Class 40 — Transaction Rollback -func IsTransactionRollback(code string) bool { - switch code { - case TransactionRollback, TransactionIntegrityConstraintViolation, SerializationFailure, StatementCompletionUnknown, DeadlockDetected: - return true - } - return false -} - -// IsSyntaxErrororAccessRuleViolation asserts the error code class is Class 42 — Syntax Error or Access Rule Violation -func IsSyntaxErrororAccessRuleViolation(code string) bool { - switch code { - case SyntaxErrorOrAccessRuleViolation, SyntaxError, InsufficientPrivilege, CannotCoerce, GroupingError, WindowingError, InvalidRecursion, InvalidForeignKey, InvalidName, NameTooLong, ReservedName, DatatypeMismatch, IndeterminateDatatype, CollationMismatch, IndeterminateCollation, WrongObjectType, GeneratedAlways, UndefinedColumn, UndefinedFunction, UndefinedTable, UndefinedParameter, UndefinedObject, DuplicateColumn, DuplicateCursor, DuplicateDatabase, DuplicateFunction, DuplicatePreparedStatement, DuplicateSchema, DuplicateTable, DuplicateAlias, DuplicateObject, AmbiguousColumn, AmbiguousFunction, AmbiguousParameter, AmbiguousAlias, InvalidColumnReference, InvalidColumnDefinition, InvalidCursorDefinition, InvalidDatabaseDefinition, InvalidFunctionDefinition, InvalidPreparedStatementDefinition, InvalidSchemaDefinition, InvalidTableDefinition, InvalidObjectDefinition: - return true - } - return false -} - -// IsWithCheckOptionViolation asserts the error code class is Class 44 — WITH CHECK OPTION Violation -func IsWithCheckOptionViolation(code string) bool { - switch code { - case WithCheckOptionViolation: - return true - } - return false -} - -// IsInsufficientResources asserts the error code class is Class 53 — Insufficient Resources -func IsInsufficientResources(code string) bool { - switch code { - case InsufficientResources, DiskFull, OutOfMemory, TooManyConnections, ConfigurationLimitExceeded: - return true - } - return false -} - -// IsProgramLimitExceeded asserts the error code class is Class 54 — Program Limit Exceeded -func IsProgramLimitExceeded(code string) bool { - switch code { - case ProgramLimitExceeded, StatementTooComplex, TooManyColumns, TooManyArguments: - return true - } - return false -} - -// IsObjectNotInPrerequisiteState asserts the error code class is Class 55 — Object Not In Prerequisite State -func IsObjectNotInPrerequisiteState(code string) bool { - switch code { - case ObjectNotInPrerequisiteState, ObjectInUse, CantChangeRuntimeParam, LockNotAvailable, UnsafeNewEnumValueUsage: - return true - } - return false -} - -// IsOperatorIntervention asserts the error code class is Class 57 — Operator Intervention -func IsOperatorIntervention(code string) bool { - switch code { - case OperatorIntervention, QueryCanceled, AdminShutdown, CrashShutdown, CannotConnectNow, DatabaseDropped, IdleSessionTimeout: - return true - } - return false -} - -// IsSystemError asserts the error code class is Class 58 — System Error (errors external to PostgreSQL itself) -func IsSystemError(code string) bool { - switch code { - case SystemError, IOError, UndefinedFile, DuplicateFile: - return true - } - return false -} - -// IsSnapshotFailure asserts the error code class is Class 72 — Snapshot Failure -func IsSnapshotFailure(code string) bool { - switch code { - case SnapshotTooOld: - return true - } - return false -} - -// IsConfigurationFileError asserts the error code class is Class F0 — Configuration File Error -func IsConfigurationFileError(code string) bool { - switch code { - case ConfigFileError, LockFileExists: - return true - } - return false -} - -// IsForeignDataWrapperError asserts the error code class is Class HV — Foreign Data Wrapper Error (SQL/MED) -func IsForeignDataWrapperError(code string) bool { - switch code { - case FDWError, FDWColumnNameNotFound, FDWDynamicParameterValueNeeded, FDWFunctionSequenceError, FDWInconsistentDescriptorInformation, FDWInvalidAttributeValue, FDWInvalidColumnName, FDWInvalidColumnNumber, FDWInvalidDataType, FDWInvalidDataTypeDescriptors, FDWInvalidDescriptorFieldIdentifier, FDWInvalidHandle, FDWInvalidOptionIndex, FDWInvalidOptionName, FDWInvalidStringLengthOrBufferLength, FDWInvalidStringFormat, FDWInvalidUseOfNullPointer, FDWTooManyHandles, FDWOutOfMemory, FDWNoSchemas, FDWOptionNameNotFound, FDWReplyHandle, FDWSchemaNotFound, FDWTableNotFound, FDWUnableToCreateExecution, FDWUnableToCreateReply, FDWUnableToEstablishConnection: - return true - } - return false -} - -// IsPLpgSQLError asserts the error code class is Class P0 — PL/pgSQL Error -func IsPLpgSQLError(code string) bool { - switch code { - case PLpgSQLError, RaiseException, NoDataFound, TooManyRows, AssertFailure: - return true - } - return false -} - -// IsInternalError asserts the error code class is Class XX — Internal Error -func IsInternalError(code string) bool { - switch code { - case InternalError, DataCorrupted, IndexCorrupted: - return true - } - return false -} diff --git a/vendor/github.com/jackc/pgerrcode/gen.rb b/vendor/github.com/jackc/pgerrcode/gen.rb deleted file mode 100644 index eccce6a1f..000000000 --- a/vendor/github.com/jackc/pgerrcode/gen.rb +++ /dev/null @@ -1,108 +0,0 @@ -# Run this script against the data in table A.1. on https://www.postgresql.org/docs/16/errcodes-appendix.html. -# -# Source data should be formatted like the following: -# -# Class 00 — Successful Completion -# 00000 successful_completion -# Class 01 — Warning -# 01000 warning -# 0100C dynamic_result_sets_returned -# -# for best results pass through gofmt -# ruby gen.rb < tablecontents.txt | gofmt > errcode.go - -code_name_overrides = { - # Some error code names are repeated. In those cases add the error class as a suffix. - "01004" => "StringDataRightTruncationWarning", - "22001" => "StringDataRightTruncationDataException", - "22004" => "NullValueNotAllowedDataException", - "2F002" => "ModifyingSQLDataNotPermittedSQLRoutineException", - "2F003" => "ProhibitedSQLStatementAttemptedSQLRoutineException", - "2F004" => "ReadingSQLDataNotPermittedSQLRoutineException", - "38002" => "ModifyingSQLDataNotPermittedExternalRoutineException", - "38003" => "ProhibitedSQLStatementAttemptedExternalRoutineException", - "38004" => "ReadingSQLDataNotPermittedExternalRoutineException", - "39004" => "NullValueNotAllowedExternalRoutineInvocationException", - - # Go casing corrections - "08001" => "SQLClientUnableToEstablishSQLConnection", - "08004" => "SQLServerRejectedEstablishmentOfSQLConnection", - "P0000" => "PLpgSQLError" -} - -class_name_overrides = { - # Go casing corrections - "WITHCHECKOPTIONViolation" => "WithCheckOptionViolation" -} - -cls_errs = Array.new -cls_assertions = Array.new -last_cls = "" -last_cls_full = "" - -def build_assert_func(last_cls, last_cls_full, cls_errs) - <<~GO - // Is#{last_cls} asserts the error code class is #{last_cls_full} - func Is#{last_cls} (code string) bool { - switch code{ - case #{cls_errs.join(", ")}: - return true - } - return false - } - GO -end - -puts <<~STR -// Package pgerrcode contains constants for PostgreSQL error codes. -package pgerrcode - -// Source: https://www.postgresql.org/docs/16/errcodes-appendix.html -// See gen.rb for script that can convert the error code table to Go code. - -const ( -STR - -ARGF.each do |line| - case line - when /^Class/ - if cls_errs.length > 0 && last_cls != "" - assert_func = build_assert_func(class_name_overrides.fetch(last_cls) { last_cls }, last_cls_full, cls_errs) - cls_assertions.push(assert_func) - end - last_cls = line.split("—")[1] - .gsub(" ", "") - .gsub("/", "") - .gsub("\n", "") - .sub(/\(\w*\)/, "") - last_cls_full = line.gsub("\n", "") - cls_errs.clear - puts - puts "// #{line}" - when /^(\w{5})\s+(\w+)/ - code = $1 - name = code_name_overrides.fetch(code) do - $2.split("_").map(&:capitalize).join - .gsub("Sql", "SQL") - .gsub("Xml", "XML") - .gsub("Fdw", "FDW") - .gsub("Srf", "SRF") - .gsub("Io", "IO") - .gsub("Json", "JSON") - end - cls_errs.push(name) - puts %Q[#{name} = "#{code}"] - else - puts line - end -end -puts ")" - -if cls_errs.length > 0 - assert_func = build_assert_func(class_name_overrides.fetch(last_cls) { last_cls }, last_cls_full, cls_errs) - cls_assertions.push(assert_func) -end - -cls_assertions.each do |cls_assertion| - puts cls_assertion -end diff --git a/vendor/github.com/jackc/pgpassfile/.travis.yml b/vendor/github.com/jackc/pgpassfile/.travis.yml deleted file mode 100644 index e176228e8..000000000 --- a/vendor/github.com/jackc/pgpassfile/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -go: - - 1.x - - tip - -matrix: - allow_failures: - - go: tip diff --git a/vendor/github.com/jackc/pgpassfile/LICENSE b/vendor/github.com/jackc/pgpassfile/LICENSE deleted file mode 100644 index c1c4f50fc..000000000 --- a/vendor/github.com/jackc/pgpassfile/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2019 Jack Christensen - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/pgpassfile/README.md b/vendor/github.com/jackc/pgpassfile/README.md deleted file mode 100644 index 661289ed8..000000000 --- a/vendor/github.com/jackc/pgpassfile/README.md +++ /dev/null @@ -1,8 +0,0 @@ -[![](https://godoc.org/github.com/jackc/pgpassfile?status.svg)](https://godoc.org/github.com/jackc/pgpassfile) -[![Build Status](https://travis-ci.org/jackc/pgpassfile.svg)](https://travis-ci.org/jackc/pgpassfile) - -# pgpassfile - -Package pgpassfile is a parser PostgreSQL .pgpass files. - -Extracted and rewritten from original implementation in https://github.com/jackc/pgx. diff --git a/vendor/github.com/jackc/pgpassfile/pgpass.go b/vendor/github.com/jackc/pgpassfile/pgpass.go deleted file mode 100644 index f7eed3c84..000000000 --- a/vendor/github.com/jackc/pgpassfile/pgpass.go +++ /dev/null @@ -1,110 +0,0 @@ -// Package pgpassfile is a parser PostgreSQL .pgpass files. -package pgpassfile - -import ( - "bufio" - "io" - "os" - "regexp" - "strings" -) - -// Entry represents a line in a PG passfile. -type Entry struct { - Hostname string - Port string - Database string - Username string - Password string -} - -// Passfile is the in memory data structure representing a PG passfile. -type Passfile struct { - Entries []*Entry -} - -// ReadPassfile reads the file at path and parses it into a Passfile. -func ReadPassfile(path string) (*Passfile, error) { - f, err := os.Open(path) - if err != nil { - return nil, err - } - defer f.Close() - - return ParsePassfile(f) -} - -// ParsePassfile reads r and parses it into a Passfile. -func ParsePassfile(r io.Reader) (*Passfile, error) { - passfile := &Passfile{} - - scanner := bufio.NewScanner(r) - for scanner.Scan() { - entry := parseLine(scanner.Text()) - if entry != nil { - passfile.Entries = append(passfile.Entries, entry) - } - } - - return passfile, scanner.Err() -} - -// Match (not colons or escaped colon or escaped backslash)+. Essentially gives a split on unescaped -// colon. -var colonSplitterRegexp = regexp.MustCompile("(([^:]|(\\:)))+") - -// var colonSplitterRegexp = regexp.MustCompile("((?:[^:]|(?:\\:)|(?:\\\\))+)") - -// parseLine parses a line into an *Entry. It returns nil on comment lines or any other unparsable -// line. -func parseLine(line string) *Entry { - const ( - tmpBackslash = "\r" - tmpColon = "\n" - ) - - line = strings.TrimSpace(line) - - if strings.HasPrefix(line, "#") { - return nil - } - - line = strings.Replace(line, `\\`, tmpBackslash, -1) - line = strings.Replace(line, `\:`, tmpColon, -1) - - parts := strings.Split(line, ":") - if len(parts) != 5 { - return nil - } - - // Unescape escaped colons and backslashes - for i := range parts { - parts[i] = strings.Replace(parts[i], tmpBackslash, `\`, -1) - parts[i] = strings.Replace(parts[i], tmpColon, `:`, -1) - } - - return &Entry{ - Hostname: parts[0], - Port: parts[1], - Database: parts[2], - Username: parts[3], - Password: parts[4], - } -} - -// FindPassword finds the password for the provided hostname, port, database, and username. For a -// Unix domain socket hostname must be set to "localhost". An empty string will be returned if no -// match is found. -// -// See https://www.postgresql.org/docs/current/libpq-pgpass.html for more password file information. -func (pf *Passfile) FindPassword(hostname, port, database, username string) (password string) { - for _, e := range pf.Entries { - if (e.Hostname == "*" || e.Hostname == hostname) && - (e.Port == "*" || e.Port == port) && - (e.Database == "*" || e.Database == database) && - (e.Username == "*" || e.Username == username) { - return e.Password - } - } - return "" -} diff --git a/vendor/github.com/jackc/pgservicefile/LICENSE b/vendor/github.com/jackc/pgservicefile/LICENSE deleted file mode 100644 index f1b4c2892..000000000 --- a/vendor/github.com/jackc/pgservicefile/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2020 Jack Christensen - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/pgservicefile/README.md b/vendor/github.com/jackc/pgservicefile/README.md deleted file mode 100644 index 2fc7e012c..000000000 --- a/vendor/github.com/jackc/pgservicefile/README.md +++ /dev/null @@ -1,7 +0,0 @@ -[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/pgservicefile.svg)](https://pkg.go.dev/github.com/jackc/pgservicefile) -[![Build Status](https://github.com/jackc/pgservicefile/actions/workflows/ci.yml/badge.svg)](https://github.com/jackc/pgservicefile/actions/workflows/ci.yml) - - -# pgservicefile - -Package pgservicefile is a parser for PostgreSQL service files (e.g. `.pg_service.conf`). diff --git a/vendor/github.com/jackc/pgservicefile/pgservicefile.go b/vendor/github.com/jackc/pgservicefile/pgservicefile.go deleted file mode 100644 index c62caa7fe..000000000 --- a/vendor/github.com/jackc/pgservicefile/pgservicefile.go +++ /dev/null @@ -1,81 +0,0 @@ -// Package pgservicefile is a parser for PostgreSQL service files (e.g. .pg_service.conf). -package pgservicefile - -import ( - "bufio" - "errors" - "fmt" - "io" - "os" - "strings" -) - -type Service struct { - Name string - Settings map[string]string -} - -type Servicefile struct { - Services []*Service - servicesByName map[string]*Service -} - -// GetService returns the named service. -func (sf *Servicefile) GetService(name string) (*Service, error) { - service, present := sf.servicesByName[name] - if !present { - return nil, errors.New("not found") - } - return service, nil -} - -// ReadServicefile reads the file at path and parses it into a Servicefile. -func ReadServicefile(path string) (*Servicefile, error) { - f, err := os.Open(path) - if err != nil { - return nil, err - } - defer f.Close() - - return ParseServicefile(f) -} - -// ParseServicefile reads r and parses it into a Servicefile. -func ParseServicefile(r io.Reader) (*Servicefile, error) { - servicefile := &Servicefile{} - - var service *Service - scanner := bufio.NewScanner(r) - lineNum := 0 - for scanner.Scan() { - lineNum += 1 - line := scanner.Text() - line = strings.TrimSpace(line) - - if line == "" || strings.HasPrefix(line, "#") { - // ignore comments and empty lines - } else if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { - service = &Service{Name: line[1 : len(line)-1], Settings: make(map[string]string)} - servicefile.Services = append(servicefile.Services, service) - } else if service != nil { - parts := strings.SplitN(line, "=", 2) - if len(parts) != 2 { - return nil, fmt.Errorf("unable to parse line %d", lineNum) - } - - key := strings.TrimSpace(parts[0]) - value := strings.TrimSpace(parts[1]) - - service.Settings[key] = value - } else { - return nil, fmt.Errorf("line %d is not in a section", lineNum) - } - } - - servicefile.servicesByName = make(map[string]*Service, len(servicefile.Services)) - for _, service := range servicefile.Services { - servicefile.servicesByName[service.Name] = service - } - - return servicefile, scanner.Err() -} diff --git a/vendor/github.com/jackc/pgx/v5/.gitignore b/vendor/github.com/jackc/pgx/v5/.gitignore deleted file mode 100644 index a2ebbe9c6..000000000 --- a/vendor/github.com/jackc/pgx/v5/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -# 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 - -.envrc -/.testdb - -.DS_Store diff --git a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md deleted file mode 100644 index 6470088b2..000000000 --- a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md +++ /dev/null @@ -1,434 +0,0 @@ -# 5.7.2 (December 21, 2024) - -* Fix prepared statement already exists on batch prepare failure -* Add commit query to tx options (Lucas Hild) -* Fix pgtype.Timestamp json unmarshal (Shean de Montigny-Desautels) -* Add message body size limits in frontend and backend (zene) -* Add xid8 type -* Ensure planning encodes and scans cannot infinitely recurse -* Implement pgtype.UUID.String() (Konstantin Grachev) -* Switch from ExecParams to Exec in ValidateConnectTargetSessionAttrs functions (Alexander Rumyantsev) -* Update golang.org/x/crypto - -# 5.7.1 (September 10, 2024) - -* Fix data race in tracelog.TraceLog -* Update puddle to v2.2.2. This removes the import of nanotime via linkname. -* Update golang.org/x/crypto and golang.org/x/text - -# 5.7.0 (September 7, 2024) - -* Add support for sslrootcert=system (Yann Soubeyrand) -* Add LoadTypes to load multiple types in a single SQL query (Nick Farrell) -* Add XMLCodec supports encoding + scanning XML column type like json (nickcruess-soda) -* Add MultiTrace (Stepan Rabotkin) -* Add TraceLogConfig with customizable TimeKey (stringintech) -* pgx.ErrNoRows wraps sql.ErrNoRows to aid in database/sql compatibility with native pgx functions (merlin) -* Support scanning binary formatted uint32 into string / TextScanner (jennifersp) -* Fix interval encoding to allow 0s and avoid extra spaces (Carlos Pérez-Aradros Herce) -* Update pgservicefile - fixes panic when parsing invalid file -* Better error message when reading past end of batch -* Don't print url when url.Parse returns an error (Kevin Biju) -* Fix snake case name normalization collision in RowToStructByName with db tag (nolandseigler) -* Fix: Scan and encode types with underlying types of arrays - -# 5.6.0 (May 25, 2024) - -* Add StrictNamedArgs (Tomas Zahradnicek) -* Add support for macaddr8 type (Carlos Pérez-Aradros Herce) -* Add SeverityUnlocalized field to PgError / Notice -* Performance optimization of RowToStructByPos/Name (Zach Olstein) -* Allow customizing context canceled behavior for pgconn -* Add ScanLocation to pgtype.Timestamp[tz]Codec -* Add custom data to pgconn.PgConn -* Fix ResultReader.Read() to handle nil values -* Do not encode interval microseconds when they are 0 (Carlos Pérez-Aradros Herce) -* pgconn.SafeToRetry checks for wrapped errors (tjasko) -* Failed connection attempts include all errors -* Optimize LargeObject.Read (Mitar) -* Add tracing for connection acquire and release from pool (ngavinsir) -* Fix encode driver.Valuer not called when nil -* Add support for custom JSON marshal and unmarshal (Mitar) -* Use Go default keepalive for TCP connections (Hans-Joachim Kliemeck) - -# 5.5.5 (March 9, 2024) - -Use spaces instead of parentheses for SQL sanitization. - -This still solves the problem of negative numbers creating a line comment, but this avoids breaking edge cases such as -`set foo to $1` where the substitution is taking place in a location where an arbitrary expression is not allowed. - -# 5.5.4 (March 4, 2024) - -Fix CVE-2024-27304 - -SQL injection can occur if an attacker can cause a single query or bind message to exceed 4 GB in size. An integer -overflow in the calculated message size can cause the one large message to be sent as multiple messages under the -attacker's control. - -Thanks to Paul Gerste for reporting this issue. - -* Fix behavior of CollectRows to return empty slice if Rows are empty (Felix) -* Fix simple protocol encoding of json.RawMessage -* Fix *Pipeline.getResults should close pipeline on error -* Fix panic in TryFindUnderlyingTypeScanPlan (David Kurman) -* Fix deallocation of invalidated cached statements in a transaction -* Handle invalid sslkey file -* Fix scan float4 into sql.Scanner -* Fix pgtype.Bits not making copy of data from read buffer. This would cause the data to be corrupted by future reads. - -# 5.5.3 (February 3, 2024) - -* Fix: prepared statement already exists -* Improve CopyFrom auto-conversion of text-ish values -* Add ltree type support (Florent Viel) -* Make some properties of Batch and QueuedQuery public (Pavlo Golub) -* Add AppendRows function (Edoardo Spadolini) -* Optimize convert UUID [16]byte to string (Kirill Malikov) -* Fix: LargeObject Read and Write of more than ~1GB at a time (Mitar) - -# 5.5.2 (January 13, 2024) - -* Allow NamedArgs to start with underscore -* pgproto3: Maximum message body length support (jeremy.spriet) -* Upgrade golang.org/x/crypto to v0.17.0 -* Add snake_case support to RowToStructByName (Tikhon Fedulov) -* Fix: update description cache after exec prepare (James Hartig) -* Fix: pipeline checks if it is closed (James Hartig and Ryan Fowler) -* Fix: normalize timeout / context errors during TLS startup (Samuel Stauffer) -* Add OnPgError for easier centralized error handling (James Hartig) - -# 5.5.1 (December 9, 2023) - -* Add CopyFromFunc helper function. (robford) -* Add PgConn.Deallocate method that uses PostgreSQL protocol Close message. -* pgx uses new PgConn.Deallocate method. This allows deallocating statements to work in a failed transaction. This fixes a case where the prepared statement map could become invalid. -* Fix: Prefer driver.Valuer over json.Marshaler for json fields. (Jacopo) -* Fix: simple protocol SQL sanitizer previously panicked if an invalid $0 placeholder was used. This now returns an error instead. (maksymnevajdev) -* Add pgtype.Numeric.ScanScientific (Eshton Robateau) - -# 5.5.0 (November 4, 2023) - -* Add CollectExactlyOneRow. (Julien GOTTELAND) -* Add OpenDBFromPool to create *database/sql.DB from *pgxpool.Pool. (Lev Zakharov) -* Prepare can automatically choose statement name based on sql. This makes it easier to explicitly manage prepared statements. -* Statement cache now uses deterministic, stable statement names. -* database/sql prepared statement names are deterministically generated. -* Fix: SendBatch wasn't respecting context cancellation. -* Fix: Timeout error from pipeline is now normalized. -* Fix: database/sql encoding json.RawMessage to []byte. -* CancelRequest: Wait for the cancel request to be acknowledged by the server. This should improve PgBouncer compatibility. (Anton Levakin) -* stdlib: Use Ping instead of CheckConn in ResetSession -* Add json.Marshaler and json.Unmarshaler for Float4, Float8 (Kirill Mironov) - -# 5.4.3 (August 5, 2023) - -* Fix: QCharArrayOID was defined with the wrong OID (Christoph Engelbert) -* Fix: connect_timeout for sslmode=allow|prefer (smaher-edb) -* Fix: pgxpool: background health check cannot overflow pool -* Fix: Check for nil in defer when sending batch (recover properly from panic) -* Fix: json scan of non-string pointer to pointer -* Fix: zeronull.Timestamptz should use pgtype.Timestamptz -* Fix: NewConnsCount was not correctly counting connections created by Acquire directly. (James Hartig) -* RowTo(AddrOf)StructByPos ignores fields with "-" db tag -* Optimization: improve text format numeric parsing (horpto) - -# 5.4.2 (July 11, 2023) - -* Fix: RowScanner errors are fatal to Rows -* Fix: Enable failover efforts when pg_hba.conf disallows non-ssl connections (Brandon Kauffman) -* Hstore text codec internal improvements (Evan Jones) -* Fix: Stop timers for background reader when not in use. Fixes memory leak when closing connections (Adrian-Stefan Mares) -* Fix: Stop background reader as soon as possible. -* Add PgConn.SyncConn(). This combined with the above fix makes it safe to directly use the underlying net.Conn. - -# 5.4.1 (June 18, 2023) - -* Fix: concurrency bug with pgtypeDefaultMap and simple protocol (Lev Zakharov) -* Add TxOptions.BeginQuery to allow overriding the default BEGIN query - -# 5.4.0 (June 14, 2023) - -* Replace platform specific syscalls for non-blocking IO with more traditional goroutines and deadlines. This returns to the v4 approach with some additional improvements and fixes. This restores the ability to use a pgx.Conn over an ssh.Conn as well as other non-TCP or Unix socket connections. In addition, it is a significantly simpler implementation that is less likely to have cross platform issues. -* Optimization: The default type registrations are now shared among all connections. This saves about 100KB of memory per connection. `pgtype.Type` and `pgtype.Codec` values are now required to be immutable after registration. This was already necessary in most cases but wasn't documented until now. (Lev Zakharov) -* Fix: Ensure pgxpool.Pool.QueryRow.Scan releases connection on panic -* CancelRequest: don't try to read the reply (Nicola Murino) -* Fix: correctly handle bool type aliases (Wichert Akkerman) -* Fix: pgconn.CancelRequest: Fix unix sockets: don't use RemoteAddr() -* Fix: pgx.Conn memory leak with prepared statement caching (Evan Jones) -* Add BeforeClose to pgxpool.Pool (Evan Cordell) -* Fix: various hstore fixes and optimizations (Evan Jones) -* Fix: RowToStructByPos with embedded unexported struct -* Support different bool string representations (Lev Zakharov) -* Fix: error when using BatchResults.Exec on a select that returns an error after some rows. -* Fix: pipelineBatchResults.Exec() not returning error from ResultReader -* Fix: pipeline batch results not closing pipeline when error occurs while reading directly from results instead of using - a callback. -* Fix: scanning a table type into a struct -* Fix: scan array of record to pointer to slice of struct -* Fix: handle null for json (Cemre Mengu) -* Batch Query callback is called even when there is an error -* Add RowTo(AddrOf)StructByNameLax (Audi P. Risa P) - -# 5.3.1 (February 27, 2023) - -* Fix: Support v4 and v5 stdlib in same program (Tomáš Procházka) -* Fix: sql.Scanner not being used in certain cases -* Add text format jsonpath support -* Fix: fake non-blocking read adaptive wait time - -# 5.3.0 (February 11, 2023) - -* Fix: json values work with sql.Scanner -* Fixed / improved error messages (Mark Chambers and Yevgeny Pats) -* Fix: support scan into single dimensional arrays -* Fix: MaxConnLifetimeJitter setting actually jitter (Ben Weintraub) -* Fix: driver.Value representation of bytea should be []byte not string -* Fix: better handling of unregistered OIDs -* CopyFrom can use query cache to avoid extra round trip to get OIDs (Alejandro Do Nascimento Mora) -* Fix: encode to json ignoring driver.Valuer -* Support sql.Scanner on renamed base type -* Fix: pgtype.Numeric text encoding of negative numbers (Mark Chambers) -* Fix: connect with multiple hostnames when one can't be resolved -* Upgrade puddle to remove dependency on uber/atomic and fix alignment issue on 32-bit platform -* Fix: scanning json column into **string -* Multiple reductions in memory allocations -* Fake non-blocking read adapts its max wait time -* Improve CopyFrom performance and reduce memory usage -* Fix: encode []any to array -* Fix: LoadType for composite with dropped attributes (Felix Röhrich) -* Support v4 and v5 stdlib in same program -* Fix: text format array decoding with string of "NULL" -* Prefer binary format for arrays - -# 5.2.0 (December 5, 2022) - -* `tracelog.TraceLog` implements the pgx.PrepareTracer interface. (Vitalii Solodilov) -* Optimize creating begin transaction SQL string (Petr Evdokimov and ksco) -* `Conn.LoadType` supports range and multirange types (Vitalii Solodilov) -* Fix scan `uint` and `uint64` `ScanNumeric`. This resolves a PostgreSQL `numeric` being incorrectly scanned into `uint` and `uint64`. - -# 5.1.1 (November 17, 2022) - -* Fix simple query sanitizer where query text contains a Unicode replacement character. -* Remove erroneous `name` argument from `DeallocateAll()`. Technically, this is a breaking change, but given that method was only added 5 days ago this change was accepted. (Bodo Kaiser) - -# 5.1.0 (November 12, 2022) - -* Update puddle to v2.1.2. This resolves a race condition and a deadlock in pgxpool. -* `QueryRewriter.RewriteQuery` now returns an error. Technically, this is a breaking change for any external implementers, but given the minimal likelihood that there are actually any external implementers this change was accepted. -* Expose `GetSSLPassword` support to pgx. -* Fix encode `ErrorResponse` unknown field handling. This would only affect pgproto3 being used directly as a proxy with a non-PostgreSQL server that included additional error fields. -* Fix date text format encoding with 5 digit years. -* Fix date values passed to a `sql.Scanner` as `string` instead of `time.Time`. -* DateCodec.DecodeValue can return `pgtype.InfinityModifier` instead of `string` for infinite values. This now matches the behavior of the timestamp types. -* Add domain type support to `Conn.LoadType()`. -* Add `RowToStructByName` and `RowToAddrOfStructByName`. (Pavlo Golub) -* Add `Conn.DeallocateAll()` to clear all prepared statements including the statement cache. (Bodo Kaiser) - -# 5.0.4 (October 24, 2022) - -* Fix: CollectOneRow prefers PostgreSQL error over pgx.ErrorNoRows -* Fix: some reflect Kind checks to first check for nil -* Bump golang.org/x/text dependency to placate snyk -* Fix: RowToStructByPos on structs with multiple anonymous sub-structs (Baptiste Fontaine) -* Fix: Exec checks if tx is closed - -# 5.0.3 (October 14, 2022) - -* Fix `driver.Valuer` handling edge cases that could cause infinite loop or crash - -# v5.0.2 (October 8, 2022) - -* Fix date encoding in text format to always use 2 digits for month and day -* Prefer driver.Valuer over wrap plans when encoding -* Fix scan to pointer to pointer to renamed type -* Allow scanning NULL even if PG and Go types are incompatible - -# v5.0.1 (September 24, 2022) - -* Fix 32-bit atomic usage -* Add MarshalJSON for Float8 (yogipristiawan) -* Add `[` and `]` to text encoding of `Lseg` -* Fix sqlScannerWrapper NULL handling - -# v5.0.0 (September 17, 2022) - -## Merged Packages - -`github.com/jackc/pgtype`, `github.com/jackc/pgconn`, and `github.com/jackc/pgproto3` are now included in the main -`github.com/jackc/pgx` repository. Previously there was confusion as to where issues should be reported, additional -release work due to releasing multiple packages, and less clear changelogs. - -## pgconn - -`CommandTag` is now an opaque type instead of directly exposing an underlying `[]byte`. - -The return value `ResultReader.Values()` is no longer safe to retain a reference to after a subsequent call to `NextRow()` or `Close()`. - -`Trace()` method adds low level message tracing similar to the `PQtrace` function in `libpq`. - -pgconn now uses non-blocking IO. This is a significant internal restructuring, but it should not cause any visible changes on its own. However, it is important in implementing other new features. - -`CheckConn()` checks a connection's liveness by doing a non-blocking read. This can be used to detect database restarts or network interruptions without executing a query or a ping. - -pgconn now supports pipeline mode. - -`*PgConn.ReceiveResults` removed. Use pipeline mode instead. - -`Timeout()` no longer considers `context.Canceled` as a timeout error. `context.DeadlineExceeded` still is considered a timeout error. - -## pgxpool - -`Connect` and `ConnectConfig` have been renamed to `New` and `NewWithConfig` respectively. The `LazyConnect` option has been removed. Pools always lazily connect. - -## pgtype - -The `pgtype` package has been significantly changed. - -### NULL Representation - -Previously, types had a `Status` field that could be `Undefined`, `Null`, or `Present`. This has been changed to a -`Valid` `bool` field to harmonize with how `database/sql` represents `NULL` and to make the zero value useable. - -Previously, a type that implemented `driver.Valuer` would have the `Value` method called even on a nil pointer. All nils -whether typed or untyped now represent `NULL`. - -### Codec and Value Split - -Previously, the type system combined decoding and encoding values with the value types. e.g. Type `Int8` both handled -encoding and decoding the PostgreSQL representation and acted as a value object. This caused some difficulties when -there was not an exact 1 to 1 relationship between the Go types and the PostgreSQL types For example, scanning a -PostgreSQL binary `numeric` into a Go `float64` was awkward (see https://github.com/jackc/pgtype/issues/147). This -concepts have been separated. A `Codec` only has responsibility for encoding and decoding values. Value types are -generally defined by implementing an interface that a particular `Codec` understands (e.g. `PointScanner` and -`PointValuer` for the PostgreSQL `point` type). - -### Array Types - -All array types are now handled by `ArrayCodec` instead of using code generation for each new array type. This also -means that less common array types such as `point[]` are now supported. `Array[T]` supports PostgreSQL multi-dimensional -arrays. - -### Composite Types - -Composite types must be registered before use. `CompositeFields` may still be used to construct and destruct composite -values, but any type may now implement `CompositeIndexGetter` and `CompositeIndexScanner` to be used as a composite. - -### Range Types - -Range types are now handled with types `RangeCodec` and `Range[T]`. This allows additional user defined range types to -easily be handled. Multirange types are handled similarly with `MultirangeCodec` and `Multirange[T]`. - -### pgxtype - -`LoadDataType` moved to `*Conn` as `LoadType`. - -### Bytea - -The `Bytea` and `GenericBinary` types have been replaced. Use the following instead: - -* `[]byte` - For normal usage directly use `[]byte`. -* `DriverBytes` - Uses driver memory only available until next database method call. Avoids a copy and an allocation. -* `PreallocBytes` - Uses preallocated byte slice to avoid an allocation. -* `UndecodedBytes` - Avoids any decoding. Allows working with raw bytes. - -### Dropped lib/pq Support - -`pgtype` previously supported and was tested against [lib/pq](https://github.com/lib/pq). While it will continue to work -in most cases this is no longer supported. - -### database/sql Scan - -Previously, most `Scan` implementations would convert `[]byte` to `string` automatically to decode a text value. Now -only `string` is handled. This is to allow the possibility of future binary support in `database/sql` mode by -considering `[]byte` to be binary format and `string` text format. This change should have no effect for any use with -`pgx`. The previous behavior was only necessary for `lib/pq` compatibility. - -Added `*Map.SQLScanner` to create a `sql.Scanner` for types such as `[]int32` and `Range[T]` that do not implement -`sql.Scanner` directly. - -### Number Type Fields Include Bit size - -`Int2`, `Int4`, `Int8`, `Float4`, `Float8`, and `Uint32` fields now include bit size. e.g. `Int` is renamed to `Int64`. -This matches the convention set by `database/sql`. In addition, for comparable types like `pgtype.Int8` and -`sql.NullInt64` the structures are identical. This means they can be directly converted one to another. - -### 3rd Party Type Integrations - -* Extracted integrations with https://github.com/shopspring/decimal and https://github.com/gofrs/uuid to - https://github.com/jackc/pgx-shopspring-decimal and https://github.com/jackc/pgx-gofrs-uuid respectively. This trims - the pgx dependency tree. - -### Other Changes - -* `Bit` and `Varbit` are both replaced by the `Bits` type. -* `CID`, `OID`, `OIDValue`, and `XID` are replaced by the `Uint32` type. -* `Hstore` is now defined as `map[string]*string`. -* `JSON` and `JSONB` types removed. Use `[]byte` or `string` directly. -* `QChar` type removed. Use `rune` or `byte` directly. -* `Inet` and `Cidr` types removed. Use `netip.Addr` and `netip.Prefix` directly. These types are more memory efficient than the previous `net.IPNet`. -* `Macaddr` type removed. Use `net.HardwareAddr` directly. -* Renamed `pgtype.ConnInfo` to `pgtype.Map`. -* Renamed `pgtype.DataType` to `pgtype.Type`. -* Renamed `pgtype.None` to `pgtype.Finite`. -* `RegisterType` now accepts a `*Type` instead of `Type`. -* Assorted array helper methods and types made private. - -## stdlib - -* Removed `AcquireConn` and `ReleaseConn` as that functionality has been built in since Go 1.13. - -## Reduced Memory Usage by Reusing Read Buffers - -Previously, the connection read buffer would allocate large chunks of memory and never reuse them. This allowed -transferring ownership to anything such as scanned values without incurring an additional allocation and memory copy. -However, this came at the cost of overall increased memory allocation size. But worse it was also possible to pin large -chunks of memory by retaining a reference to a small value that originally came directly from the read buffer. Now -ownership remains with the read buffer and anything needing to retain a value must make a copy. - -## Query Execution Modes - -Control over automatic prepared statement caching and simple protocol use are now combined into query execution mode. -See documentation for `QueryExecMode`. - -## QueryRewriter Interface and NamedArgs - -pgx now supports named arguments with the `NamedArgs` type. This is implemented via the new `QueryRewriter` interface which -allows arbitrary rewriting of query SQL and arguments. - -## RowScanner Interface - -The `RowScanner` interface allows a single argument to Rows.Scan to scan the entire row. - -## Rows Result Helpers - -* `CollectRows` and `RowTo*` functions simplify collecting results into a slice. -* `CollectOneRow` collects one row using `RowTo*` functions. -* `ForEachRow` simplifies scanning each row and executing code using the scanned values. `ForEachRow` replaces `QueryFunc`. - -## Tx Helpers - -Rather than every type that implemented `Begin` or `BeginTx` methods also needing to implement `BeginFunc` and -`BeginTxFunc` these methods have been converted to functions that take a db that implements `Begin` or `BeginTx`. - -## Improved Batch Query Ergonomics - -Previously, the code for building a batch went in one place before the call to `SendBatch`, and the code for reading the -results went in one place after the call to `SendBatch`. This could make it difficult to match up the query and the code -to handle the results. Now `Queue` returns a `QueuedQuery` which has methods `Query`, `QueryRow`, and `Exec` which can -be used to register a callback function that will handle the result. Callback functions are called automatically when -`BatchResults.Close` is called. - -## SendBatch Uses Pipeline Mode When Appropriate - -Previously, a batch with 10 unique parameterized statements executed 100 times would entail 11 network round trips. 1 -for each prepare / describe and 1 for executing them all. Now pipeline mode is used to prepare / describe all statements -in a single network round trip. So it would only take 2 round trips. - -## Tracing and Logging - -Internal logging support has been replaced with tracing hooks. This allows custom tracing integration with tools like OpenTelemetry. Package tracelog provides an adapter for pgx v4 loggers to act as a tracer. - -All integrations with 3rd party loggers have been extracted to separate repositories. This trims the pgx dependency -tree. diff --git a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md deleted file mode 100644 index c975a9372..000000000 --- a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md +++ /dev/null @@ -1,121 +0,0 @@ -# Contributing - -## Discuss Significant Changes - -Before you invest a significant amount of time on a change, please create a discussion or issue describing your -proposal. This will help to ensure your proposed change has a reasonable chance of being merged. - -## Avoid Dependencies - -Adding a dependency is a big deal. While on occasion a new dependency may be accepted, the default answer to any change -that adds a dependency is no. - -## Development Environment Setup - -pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the `PGX_TEST_DATABASE` -environment variable. The `PGX_TEST_DATABASE` environment variable can either be a URL or key-value pairs. In addition, -the standard `PG*` environment variables will be respected. Consider using [direnv](https://github.com/direnv/direnv) to -simplify environment variable handling. - -### Using an Existing PostgreSQL Cluster - -If you already have a PostgreSQL development server this is the quickest way to start and run the majority of the pgx -test suite. Some tests will be skipped that require server configuration changes (e.g. those testing different -authentication methods). - -Create and setup a test database: - -``` -export PGDATABASE=pgx_test -createdb -psql -c 'create extension hstore;' -psql -c 'create extension ltree;' -psql -c 'create domain uint64 as numeric(20,0);' -``` - -Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some installation methods -such as Homebrew do not. - -``` -createuser -s postgres -``` - -Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run the tests. - -``` -export PGX_TEST_DATABASE="host=/private/tmp database=pgx_test" -go test ./... -``` - -This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing different connection methods). - -### Creating a New PostgreSQL Cluster Exclusively for Testing - -The following environment variables need to be set both for initial setup and whenever the tests are run. (direnv is -highly recommended). Depending on your platform, you may need to change the host for `PGX_TEST_UNIX_SOCKET_CONN_STRING`. - -``` -export PGPORT=5015 -export PGUSER=postgres -export PGDATABASE=pgx_test -export POSTGRESQL_DATA_DIR=postgresql - -export PGX_TEST_DATABASE="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/private/tmp database=pgx_test" -export PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_scram password=secret database=pgx_test" -export PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" -export PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_pw password=secret" -export PGX_TEST_TLS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem" -export PGX_SSL_PASSWORD=certpw -export PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost user=pgx_sslcert sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test sslcert=`pwd`/.testdb/pgx_sslcert.crt sslkey=`pwd`/.testdb/pgx_sslcert.key" -``` - -Create a new database cluster. - -``` -initdb --locale=en_US -E UTF-8 --username=postgres .testdb/$POSTGRESQL_DATA_DIR - -echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf -cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf - -cd .testdb - -# Generate CA, server, and encrypted client certificates. -go run ../testsetup/generate_certs.go - -# Copy certificates to server directory and set permissions. -cp ca.pem $POSTGRESQL_DATA_DIR/root.crt -cp localhost.key $POSTGRESQL_DATA_DIR/server.key -chmod 600 $POSTGRESQL_DATA_DIR/server.key -cp localhost.crt $POSTGRESQL_DATA_DIR/server.crt - -cd .. -``` - - -Start the new cluster. This will be necessary whenever you are running pgx tests. - -``` -postgres -D .testdb/$POSTGRESQL_DATA_DIR -``` - -Setup the test database in the new cluster. - -``` -createdb -psql --no-psqlrc -f testsetup/postgresql_setup.sql -``` - -### PgBouncer - -There are tests specific for PgBouncer that will be executed if `PGX_TEST_PGBOUNCER_CONN_STRING` is set. - -### Optional Tests - -pgx supports multiple connection types and means of authentication. These tests are optional. They will only run if the -appropriate environment variables are set. In addition, there may be tests specific to particular PostgreSQL versions, -non-PostgreSQL servers (e.g. CockroachDB), or connection poolers (e.g. PgBouncer). `go test ./... -v | grep SKIP` to see -if any tests are being skipped. diff --git a/vendor/github.com/jackc/pgx/v5/LICENSE b/vendor/github.com/jackc/pgx/v5/LICENSE deleted file mode 100644 index 5c486c39a..000000000 --- a/vendor/github.com/jackc/pgx/v5/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013-2021 Jack Christensen - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/pgx/v5/README.md b/vendor/github.com/jackc/pgx/v5/README.md deleted file mode 100644 index bbeb1336c..000000000 --- a/vendor/github.com/jackc/pgx/v5/README.md +++ /dev/null @@ -1,174 +0,0 @@ -[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/pgx/v5.svg)](https://pkg.go.dev/github.com/jackc/pgx/v5) -[![Build Status](https://github.com/jackc/pgx/actions/workflows/ci.yml/badge.svg)](https://github.com/jackc/pgx/actions/workflows/ci.yml) - -# pgx - PostgreSQL Driver and Toolkit - -pgx is a pure Go driver and toolkit for PostgreSQL. - -The pgx driver is a low-level, high performance interface that exposes PostgreSQL-specific features such as `LISTEN` / -`NOTIFY` and `COPY`. It also includes an adapter for the standard `database/sql` interface. - -The toolkit component is a related set of packages that implement PostgreSQL functionality such as parsing the wire protocol -and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers, -proxies, load balancers, logical replication clients, etc. - -## Example Usage - -```go -package main - -import ( - "context" - "fmt" - "os" - - "github.com/jackc/pgx/v5" -) - -func main() { - // urlExample := "postgres://username:password@localhost:5432/database_name" - conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) - if err != nil { - fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err) - os.Exit(1) - } - defer conn.Close(context.Background()) - - var name string - var weight int64 - err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight) - if err != nil { - fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err) - os.Exit(1) - } - - fmt.Println(name, weight) -} -``` - -See the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx) for more information. - -## Features - -* Support for approximately 70 different PostgreSQL types -* Automatic statement preparation and caching -* Batch queries -* Single-round trip query mode -* Full TLS connection control -* Binary format support for custom types (allows for much quicker encoding/decoding) -* `COPY` protocol support for faster bulk data loads -* Tracing and logging support -* Connection pool with after-connect hook for arbitrary connection setup -* `LISTEN` / `NOTIFY` -* Conversion of PostgreSQL arrays to Go slice mappings for integers, floats, and strings -* `hstore` support -* `json` and `jsonb` support -* Maps `inet` and `cidr` PostgreSQL types to `netip.Addr` and `netip.Prefix` -* Large object support -* NULL mapping to pointer to pointer -* Supports `database/sql.Scanner` and `database/sql/driver.Valuer` interfaces for custom types -* Notice response handling -* Simulated nested transactions with savepoints - -## Choosing Between the pgx and database/sql Interfaces - -The pgx interface is faster. Many PostgreSQL specific features such as `LISTEN` / `NOTIFY` and `COPY` are not available -through the `database/sql` interface. - -The pgx interface is recommended when: - -1. The application only targets PostgreSQL. -2. No other libraries that require `database/sql` are in use. - -It is also possible to use the `database/sql` interface and convert a connection to the lower-level pgx interface as needed. - -## Testing - -See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions. - -## Architecture - -See the presentation at Golang Estonia, [PGX Top to Bottom](https://www.youtube.com/watch?v=sXMSWhcHCf8) for a description of pgx architecture. - -## Supported Go and PostgreSQL Versions - -pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases and for [PostgreSQL](https://www.postgresql.org/support/versioning/) the major releases in the last 5 years. This means pgx supports Go 1.21 and higher and PostgreSQL 12 and higher. pgx also is tested against the latest version of [CockroachDB](https://www.cockroachlabs.com/product/). - -## Version Policy - -pgx follows semantic versioning for the documented public API on stable releases. `v5` is the latest stable major version. - -## PGX Family Libraries - -### [github.com/jackc/pglogrepl](https://github.com/jackc/pglogrepl) - -pglogrepl provides functionality to act as a client for PostgreSQL logical replication. - -### [github.com/jackc/pgmock](https://github.com/jackc/pgmock) - -pgmock offers the ability to create a server that mocks the PostgreSQL wire protocol. This is used internally to test pgx by purposely inducing unusual errors. pgproto3 and pgmock together provide most of the foundational tooling required to implement a PostgreSQL proxy or MitM (such as for a custom connection pooler). - -### [github.com/jackc/tern](https://github.com/jackc/tern) - -tern is a stand-alone SQL migration system. - -### [github.com/jackc/pgerrcode](https://github.com/jackc/pgerrcode) - -pgerrcode contains constants for the PostgreSQL error codes. - -## Adapters for 3rd Party Types - -* [github.com/jackc/pgx-gofrs-uuid](https://github.com/jackc/pgx-gofrs-uuid) -* [github.com/jackc/pgx-shopspring-decimal](https://github.com/jackc/pgx-shopspring-decimal) -* [github.com/twpayne/pgx-geos](https://github.com/twpayne/pgx-geos) ([PostGIS](https://postgis.net/) and [GEOS](https://libgeos.org/) via [go-geos](https://github.com/twpayne/go-geos)) -* [github.com/vgarvardt/pgx-google-uuid](https://github.com/vgarvardt/pgx-google-uuid) - - -## Adapters for 3rd Party Tracers - -* [github.com/jackhopner/pgx-xray-tracer](https://github.com/jackhopner/pgx-xray-tracer) - -## Adapters for 3rd Party Loggers - -These adapters can be used with the tracelog package. - -* [github.com/jackc/pgx-go-kit-log](https://github.com/jackc/pgx-go-kit-log) -* [github.com/jackc/pgx-log15](https://github.com/jackc/pgx-log15) -* [github.com/jackc/pgx-logrus](https://github.com/jackc/pgx-logrus) -* [github.com/jackc/pgx-zap](https://github.com/jackc/pgx-zap) -* [github.com/jackc/pgx-zerolog](https://github.com/jackc/pgx-zerolog) -* [github.com/mcosta74/pgx-slog](https://github.com/mcosta74/pgx-slog) -* [github.com/kataras/pgx-golog](https://github.com/kataras/pgx-golog) - -## 3rd Party Libraries with PGX Support - -### [github.com/pashagolub/pgxmock](https://github.com/pashagolub/pgxmock) - -pgxmock is a mock library implementing pgx interfaces. -pgxmock has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection. - -### [github.com/georgysavva/scany](https://github.com/georgysavva/scany) - -Library for scanning data from a database into Go structs and more. - -### [github.com/vingarcia/ksql](https://github.com/vingarcia/ksql) - -A carefully designed SQL client for making using SQL easier, -more productive, and less error-prone on Golang. - -### [github.com/otan/gopgkrb5](https://github.com/otan/gopgkrb5) - -Adds GSSAPI / Kerberos authentication support. - -### [github.com/wcamarao/pmx](https://github.com/wcamarao/pmx) - -Explicit data mapping and scanning library for Go structs and slices. - -### [github.com/stephenafamo/scan](https://github.com/stephenafamo/scan) - -Type safe and flexible package for scanning database data into Go types. -Supports, structs, maps, slices and custom mapping functions. - -### [github.com/z0ne-dev/mgx](https://github.com/z0ne-dev/mgx) - -Code first migration library for native pgx (no database/sql abstraction). diff --git a/vendor/github.com/jackc/pgx/v5/Rakefile b/vendor/github.com/jackc/pgx/v5/Rakefile deleted file mode 100644 index d957573e9..000000000 --- a/vendor/github.com/jackc/pgx/v5/Rakefile +++ /dev/null @@ -1,18 +0,0 @@ -require "erb" - -rule '.go' => '.go.erb' do |task| - erb = ERB.new(File.read(task.source)) - File.write(task.name, "// Do not edit. Generated from #{task.source}\n" + erb.result(binding)) - sh "goimports", "-w", task.name -end - -generated_code_files = [ - "pgtype/int.go", - "pgtype/int_test.go", - "pgtype/integration_benchmark_test.go", - "pgtype/zeronull/int.go", - "pgtype/zeronull/int_test.go" -] - -desc "Generate code" -task generate: generated_code_files diff --git a/vendor/github.com/jackc/pgx/v5/batch.go b/vendor/github.com/jackc/pgx/v5/batch.go deleted file mode 100644 index c3c2834f2..000000000 --- a/vendor/github.com/jackc/pgx/v5/batch.go +++ /dev/null @@ -1,443 +0,0 @@ -package pgx - -import ( - "context" - "errors" - "fmt" - - "github.com/jackc/pgx/v5/pgconn" -) - -// QueuedQuery is a query that has been queued for execution via a Batch. -type QueuedQuery struct { - SQL string - Arguments []any - Fn batchItemFunc - sd *pgconn.StatementDescription -} - -type batchItemFunc func(br BatchResults) error - -// Query sets fn to be called when the response to qq is received. -func (qq *QueuedQuery) Query(fn func(rows Rows) error) { - qq.Fn = func(br BatchResults) error { - rows, _ := br.Query() - defer rows.Close() - - err := fn(rows) - if err != nil { - return err - } - rows.Close() - - return rows.Err() - } -} - -// Query sets fn to be called when the response to qq is received. -func (qq *QueuedQuery) QueryRow(fn func(row Row) error) { - qq.Fn = func(br BatchResults) error { - row := br.QueryRow() - return fn(row) - } -} - -// Exec sets fn to be called when the response to qq is received. -func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) { - qq.Fn = func(br BatchResults) error { - ct, err := br.Exec() - if err != nil { - return err - } - - return fn(ct) - } -} - -// Batch queries are a way of bundling multiple queries together to avoid -// unnecessary network round trips. A Batch must only be sent once. -type Batch struct { - QueuedQueries []*QueuedQuery -} - -// Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. The only pgx option -// argument that is supported is QueryRewriter. Queries are executed using the connection's DefaultQueryExecMode. -// -// While query can contain multiple statements if the connection's DefaultQueryExecMode is QueryModeSimple, this should -// be avoided. QueuedQuery.Fn must not be set as it will only be called for the first query. That is, QueuedQuery.Query, -// QueuedQuery.QueryRow, and QueuedQuery.Exec must not be called. In addition, any error messages or tracing that -// include the current query may reference the wrong query. -func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery { - qq := &QueuedQuery{ - SQL: query, - Arguments: arguments, - } - b.QueuedQueries = append(b.QueuedQueries, qq) - return qq -} - -// Len returns number of queries that have been queued so far. -func (b *Batch) Len() int { - return len(b.QueuedQueries) -} - -type BatchResults interface { - // Exec reads the results from the next query in the batch as if the query has been sent with Conn.Exec. Prefer - // calling Exec on the QueuedQuery. - Exec() (pgconn.CommandTag, error) - - // Query reads the results from the next query in the batch as if the query has been sent with Conn.Query. Prefer - // calling Query on the QueuedQuery. - Query() (Rows, error) - - // QueryRow reads the results from the next query in the batch as if the query has been sent with Conn.QueryRow. - // Prefer calling QueryRow on the QueuedQuery. - QueryRow() Row - - // Close closes the batch operation. All unread results are read and any callback functions registered with - // QueuedQuery.Query, QueuedQuery.QueryRow, or QueuedQuery.Exec will be called. If a callback function returns an - // error or the batch encounters an error subsequent callback functions will not be called. - // - // Close must be called before the underlying connection can be used again. Any error that occurred during a batch - // operation may have made it impossible to resyncronize the connection with the server. In this case the underlying - // connection will have been closed. - // - // Close is safe to call multiple times. If it returns an error subsequent calls will return the same error. Callback - // functions will not be rerun. - Close() error -} - -type batchResults struct { - ctx context.Context - conn *Conn - mrr *pgconn.MultiResultReader - err error - b *Batch - qqIdx int - closed bool - endTraced bool -} - -// Exec reads the results from the next query in the batch as if the query has been sent with Exec. -func (br *batchResults) Exec() (pgconn.CommandTag, error) { - if br.err != nil { - return pgconn.CommandTag{}, br.err - } - if br.closed { - return pgconn.CommandTag{}, fmt.Errorf("batch already closed") - } - - query, arguments, _ := br.nextQueryAndArgs() - - if !br.mrr.NextResult() { - err := br.mrr.Close() - if err == nil { - err = errors.New("no more results in batch") - } - if br.conn.batchTracer != nil { - br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - Err: err, - }) - } - return pgconn.CommandTag{}, err - } - - commandTag, err := br.mrr.ResultReader().Close() - if err != nil { - br.err = err - br.mrr.Close() - } - - if br.conn.batchTracer != nil { - br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - CommandTag: commandTag, - Err: br.err, - }) - } - - return commandTag, br.err -} - -// Query reads the results from the next query in the batch as if the query has been sent with Query. -func (br *batchResults) Query() (Rows, error) { - query, arguments, ok := br.nextQueryAndArgs() - if !ok { - query = "batch query" - } - - if br.err != nil { - return &baseRows{err: br.err, closed: true}, br.err - } - - if br.closed { - alreadyClosedErr := fmt.Errorf("batch already closed") - return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr - } - - rows := br.conn.getRows(br.ctx, query, arguments) - rows.batchTracer = br.conn.batchTracer - - if !br.mrr.NextResult() { - rows.err = br.mrr.Close() - if rows.err == nil { - rows.err = errors.New("no more results in batch") - } - rows.closed = true - - if br.conn.batchTracer != nil { - br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - Err: rows.err, - }) - } - - return rows, rows.err - } - - rows.resultReader = br.mrr.ResultReader() - return rows, nil -} - -// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow. -func (br *batchResults) QueryRow() Row { - rows, _ := br.Query() - return (*connRow)(rows.(*baseRows)) - -} - -// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to -// resyncronize the connection with the server. In this case the underlying connection will have been closed. -func (br *batchResults) Close() error { - defer func() { - if !br.endTraced { - if br.conn != nil && br.conn.batchTracer != nil { - br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err}) - } - br.endTraced = true - } - }() - - if br.err != nil { - return br.err - } - - if br.closed { - return nil - } - - // Read and run fn for all remaining items - for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { - if br.b.QueuedQueries[br.qqIdx].Fn != nil { - err := br.b.QueuedQueries[br.qqIdx].Fn(br) - if err != nil { - br.err = err - } - } else { - br.Exec() - } - } - - br.closed = true - - err := br.mrr.Close() - if br.err == nil { - br.err = err - } - - return br.err -} - -func (br *batchResults) earlyError() error { - return br.err -} - -func (br *batchResults) nextQueryAndArgs() (query string, args []any, ok bool) { - if br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { - bi := br.b.QueuedQueries[br.qqIdx] - query = bi.SQL - args = bi.Arguments - ok = true - br.qqIdx++ - } - return -} - -type pipelineBatchResults struct { - ctx context.Context - conn *Conn - pipeline *pgconn.Pipeline - lastRows *baseRows - err error - b *Batch - qqIdx int - closed bool - endTraced bool -} - -// Exec reads the results from the next query in the batch as if the query has been sent with Exec. -func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) { - if br.err != nil { - return pgconn.CommandTag{}, br.err - } - if br.closed { - return pgconn.CommandTag{}, fmt.Errorf("batch already closed") - } - if br.lastRows != nil && br.lastRows.err != nil { - return pgconn.CommandTag{}, br.err - } - - query, arguments, err := br.nextQueryAndArgs() - if err != nil { - return pgconn.CommandTag{}, err - } - - results, err := br.pipeline.GetResults() - if err != nil { - br.err = err - return pgconn.CommandTag{}, br.err - } - var commandTag pgconn.CommandTag - switch results := results.(type) { - case *pgconn.ResultReader: - commandTag, br.err = results.Close() - default: - return pgconn.CommandTag{}, fmt.Errorf("unexpected pipeline result: %T", results) - } - - if br.conn.batchTracer != nil { - br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - CommandTag: commandTag, - Err: br.err, - }) - } - - return commandTag, br.err -} - -// Query reads the results from the next query in the batch as if the query has been sent with Query. -func (br *pipelineBatchResults) Query() (Rows, error) { - if br.err != nil { - return &baseRows{err: br.err, closed: true}, br.err - } - - if br.closed { - alreadyClosedErr := fmt.Errorf("batch already closed") - return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr - } - - if br.lastRows != nil && br.lastRows.err != nil { - br.err = br.lastRows.err - return &baseRows{err: br.err, closed: true}, br.err - } - - query, arguments, err := br.nextQueryAndArgs() - if err != nil { - return &baseRows{err: err, closed: true}, err - } - - rows := br.conn.getRows(br.ctx, query, arguments) - rows.batchTracer = br.conn.batchTracer - br.lastRows = rows - - results, err := br.pipeline.GetResults() - if err != nil { - br.err = err - rows.err = err - rows.closed = true - - if br.conn.batchTracer != nil { - br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ - SQL: query, - Args: arguments, - Err: err, - }) - } - } else { - switch results := results.(type) { - case *pgconn.ResultReader: - rows.resultReader = results - default: - err = fmt.Errorf("unexpected pipeline result: %T", results) - br.err = err - rows.err = err - rows.closed = true - } - } - - return rows, rows.err -} - -// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow. -func (br *pipelineBatchResults) QueryRow() Row { - rows, _ := br.Query() - return (*connRow)(rows.(*baseRows)) - -} - -// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to -// resyncronize the connection with the server. In this case the underlying connection will have been closed. -func (br *pipelineBatchResults) Close() error { - defer func() { - if !br.endTraced { - if br.conn.batchTracer != nil { - br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err}) - } - br.endTraced = true - } - }() - - if br.err == nil && br.lastRows != nil && br.lastRows.err != nil { - br.err = br.lastRows.err - return br.err - } - - if br.closed { - return br.err - } - - // Read and run fn for all remaining items - for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { - if br.b.QueuedQueries[br.qqIdx].Fn != nil { - err := br.b.QueuedQueries[br.qqIdx].Fn(br) - if err != nil { - br.err = err - } - } else { - br.Exec() - } - } - - br.closed = true - - err := br.pipeline.Close() - if br.err == nil { - br.err = err - } - - return br.err -} - -func (br *pipelineBatchResults) earlyError() error { - return br.err -} - -func (br *pipelineBatchResults) nextQueryAndArgs() (query string, args []any, err error) { - if br.b == nil { - return "", nil, errors.New("no reference to batch") - } - - if br.qqIdx >= len(br.b.QueuedQueries) { - return "", nil, errors.New("no more results in batch") - } - - bi := br.b.QueuedQueries[br.qqIdx] - br.qqIdx++ - return bi.SQL, bi.Arguments, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/conn.go b/vendor/github.com/jackc/pgx/v5/conn.go deleted file mode 100644 index ed6a3a09e..000000000 --- a/vendor/github.com/jackc/pgx/v5/conn.go +++ /dev/null @@ -1,1444 +0,0 @@ -package pgx - -import ( - "context" - "crypto/sha256" - "database/sql" - "encoding/hex" - "errors" - "fmt" - "strconv" - "strings" - "time" - - "github.com/jackc/pgx/v5/internal/sanitize" - "github.com/jackc/pgx/v5/internal/stmtcache" - "github.com/jackc/pgx/v5/pgconn" - "github.com/jackc/pgx/v5/pgtype" -) - -// ConnConfig contains all the options used to establish a connection. It must be created by ParseConfig and -// then it can be modified. A manually initialized ConnConfig will cause ConnectConfig to panic. -type ConnConfig struct { - pgconn.Config - - Tracer QueryTracer - - // Original connection string that was parsed into config. - connString string - - // StatementCacheCapacity is maximum size of the statement cache used when executing a query with "cache_statement" - // query exec mode. - StatementCacheCapacity int - - // DescriptionCacheCapacity is the maximum size of the description cache used when executing a query with - // "cache_describe" query exec mode. - DescriptionCacheCapacity int - - // DefaultQueryExecMode controls the default mode for executing queries. By default pgx uses the extended protocol - // and automatically prepares and caches prepared statements. However, this may be incompatible with proxies such as - // PGBouncer. In this case it may be preferable to use QueryExecModeExec or QueryExecModeSimpleProtocol. The same - // functionality can be controlled on a per query basis by passing a QueryExecMode as the first query argument. - DefaultQueryExecMode QueryExecMode - - createdByParseConfig bool // Used to enforce created by ParseConfig rule. -} - -// ParseConfigOptions contains options that control how a config is built such as getsslpassword. -type ParseConfigOptions struct { - pgconn.ParseConfigOptions -} - -// Copy returns a deep copy of the config that is safe to use and modify. -// The only exception is the tls.Config: -// according to the tls.Config docs it must not be modified after creation. -func (cc *ConnConfig) Copy() *ConnConfig { - newConfig := new(ConnConfig) - *newConfig = *cc - newConfig.Config = *newConfig.Config.Copy() - return newConfig -} - -// ConnString returns the connection string as parsed by pgx.ParseConfig into pgx.ConnConfig. -func (cc *ConnConfig) ConnString() string { return cc.connString } - -// Conn is a PostgreSQL connection handle. It is not safe for concurrent usage. Use a connection pool to manage access -// to multiple database connections from multiple goroutines. -type Conn struct { - pgConn *pgconn.PgConn - config *ConnConfig // config used when establishing this connection - preparedStatements map[string]*pgconn.StatementDescription - statementCache stmtcache.Cache - descriptionCache stmtcache.Cache - - queryTracer QueryTracer - batchTracer BatchTracer - copyFromTracer CopyFromTracer - prepareTracer PrepareTracer - - notifications []*pgconn.Notification - - doneChan chan struct{} - closedChan chan error - - typeMap *pgtype.Map - - wbuf []byte - eqb ExtendedQueryBuilder -} - -// Identifier a PostgreSQL identifier or name. Identifiers can be composed of -// multiple parts such as ["schema", "table"] or ["table", "column"]. -type Identifier []string - -// Sanitize returns a sanitized string safe for SQL interpolation. -func (ident Identifier) Sanitize() string { - parts := make([]string, len(ident)) - for i := range ident { - s := strings.ReplaceAll(ident[i], string([]byte{0}), "") - parts[i] = `"` + strings.ReplaceAll(s, `"`, `""`) + `"` - } - return strings.Join(parts, ".") -} - -var ( - // ErrNoRows occurs when rows are expected but none are returned. - ErrNoRows = newProxyErr(sql.ErrNoRows, "no rows in result set") - // ErrTooManyRows occurs when more rows than expected are returned. - ErrTooManyRows = errors.New("too many rows in result set") -) - -func newProxyErr(background error, msg string) error { - return &proxyError{ - msg: msg, - background: background, - } -} - -type proxyError struct { - msg string - background error -} - -func (err *proxyError) Error() string { return err.msg } - -func (err *proxyError) Unwrap() error { return err.background } - -var ( - errDisabledStatementCache = fmt.Errorf("cannot use QueryExecModeCacheStatement with disabled statement cache") - errDisabledDescriptionCache = fmt.Errorf("cannot use QueryExecModeCacheDescribe with disabled description cache") -) - -// Connect establishes a connection with a PostgreSQL server with a connection string. See -// pgconn.Connect for details. -func Connect(ctx context.Context, connString string) (*Conn, error) { - connConfig, err := ParseConfig(connString) - if err != nil { - return nil, err - } - return connect(ctx, connConfig) -} - -// ConnectWithOptions behaves exactly like Connect with the addition of options. At the present options is only used to -// provide a GetSSLPassword function. -func ConnectWithOptions(ctx context.Context, connString string, options ParseConfigOptions) (*Conn, error) { - connConfig, err := ParseConfigWithOptions(connString, options) - if err != nil { - return nil, err - } - return connect(ctx, connConfig) -} - -// ConnectConfig establishes a connection with a PostgreSQL server with a configuration struct. -// connConfig must have been created by ParseConfig. -func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error) { - // In general this improves safety. In particular avoid the config.Config.OnNotification mutation from affecting other - // connections with the same config. See https://github.com/jackc/pgx/issues/618. - connConfig = connConfig.Copy() - - return connect(ctx, connConfig) -} - -// ParseConfigWithOptions behaves exactly as ParseConfig does with the addition of options. At the present options is -// only used to provide a GetSSLPassword function. -func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*ConnConfig, error) { - config, err := pgconn.ParseConfigWithOptions(connString, options.ParseConfigOptions) - if err != nil { - return nil, err - } - - statementCacheCapacity := 512 - if s, ok := config.RuntimeParams["statement_cache_capacity"]; ok { - delete(config.RuntimeParams, "statement_cache_capacity") - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - return nil, fmt.Errorf("cannot parse statement_cache_capacity: %w", err) - } - statementCacheCapacity = int(n) - } - - descriptionCacheCapacity := 512 - if s, ok := config.RuntimeParams["description_cache_capacity"]; ok { - delete(config.RuntimeParams, "description_cache_capacity") - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - return nil, fmt.Errorf("cannot parse description_cache_capacity: %w", err) - } - descriptionCacheCapacity = int(n) - } - - defaultQueryExecMode := QueryExecModeCacheStatement - if s, ok := config.RuntimeParams["default_query_exec_mode"]; ok { - delete(config.RuntimeParams, "default_query_exec_mode") - switch s { - case "cache_statement": - defaultQueryExecMode = QueryExecModeCacheStatement - case "cache_describe": - defaultQueryExecMode = QueryExecModeCacheDescribe - case "describe_exec": - defaultQueryExecMode = QueryExecModeDescribeExec - case "exec": - defaultQueryExecMode = QueryExecModeExec - case "simple_protocol": - defaultQueryExecMode = QueryExecModeSimpleProtocol - default: - return nil, fmt.Errorf("invalid default_query_exec_mode: %s", s) - } - } - - connConfig := &ConnConfig{ - Config: *config, - createdByParseConfig: true, - StatementCacheCapacity: statementCacheCapacity, - DescriptionCacheCapacity: descriptionCacheCapacity, - DefaultQueryExecMode: defaultQueryExecMode, - connString: connString, - } - - return connConfig, nil -} - -// ParseConfig creates a ConnConfig from a connection string. ParseConfig handles all options that [pgconn.ParseConfig] -// does. In addition, it accepts the following options: -// -// - default_query_exec_mode. -// Possible values: "cache_statement", "cache_describe", "describe_exec", "exec", and "simple_protocol". See -// QueryExecMode constant documentation for the meaning of these values. Default: "cache_statement". -// -// - statement_cache_capacity. -// The maximum size of the statement cache used when executing a query with "cache_statement" query exec mode. -// Default: 512. -// -// - description_cache_capacity. -// The maximum size of the description cache used when executing a query with "cache_describe" query exec mode. -// Default: 512. -func ParseConfig(connString string) (*ConnConfig, error) { - return ParseConfigWithOptions(connString, ParseConfigOptions{}) -} - -// connect connects to a database. connect takes ownership of config. The caller must not use or access it again. -func connect(ctx context.Context, config *ConnConfig) (c *Conn, err error) { - if connectTracer, ok := config.Tracer.(ConnectTracer); ok { - ctx = connectTracer.TraceConnectStart(ctx, TraceConnectStartData{ConnConfig: config}) - defer func() { - connectTracer.TraceConnectEnd(ctx, TraceConnectEndData{Conn: c, Err: err}) - }() - } - - // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from - // zero values. - if !config.createdByParseConfig { - panic("config must be created by ParseConfig") - } - - c = &Conn{ - config: config, - typeMap: pgtype.NewMap(), - queryTracer: config.Tracer, - } - - if t, ok := c.queryTracer.(BatchTracer); ok { - c.batchTracer = t - } - if t, ok := c.queryTracer.(CopyFromTracer); ok { - c.copyFromTracer = t - } - if t, ok := c.queryTracer.(PrepareTracer); ok { - c.prepareTracer = t - } - - // Only install pgx notification system if no other callback handler is present. - if config.Config.OnNotification == nil { - config.Config.OnNotification = c.bufferNotifications - } - - c.pgConn, err = pgconn.ConnectConfig(ctx, &config.Config) - if err != nil { - return nil, err - } - - c.preparedStatements = make(map[string]*pgconn.StatementDescription) - c.doneChan = make(chan struct{}) - c.closedChan = make(chan error) - c.wbuf = make([]byte, 0, 1024) - - if c.config.StatementCacheCapacity > 0 { - c.statementCache = stmtcache.NewLRUCache(c.config.StatementCacheCapacity) - } - - if c.config.DescriptionCacheCapacity > 0 { - c.descriptionCache = stmtcache.NewLRUCache(c.config.DescriptionCacheCapacity) - } - - return c, nil -} - -// Close closes a connection. It is safe to call Close on an already closed -// connection. -func (c *Conn) Close(ctx context.Context) error { - if c.IsClosed() { - return nil - } - - err := c.pgConn.Close(ctx) - return err -} - -// Prepare creates a prepared statement with name and sql. sql can contain placeholders for bound parameters. These -// placeholders are referenced positionally as $1, $2, etc. name can be used instead of sql with Query, QueryRow, and -// Exec to execute the statement. It can also be used with Batch.Queue. -// -// The underlying PostgreSQL identifier for the prepared statement will be name if name != sql or a digest of sql if -// name == sql. -// -// Prepare is idempotent; i.e. it is safe to call Prepare multiple times with the same name and sql arguments. This -// allows a code path to Prepare and Query/Exec without concern for if the statement has already been prepared. -func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.StatementDescription, err error) { - if c.prepareTracer != nil { - ctx = c.prepareTracer.TracePrepareStart(ctx, c, TracePrepareStartData{Name: name, SQL: sql}) - } - - if name != "" { - var ok bool - if sd, ok = c.preparedStatements[name]; ok && sd.SQL == sql { - if c.prepareTracer != nil { - c.prepareTracer.TracePrepareEnd(ctx, c, TracePrepareEndData{AlreadyPrepared: true}) - } - return sd, nil - } - } - - if c.prepareTracer != nil { - defer func() { - c.prepareTracer.TracePrepareEnd(ctx, c, TracePrepareEndData{Err: err}) - }() - } - - var psName, psKey string - if name == sql { - digest := sha256.Sum256([]byte(sql)) - psName = "stmt_" + hex.EncodeToString(digest[0:24]) - psKey = sql - } else { - psName = name - psKey = name - } - - sd, err = c.pgConn.Prepare(ctx, psName, sql, nil) - if err != nil { - return nil, err - } - - if psKey != "" { - c.preparedStatements[psKey] = sd - } - - return sd, nil -} - -// Deallocate releases a prepared statement. Calling Deallocate on a non-existent prepared statement will succeed. -func (c *Conn) Deallocate(ctx context.Context, name string) error { - var psName string - sd := c.preparedStatements[name] - if sd != nil { - psName = sd.Name - } else { - psName = name - } - - err := c.pgConn.Deallocate(ctx, psName) - if err != nil { - return err - } - - if sd != nil { - delete(c.preparedStatements, name) - } - - return nil -} - -// DeallocateAll releases all previously prepared statements from the server and client, where it also resets the statement and description cache. -func (c *Conn) DeallocateAll(ctx context.Context) error { - c.preparedStatements = map[string]*pgconn.StatementDescription{} - if c.config.StatementCacheCapacity > 0 { - c.statementCache = stmtcache.NewLRUCache(c.config.StatementCacheCapacity) - } - if c.config.DescriptionCacheCapacity > 0 { - c.descriptionCache = stmtcache.NewLRUCache(c.config.DescriptionCacheCapacity) - } - _, err := c.pgConn.Exec(ctx, "deallocate all").ReadAll() - return err -} - -func (c *Conn) bufferNotifications(_ *pgconn.PgConn, n *pgconn.Notification) { - c.notifications = append(c.notifications, n) -} - -// WaitForNotification waits for a PostgreSQL notification. It wraps the underlying pgconn notification system in a -// slightly more convenient form. -func (c *Conn) WaitForNotification(ctx context.Context) (*pgconn.Notification, error) { - var n *pgconn.Notification - - // Return already received notification immediately - if len(c.notifications) > 0 { - n = c.notifications[0] - c.notifications = c.notifications[1:] - return n, nil - } - - err := c.pgConn.WaitForNotification(ctx) - if len(c.notifications) > 0 { - n = c.notifications[0] - c.notifications = c.notifications[1:] - } - return n, err -} - -// IsClosed reports if the connection has been closed. -func (c *Conn) IsClosed() bool { - return c.pgConn.IsClosed() -} - -func (c *Conn) die(err error) { - if c.IsClosed() { - return - } - - ctx, cancel := context.WithCancel(context.Background()) - cancel() // force immediate hard cancel - c.pgConn.Close(ctx) -} - -func quoteIdentifier(s string) string { - return `"` + strings.ReplaceAll(s, `"`, `""`) + `"` -} - -// Ping delegates to the underlying *pgconn.PgConn.Ping. -func (c *Conn) Ping(ctx context.Context) error { - return c.pgConn.Ping(ctx) -} - -// PgConn returns the underlying *pgconn.PgConn. This is an escape hatch method that allows lower level access to the -// PostgreSQL connection than pgx exposes. -// -// It is strongly recommended that the connection be idle (no in-progress queries) before the underlying *pgconn.PgConn -// is used and the connection must be returned to the same state before any *pgx.Conn methods are again used. -func (c *Conn) PgConn() *pgconn.PgConn { return c.pgConn } - -// TypeMap returns the connection info used for this connection. -func (c *Conn) TypeMap() *pgtype.Map { return c.typeMap } - -// Config returns a copy of config that was used to establish this connection. -func (c *Conn) Config() *ConnConfig { return c.config.Copy() } - -// Exec executes sql. sql can be either a prepared statement name or an SQL string. arguments should be referenced -// positionally from the sql string as $1, $2, etc. -func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { - if c.queryTracer != nil { - ctx = c.queryTracer.TraceQueryStart(ctx, c, TraceQueryStartData{SQL: sql, Args: arguments}) - } - - if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil { - return pgconn.CommandTag{}, err - } - - commandTag, err := c.exec(ctx, sql, arguments...) - - if c.queryTracer != nil { - c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{CommandTag: commandTag, Err: err}) - } - - return commandTag, err -} - -func (c *Conn) exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) { - mode := c.config.DefaultQueryExecMode - var queryRewriter QueryRewriter - -optionLoop: - for len(arguments) > 0 { - switch arg := arguments[0].(type) { - case QueryExecMode: - mode = arg - arguments = arguments[1:] - case QueryRewriter: - queryRewriter = arg - arguments = arguments[1:] - default: - break optionLoop - } - } - - if queryRewriter != nil { - sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments) - if err != nil { - return pgconn.CommandTag{}, fmt.Errorf("rewrite query failed: %w", err) - } - } - - // Always use simple protocol when there are no arguments. - if len(arguments) == 0 { - mode = QueryExecModeSimpleProtocol - } - - if sd, ok := c.preparedStatements[sql]; ok { - return c.execPrepared(ctx, sd, arguments) - } - - switch mode { - case QueryExecModeCacheStatement: - if c.statementCache == nil { - return pgconn.CommandTag{}, errDisabledStatementCache - } - sd := c.statementCache.Get(sql) - if sd == nil { - sd, err = c.Prepare(ctx, stmtcache.StatementName(sql), sql) - if err != nil { - return pgconn.CommandTag{}, err - } - c.statementCache.Put(sd) - } - - return c.execPrepared(ctx, sd, arguments) - case QueryExecModeCacheDescribe: - if c.descriptionCache == nil { - return pgconn.CommandTag{}, errDisabledDescriptionCache - } - sd := c.descriptionCache.Get(sql) - if sd == nil { - sd, err = c.Prepare(ctx, "", sql) - if err != nil { - return pgconn.CommandTag{}, err - } - c.descriptionCache.Put(sd) - } - - return c.execParams(ctx, sd, arguments) - case QueryExecModeDescribeExec: - sd, err := c.Prepare(ctx, "", sql) - if err != nil { - return pgconn.CommandTag{}, err - } - return c.execPrepared(ctx, sd, arguments) - case QueryExecModeExec: - return c.execSQLParams(ctx, sql, arguments) - case QueryExecModeSimpleProtocol: - return c.execSimpleProtocol(ctx, sql, arguments) - default: - return pgconn.CommandTag{}, fmt.Errorf("unknown QueryExecMode: %v", mode) - } -} - -func (c *Conn) execSimpleProtocol(ctx context.Context, sql string, arguments []any) (commandTag pgconn.CommandTag, err error) { - if len(arguments) > 0 { - sql, err = c.sanitizeForSimpleQuery(sql, arguments...) - if err != nil { - return pgconn.CommandTag{}, err - } - } - - mrr := c.pgConn.Exec(ctx, sql) - for mrr.NextResult() { - commandTag, _ = mrr.ResultReader().Close() - } - err = mrr.Close() - return commandTag, err -} - -func (c *Conn) execParams(ctx context.Context, sd *pgconn.StatementDescription, arguments []any) (pgconn.CommandTag, error) { - err := c.eqb.Build(c.typeMap, sd, arguments) - if err != nil { - return pgconn.CommandTag{}, err - } - - result := c.pgConn.ExecParams(ctx, sd.SQL, c.eqb.ParamValues, sd.ParamOIDs, c.eqb.ParamFormats, c.eqb.ResultFormats).Read() - c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. - return result.CommandTag, result.Err -} - -func (c *Conn) execPrepared(ctx context.Context, sd *pgconn.StatementDescription, arguments []any) (pgconn.CommandTag, error) { - err := c.eqb.Build(c.typeMap, sd, arguments) - if err != nil { - return pgconn.CommandTag{}, err - } - - result := c.pgConn.ExecPrepared(ctx, sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats).Read() - c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. - return result.CommandTag, result.Err -} - -type unknownArgumentTypeQueryExecModeExecError struct { - arg any -} - -func (e *unknownArgumentTypeQueryExecModeExecError) Error() string { - return fmt.Sprintf("cannot use unregistered type %T as query argument in QueryExecModeExec", e.arg) -} - -func (c *Conn) execSQLParams(ctx context.Context, sql string, args []any) (pgconn.CommandTag, error) { - err := c.eqb.Build(c.typeMap, nil, args) - if err != nil { - return pgconn.CommandTag{}, err - } - - result := c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats).Read() - c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. - return result.CommandTag, result.Err -} - -func (c *Conn) getRows(ctx context.Context, sql string, args []any) *baseRows { - r := &baseRows{} - - r.ctx = ctx - r.queryTracer = c.queryTracer - r.typeMap = c.typeMap - r.startTime = time.Now() - r.sql = sql - r.args = args - r.conn = c - - return r -} - -type QueryExecMode int32 - -const ( - _ QueryExecMode = iota - - // Automatically prepare and cache statements. This uses the extended protocol. Queries are executed in a single round - // trip after the statement is cached. This is the default. If the database schema is modified or the search_path is - // changed after a statement is cached then the first execution of a previously cached query may fail. e.g. If the - // number of columns returned by a "SELECT *" changes or the type of a column is changed. - QueryExecModeCacheStatement - - // Cache statement descriptions (i.e. argument and result types) and assume they do not change. This uses the extended - // protocol. Queries are executed in a single round trip after the description is cached. If the database schema is - // modified or the search_path is changed after a statement is cached then the first execution of a previously cached - // query may fail. e.g. If the number of columns returned by a "SELECT *" changes or the type of a column is changed. - QueryExecModeCacheDescribe - - // Get the statement description on every execution. This uses the extended protocol. Queries require two round trips - // to execute. It does not use named prepared statements. But it does use the unnamed prepared statement to get the - // statement description on the first round trip and then uses it to execute the query on the second round trip. This - // may cause problems with connection poolers that switch the underlying connection between round trips. It is safe - // even when the database schema is modified concurrently. - QueryExecModeDescribeExec - - // Assume the PostgreSQL query parameter types based on the Go type of the arguments. This uses the extended protocol - // with text formatted parameters and results. Queries are executed in a single round trip. Type mappings can be - // registered with pgtype.Map.RegisterDefaultPgType. Queries will be rejected that have arguments that are - // unregistered or ambiguous. e.g. A map[string]string may have the PostgreSQL type json or hstore. Modes that know - // the PostgreSQL type can use a map[string]string directly as an argument. This mode cannot. - // - // On rare occasions user defined types may behave differently when encoded in the text format instead of the binary - // format. For example, this could happen if a "type RomanNumeral int32" implements fmt.Stringer to format integers as - // Roman numerals (e.g. 7 is VII). The binary format would properly encode the integer 7 as the binary value for 7. - // But the text format would encode the integer 7 as the string "VII". As QueryExecModeExec uses the text format, it - // is possible that changing query mode from another mode to QueryExecModeExec could change the behavior of the query. - // This should not occur with types pgx supports directly and can be avoided by registering the types with - // pgtype.Map.RegisterDefaultPgType and implementing the appropriate type interfaces. In the cas of RomanNumeral, it - // should implement pgtype.Int64Valuer. - QueryExecModeExec - - // Use the simple protocol. Assume the PostgreSQL query parameter types based on the Go type of the arguments. Queries - // are executed in a single round trip. Type mappings can be registered with pgtype.Map.RegisterDefaultPgType. Queries - // will be rejected that have arguments that are unregistered or ambiguous. e.g. A map[string]string may have the - // PostgreSQL type json or hstore. Modes that know the PostgreSQL type can use a map[string]string directly as an - // argument. This mode cannot. - // - // QueryExecModeSimpleProtocol should have the user application visible behavior as QueryExecModeExec. This includes - // the warning regarding differences in text format and binary format encoding with user defined types. There may be - // other minor exceptions such as behavior when multiple result returning queries are erroneously sent in a single - // string. - // - // QueryExecModeSimpleProtocol uses client side parameter interpolation. All values are quoted and escaped. Prefer - // QueryExecModeExec over QueryExecModeSimpleProtocol whenever possible. In general QueryExecModeSimpleProtocol should - // only be used if connecting to a proxy server, connection pool server, or non-PostgreSQL server that does not - // support the extended protocol. - QueryExecModeSimpleProtocol -) - -func (m QueryExecMode) String() string { - switch m { - case QueryExecModeCacheStatement: - return "cache statement" - case QueryExecModeCacheDescribe: - return "cache describe" - case QueryExecModeDescribeExec: - return "describe exec" - case QueryExecModeExec: - return "exec" - case QueryExecModeSimpleProtocol: - return "simple protocol" - default: - return "invalid" - } -} - -// QueryResultFormats controls the result format (text=0, binary=1) of a query by result column position. -type QueryResultFormats []int16 - -// QueryResultFormatsByOID controls the result format (text=0, binary=1) of a query by the result column OID. -type QueryResultFormatsByOID map[uint32]int16 - -// QueryRewriter rewrites a query when used as the first arguments to a query method. -type QueryRewriter interface { - RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) -} - -// Query sends a query to the server and returns a Rows to read the results. Only errors encountered sending the query -// and initializing Rows will be returned. Err() on the returned Rows must be checked after the Rows is closed to -// determine if the query executed successfully. -// -// The returned Rows must be closed before the connection can be used again. It is safe to attempt to read from the -// returned Rows even if an error is returned. The error will be the available in rows.Err() after rows are closed. It -// is allowed to ignore the error returned from Query and handle it in Rows. -// -// It is possible for a call of FieldDescriptions on the returned Rows to return nil even if the Query call did not -// return an error. -// -// It is possible for a query to return one or more rows before encountering an error. In most cases the rows should be -// collected before processing rather than processed while receiving each row. This avoids the possibility of the -// application processing rows from a query that the server rejected. The CollectRows function is useful here. -// -// An implementor of QueryRewriter may be passed as the first element of args. It can rewrite the sql and change or -// replace args. For example, NamedArgs is QueryRewriter that implements named arguments. -// -// For extra control over how the query is executed, the types QueryExecMode, QueryResultFormats, and -// QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely -// needed. See the documentation for those types for details. -func (c *Conn) Query(ctx context.Context, sql string, args ...any) (Rows, error) { - if c.queryTracer != nil { - ctx = c.queryTracer.TraceQueryStart(ctx, c, TraceQueryStartData{SQL: sql, Args: args}) - } - - if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil { - if c.queryTracer != nil { - c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{Err: err}) - } - return &baseRows{err: err, closed: true}, err - } - - var resultFormats QueryResultFormats - var resultFormatsByOID QueryResultFormatsByOID - mode := c.config.DefaultQueryExecMode - var queryRewriter QueryRewriter - -optionLoop: - for len(args) > 0 { - switch arg := args[0].(type) { - case QueryResultFormats: - resultFormats = arg - args = args[1:] - case QueryResultFormatsByOID: - resultFormatsByOID = arg - args = args[1:] - case QueryExecMode: - mode = arg - args = args[1:] - case QueryRewriter: - queryRewriter = arg - args = args[1:] - default: - break optionLoop - } - } - - if queryRewriter != nil { - var err error - originalSQL := sql - originalArgs := args - sql, args, err = queryRewriter.RewriteQuery(ctx, c, sql, args) - if err != nil { - rows := c.getRows(ctx, originalSQL, originalArgs) - err = fmt.Errorf("rewrite query failed: %w", err) - rows.fatal(err) - return rows, err - } - } - - // Bypass any statement caching. - if sql == "" { - mode = QueryExecModeSimpleProtocol - } - - c.eqb.reset() - rows := c.getRows(ctx, sql, args) - - var err error - sd, explicitPreparedStatement := c.preparedStatements[sql] - if sd != nil || mode == QueryExecModeCacheStatement || mode == QueryExecModeCacheDescribe || mode == QueryExecModeDescribeExec { - if sd == nil { - sd, err = c.getStatementDescription(ctx, mode, sql) - if err != nil { - rows.fatal(err) - return rows, err - } - } - - if len(sd.ParamOIDs) != len(args) { - rows.fatal(fmt.Errorf("expected %d arguments, got %d", len(sd.ParamOIDs), len(args))) - return rows, rows.err - } - - rows.sql = sd.SQL - - err = c.eqb.Build(c.typeMap, sd, args) - if err != nil { - rows.fatal(err) - return rows, rows.err - } - - if resultFormatsByOID != nil { - resultFormats = make([]int16, len(sd.Fields)) - for i := range resultFormats { - resultFormats[i] = resultFormatsByOID[uint32(sd.Fields[i].DataTypeOID)] - } - } - - if resultFormats == nil { - resultFormats = c.eqb.ResultFormats - } - - if !explicitPreparedStatement && mode == QueryExecModeCacheDescribe { - rows.resultReader = c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, sd.ParamOIDs, c.eqb.ParamFormats, resultFormats) - } else { - rows.resultReader = c.pgConn.ExecPrepared(ctx, sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, resultFormats) - } - } else if mode == QueryExecModeExec { - err := c.eqb.Build(c.typeMap, nil, args) - if err != nil { - rows.fatal(err) - return rows, rows.err - } - - rows.resultReader = c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats) - } else if mode == QueryExecModeSimpleProtocol { - sql, err = c.sanitizeForSimpleQuery(sql, args...) - if err != nil { - rows.fatal(err) - return rows, err - } - - mrr := c.pgConn.Exec(ctx, sql) - if mrr.NextResult() { - rows.resultReader = mrr.ResultReader() - rows.multiResultReader = mrr - } else { - err = mrr.Close() - rows.fatal(err) - return rows, err - } - - return rows, nil - } else { - err = fmt.Errorf("unknown QueryExecMode: %v", mode) - rows.fatal(err) - return rows, rows.err - } - - c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. - - return rows, rows.err -} - -// getStatementDescription returns the statement description of the sql query -// according to the given mode. -// -// If the mode is one that doesn't require to know the param and result OIDs -// then nil is returned without error. -func (c *Conn) getStatementDescription( - ctx context.Context, - mode QueryExecMode, - sql string, -) (sd *pgconn.StatementDescription, err error) { - switch mode { - case QueryExecModeCacheStatement: - if c.statementCache == nil { - return nil, errDisabledStatementCache - } - sd = c.statementCache.Get(sql) - if sd == nil { - sd, err = c.Prepare(ctx, stmtcache.StatementName(sql), sql) - if err != nil { - return nil, err - } - c.statementCache.Put(sd) - } - case QueryExecModeCacheDescribe: - if c.descriptionCache == nil { - return nil, errDisabledDescriptionCache - } - sd = c.descriptionCache.Get(sql) - if sd == nil { - sd, err = c.Prepare(ctx, "", sql) - if err != nil { - return nil, err - } - c.descriptionCache.Put(sd) - } - case QueryExecModeDescribeExec: - return c.Prepare(ctx, "", sql) - } - return sd, err -} - -// QueryRow is a convenience wrapper over Query. Any error that occurs while -// querying is deferred until calling Scan on the returned Row. That Row will -// error with ErrNoRows if no rows are returned. -func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) Row { - rows, _ := c.Query(ctx, sql, args...) - return (*connRow)(rows.(*baseRows)) -} - -// SendBatch sends all queued queries to the server at once. All queries are run in an implicit transaction unless -// explicit transaction control statements are executed. The returned BatchResults must be closed before the connection -// is used again. -// -// Depending on the QueryExecMode, all queries may be prepared before any are executed. This means that creating a table -// and using it in a subsequent query in the same batch can fail. -func (c *Conn) SendBatch(ctx context.Context, b *Batch) (br BatchResults) { - if c.batchTracer != nil { - ctx = c.batchTracer.TraceBatchStart(ctx, c, TraceBatchStartData{Batch: b}) - defer func() { - err := br.(interface{ earlyError() error }).earlyError() - if err != nil { - c.batchTracer.TraceBatchEnd(ctx, c, TraceBatchEndData{Err: err}) - } - }() - } - - if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil { - return &batchResults{ctx: ctx, conn: c, err: err} - } - - for _, bi := range b.QueuedQueries { - var queryRewriter QueryRewriter - sql := bi.SQL - arguments := bi.Arguments - - optionLoop: - for len(arguments) > 0 { - // Update Batch.Queue function comment when additional options are implemented - switch arg := arguments[0].(type) { - case QueryRewriter: - queryRewriter = arg - arguments = arguments[1:] - default: - break optionLoop - } - } - - if queryRewriter != nil { - var err error - sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments) - if err != nil { - return &batchResults{ctx: ctx, conn: c, err: fmt.Errorf("rewrite query failed: %w", err)} - } - } - - bi.SQL = sql - bi.Arguments = arguments - } - - // TODO: changing mode per batch? Update Batch.Queue function comment when implemented - mode := c.config.DefaultQueryExecMode - if mode == QueryExecModeSimpleProtocol { - return c.sendBatchQueryExecModeSimpleProtocol(ctx, b) - } - - // All other modes use extended protocol and thus can use prepared statements. - for _, bi := range b.QueuedQueries { - if sd, ok := c.preparedStatements[bi.SQL]; ok { - bi.sd = sd - } - } - - switch mode { - case QueryExecModeExec: - return c.sendBatchQueryExecModeExec(ctx, b) - case QueryExecModeCacheStatement: - return c.sendBatchQueryExecModeCacheStatement(ctx, b) - case QueryExecModeCacheDescribe: - return c.sendBatchQueryExecModeCacheDescribe(ctx, b) - case QueryExecModeDescribeExec: - return c.sendBatchQueryExecModeDescribeExec(ctx, b) - default: - panic("unknown QueryExecMode") - } -} - -func (c *Conn) sendBatchQueryExecModeSimpleProtocol(ctx context.Context, b *Batch) *batchResults { - var sb strings.Builder - for i, bi := range b.QueuedQueries { - if i > 0 { - sb.WriteByte(';') - } - sql, err := c.sanitizeForSimpleQuery(bi.SQL, bi.Arguments...) - if err != nil { - return &batchResults{ctx: ctx, conn: c, err: err} - } - sb.WriteString(sql) - } - mrr := c.pgConn.Exec(ctx, sb.String()) - return &batchResults{ - ctx: ctx, - conn: c, - mrr: mrr, - b: b, - qqIdx: 0, - } -} - -func (c *Conn) sendBatchQueryExecModeExec(ctx context.Context, b *Batch) *batchResults { - batch := &pgconn.Batch{} - - for _, bi := range b.QueuedQueries { - sd := bi.sd - if sd != nil { - err := c.eqb.Build(c.typeMap, sd, bi.Arguments) - if err != nil { - return &batchResults{ctx: ctx, conn: c, err: err} - } - - batch.ExecPrepared(sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats) - } else { - err := c.eqb.Build(c.typeMap, nil, bi.Arguments) - if err != nil { - return &batchResults{ctx: ctx, conn: c, err: err} - } - batch.ExecParams(bi.SQL, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats) - } - } - - c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. - - mrr := c.pgConn.ExecBatch(ctx, batch) - - return &batchResults{ - ctx: ctx, - conn: c, - mrr: mrr, - b: b, - qqIdx: 0, - } -} - -func (c *Conn) sendBatchQueryExecModeCacheStatement(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) { - if c.statementCache == nil { - return &pipelineBatchResults{ctx: ctx, conn: c, err: errDisabledStatementCache, closed: true} - } - - distinctNewQueries := []*pgconn.StatementDescription{} - distinctNewQueriesIdxMap := make(map[string]int) - - for _, bi := range b.QueuedQueries { - if bi.sd == nil { - sd := c.statementCache.Get(bi.SQL) - if sd != nil { - bi.sd = sd - } else { - if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { - bi.sd = distinctNewQueries[idx] - } else { - sd = &pgconn.StatementDescription{ - Name: stmtcache.StatementName(bi.SQL), - SQL: bi.SQL, - } - distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) - distinctNewQueries = append(distinctNewQueries, sd) - bi.sd = sd - } - } - } - } - - return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, c.statementCache) -} - -func (c *Conn) sendBatchQueryExecModeCacheDescribe(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) { - if c.descriptionCache == nil { - return &pipelineBatchResults{ctx: ctx, conn: c, err: errDisabledDescriptionCache, closed: true} - } - - distinctNewQueries := []*pgconn.StatementDescription{} - distinctNewQueriesIdxMap := make(map[string]int) - - for _, bi := range b.QueuedQueries { - if bi.sd == nil { - sd := c.descriptionCache.Get(bi.SQL) - if sd != nil { - bi.sd = sd - } else { - if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { - bi.sd = distinctNewQueries[idx] - } else { - sd = &pgconn.StatementDescription{ - SQL: bi.SQL, - } - distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) - distinctNewQueries = append(distinctNewQueries, sd) - bi.sd = sd - } - } - } - } - - return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, c.descriptionCache) -} - -func (c *Conn) sendBatchQueryExecModeDescribeExec(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) { - distinctNewQueries := []*pgconn.StatementDescription{} - distinctNewQueriesIdxMap := make(map[string]int) - - for _, bi := range b.QueuedQueries { - if bi.sd == nil { - if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { - bi.sd = distinctNewQueries[idx] - } else { - sd := &pgconn.StatementDescription{ - SQL: bi.SQL, - } - distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) - distinctNewQueries = append(distinctNewQueries, sd) - bi.sd = sd - } - } - } - - return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, nil) -} - -func (c *Conn) sendBatchExtendedWithDescription(ctx context.Context, b *Batch, distinctNewQueries []*pgconn.StatementDescription, sdCache stmtcache.Cache) (pbr *pipelineBatchResults) { - pipeline := c.pgConn.StartPipeline(ctx) - defer func() { - if pbr != nil && pbr.err != nil { - pipeline.Close() - } - }() - - // Prepare any needed queries - if len(distinctNewQueries) > 0 { - err := func() (err error) { - for _, sd := range distinctNewQueries { - pipeline.SendPrepare(sd.Name, sd.SQL, nil) - } - - // Store all statements we are preparing into the cache. It's fine if it overflows because HandleInvalidated will - // clean them up later. - if sdCache != nil { - for _, sd := range distinctNewQueries { - sdCache.Put(sd) - } - } - - // If something goes wrong preparing the statements, we need to invalidate the cache entries we just added. - defer func() { - if err != nil && sdCache != nil { - for _, sd := range distinctNewQueries { - sdCache.Invalidate(sd.SQL) - } - } - }() - - err = pipeline.Sync() - if err != nil { - return err - } - - for _, sd := range distinctNewQueries { - results, err := pipeline.GetResults() - if err != nil { - return err - } - - resultSD, ok := results.(*pgconn.StatementDescription) - if !ok { - return fmt.Errorf("expected statement description, got %T", results) - } - - // Fill in the previously empty / pending statement descriptions. - sd.ParamOIDs = resultSD.ParamOIDs - sd.Fields = resultSD.Fields - } - - results, err := pipeline.GetResults() - if err != nil { - return err - } - - _, ok := results.(*pgconn.PipelineSync) - if !ok { - return fmt.Errorf("expected sync, got %T", results) - } - - return nil - }() - if err != nil { - return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true} - } - } - - // Queue the queries. - for _, bi := range b.QueuedQueries { - err := c.eqb.Build(c.typeMap, bi.sd, bi.Arguments) - if err != nil { - // we wrap the error so we the user can understand which query failed inside the batch - err = fmt.Errorf("error building query %s: %w", bi.SQL, err) - return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true} - } - - if bi.sd.Name == "" { - pipeline.SendQueryParams(bi.sd.SQL, c.eqb.ParamValues, bi.sd.ParamOIDs, c.eqb.ParamFormats, c.eqb.ResultFormats) - } else { - pipeline.SendQueryPrepared(bi.sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats) - } - } - - err := pipeline.Sync() - if err != nil { - return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true} - } - - return &pipelineBatchResults{ - ctx: ctx, - conn: c, - pipeline: pipeline, - b: b, - } -} - -func (c *Conn) sanitizeForSimpleQuery(sql string, args ...any) (string, error) { - if c.pgConn.ParameterStatus("standard_conforming_strings") != "on" { - return "", errors.New("simple protocol queries must be run with standard_conforming_strings=on") - } - - if c.pgConn.ParameterStatus("client_encoding") != "UTF8" { - return "", errors.New("simple protocol queries must be run with client_encoding=UTF8") - } - - var err error - valueArgs := make([]any, len(args)) - for i, a := range args { - valueArgs[i], err = convertSimpleArgument(c.typeMap, a) - if err != nil { - return "", err - } - } - - return sanitize.SanitizeSQL(sql, valueArgs...) -} - -// LoadType inspects the database for typeName and produces a pgtype.Type suitable for registration. typeName must be -// the name of a type where the underlying type(s) is already understood by pgx. It is for derived types. In particular, -// typeName must be one of the following: -// - An array type name of a type that is already registered. e.g. "_foo" when "foo" is registered. -// - A composite type name where all field types are already registered. -// - A domain type name where the base type is already registered. -// - An enum type name. -// - A range type name where the element type is already registered. -// - A multirange type name where the element type is already registered. -func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, error) { - var oid uint32 - - err := c.QueryRow(ctx, "select $1::text::regtype::oid;", typeName).Scan(&oid) - if err != nil { - return nil, err - } - - var typtype string - var typbasetype uint32 - - err = c.QueryRow(ctx, "select typtype::text, typbasetype from pg_type where oid=$1", oid).Scan(&typtype, &typbasetype) - if err != nil { - return nil, err - } - - switch typtype { - case "b": // array - elementOID, err := c.getArrayElementOID(ctx, oid) - if err != nil { - return nil, err - } - - dt, ok := c.TypeMap().TypeForOID(elementOID) - if !ok { - return nil, errors.New("array element OID not registered") - } - - return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt}}, nil - case "c": // composite - fields, err := c.getCompositeFields(ctx, oid) - if err != nil { - return nil, err - } - - return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.CompositeCodec{Fields: fields}}, nil - case "d": // domain - dt, ok := c.TypeMap().TypeForOID(typbasetype) - if !ok { - return nil, errors.New("domain base type OID not registered") - } - - return &pgtype.Type{Name: typeName, OID: oid, Codec: dt.Codec}, nil - case "e": // enum - return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.EnumCodec{}}, nil - case "r": // range - elementOID, err := c.getRangeElementOID(ctx, oid) - if err != nil { - return nil, err - } - - dt, ok := c.TypeMap().TypeForOID(elementOID) - if !ok { - return nil, errors.New("range element OID not registered") - } - - return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.RangeCodec{ElementType: dt}}, nil - case "m": // multirange - elementOID, err := c.getMultiRangeElementOID(ctx, oid) - if err != nil { - return nil, err - } - - dt, ok := c.TypeMap().TypeForOID(elementOID) - if !ok { - return nil, errors.New("multirange element OID not registered") - } - - return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.MultirangeCodec{ElementType: dt}}, nil - default: - return &pgtype.Type{}, errors.New("unknown typtype") - } -} - -func (c *Conn) getArrayElementOID(ctx context.Context, oid uint32) (uint32, error) { - var typelem uint32 - - err := c.QueryRow(ctx, "select typelem from pg_type where oid=$1", oid).Scan(&typelem) - if err != nil { - return 0, err - } - - return typelem, nil -} - -func (c *Conn) getRangeElementOID(ctx context.Context, oid uint32) (uint32, error) { - var typelem uint32 - - err := c.QueryRow(ctx, "select rngsubtype from pg_range where rngtypid=$1", oid).Scan(&typelem) - if err != nil { - return 0, err - } - - return typelem, nil -} - -func (c *Conn) getMultiRangeElementOID(ctx context.Context, oid uint32) (uint32, error) { - var typelem uint32 - - err := c.QueryRow(ctx, "select rngtypid from pg_range where rngmultitypid=$1", oid).Scan(&typelem) - if err != nil { - return 0, err - } - - return typelem, nil -} - -func (c *Conn) getCompositeFields(ctx context.Context, oid uint32) ([]pgtype.CompositeCodecField, error) { - var typrelid uint32 - - err := c.QueryRow(ctx, "select typrelid from pg_type where oid=$1", oid).Scan(&typrelid) - if err != nil { - return nil, err - } - - var fields []pgtype.CompositeCodecField - var fieldName string - var fieldOID uint32 - rows, _ := c.Query(ctx, `select attname, atttypid -from pg_attribute -where attrelid=$1 - and not attisdropped - and attnum > 0 -order by attnum`, - typrelid, - ) - _, err = ForEachRow(rows, []any{&fieldName, &fieldOID}, func() error { - dt, ok := c.TypeMap().TypeForOID(fieldOID) - if !ok { - return fmt.Errorf("unknown composite type field OID: %v", fieldOID) - } - fields = append(fields, pgtype.CompositeCodecField{Name: fieldName, Type: dt}) - return nil - }) - if err != nil { - return nil, err - } - - return fields, nil -} - -func (c *Conn) deallocateInvalidatedCachedStatements(ctx context.Context) error { - if txStatus := c.pgConn.TxStatus(); txStatus != 'I' && txStatus != 'T' { - return nil - } - - if c.descriptionCache != nil { - c.descriptionCache.RemoveInvalidated() - } - - var invalidatedStatements []*pgconn.StatementDescription - if c.statementCache != nil { - invalidatedStatements = c.statementCache.GetInvalidated() - } - - if len(invalidatedStatements) == 0 { - return nil - } - - pipeline := c.pgConn.StartPipeline(ctx) - defer pipeline.Close() - - for _, sd := range invalidatedStatements { - pipeline.SendDeallocate(sd.Name) - } - - err := pipeline.Sync() - if err != nil { - return fmt.Errorf("failed to deallocate cached statement(s): %w", err) - } - - err = pipeline.Close() - if err != nil { - return fmt.Errorf("failed to deallocate cached statement(s): %w", err) - } - - c.statementCache.RemoveInvalidated() - for _, sd := range invalidatedStatements { - delete(c.preparedStatements, sd.Name) - } - - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/copy_from.go b/vendor/github.com/jackc/pgx/v5/copy_from.go deleted file mode 100644 index abcd22396..000000000 --- a/vendor/github.com/jackc/pgx/v5/copy_from.go +++ /dev/null @@ -1,276 +0,0 @@ -package pgx - -import ( - "bytes" - "context" - "fmt" - "io" - - "github.com/jackc/pgx/v5/internal/pgio" - "github.com/jackc/pgx/v5/pgconn" -) - -// CopyFromRows returns a CopyFromSource interface over the provided rows slice -// making it usable by *Conn.CopyFrom. -func CopyFromRows(rows [][]any) CopyFromSource { - return ©FromRows{rows: rows, idx: -1} -} - -type copyFromRows struct { - rows [][]any - idx int -} - -func (ctr *copyFromRows) Next() bool { - ctr.idx++ - return ctr.idx < len(ctr.rows) -} - -func (ctr *copyFromRows) Values() ([]any, error) { - return ctr.rows[ctr.idx], nil -} - -func (ctr *copyFromRows) Err() error { - return nil -} - -// CopyFromSlice returns a CopyFromSource interface over a dynamic func -// making it usable by *Conn.CopyFrom. -func CopyFromSlice(length int, next func(int) ([]any, error)) CopyFromSource { - return ©FromSlice{next: next, idx: -1, len: length} -} - -type copyFromSlice struct { - next func(int) ([]any, error) - idx int - len int - err error -} - -func (cts *copyFromSlice) Next() bool { - cts.idx++ - return cts.idx < cts.len -} - -func (cts *copyFromSlice) Values() ([]any, error) { - values, err := cts.next(cts.idx) - if err != nil { - cts.err = err - } - return values, err -} - -func (cts *copyFromSlice) Err() error { - return cts.err -} - -// CopyFromFunc returns a CopyFromSource interface that relies on nxtf for values. -// nxtf returns rows until it either signals an 'end of data' by returning row=nil and err=nil, -// or it returns an error. If nxtf returns an error, the copy is aborted. -func CopyFromFunc(nxtf func() (row []any, err error)) CopyFromSource { - return ©FromFunc{next: nxtf} -} - -type copyFromFunc struct { - next func() ([]any, error) - valueRow []any - err error -} - -func (g *copyFromFunc) Next() bool { - g.valueRow, g.err = g.next() - // only return true if valueRow exists and no error - return g.valueRow != nil && g.err == nil -} - -func (g *copyFromFunc) Values() ([]any, error) { - return g.valueRow, g.err -} - -func (g *copyFromFunc) Err() error { - return g.err -} - -// CopyFromSource is the interface used by *Conn.CopyFrom as the source for copy data. -type CopyFromSource interface { - // Next returns true if there is another row and makes the next row data - // available to Values(). When there are no more rows available or an error - // has occurred it returns false. - Next() bool - - // Values returns the values for the current row. - Values() ([]any, error) - - // Err returns any error that has been encountered by the CopyFromSource. If - // this is not nil *Conn.CopyFrom will abort the copy. - Err() error -} - -type copyFrom struct { - conn *Conn - tableName Identifier - columnNames []string - rowSrc CopyFromSource - readerErrChan chan error - mode QueryExecMode -} - -func (ct *copyFrom) run(ctx context.Context) (int64, error) { - if ct.conn.copyFromTracer != nil { - ctx = ct.conn.copyFromTracer.TraceCopyFromStart(ctx, ct.conn, TraceCopyFromStartData{ - TableName: ct.tableName, - ColumnNames: ct.columnNames, - }) - } - - quotedTableName := ct.tableName.Sanitize() - cbuf := &bytes.Buffer{} - for i, cn := range ct.columnNames { - if i != 0 { - cbuf.WriteString(", ") - } - cbuf.WriteString(quoteIdentifier(cn)) - } - quotedColumnNames := cbuf.String() - - var sd *pgconn.StatementDescription - switch ct.mode { - case QueryExecModeExec, QueryExecModeSimpleProtocol: - // These modes don't support the binary format. Before the inclusion of the - // QueryExecModes, Conn.Prepare was called on every COPY operation to get - // the OIDs. These prepared statements were not cached. - // - // Since that's the same behavior provided by QueryExecModeDescribeExec, - // we'll default to that mode. - ct.mode = QueryExecModeDescribeExec - fallthrough - case QueryExecModeCacheStatement, QueryExecModeCacheDescribe, QueryExecModeDescribeExec: - var err error - sd, err = ct.conn.getStatementDescription( - ctx, - ct.mode, - fmt.Sprintf("select %s from %s", quotedColumnNames, quotedTableName), - ) - if err != nil { - return 0, fmt.Errorf("statement description failed: %w", err) - } - default: - return 0, fmt.Errorf("unknown QueryExecMode: %v", ct.mode) - } - - r, w := io.Pipe() - doneChan := make(chan struct{}) - - go func() { - defer close(doneChan) - - // Purposely NOT using defer w.Close(). See https://github.com/golang/go/issues/24283. - buf := ct.conn.wbuf - - buf = append(buf, "PGCOPY\n\377\r\n\000"...) - buf = pgio.AppendInt32(buf, 0) - buf = pgio.AppendInt32(buf, 0) - - moreRows := true - for moreRows { - var err error - moreRows, buf, err = ct.buildCopyBuf(buf, sd) - if err != nil { - w.CloseWithError(err) - return - } - - if ct.rowSrc.Err() != nil { - w.CloseWithError(ct.rowSrc.Err()) - return - } - - if len(buf) > 0 { - _, err = w.Write(buf) - if err != nil { - w.Close() - return - } - } - - buf = buf[:0] - } - - w.Close() - }() - - commandTag, err := ct.conn.pgConn.CopyFrom(ctx, r, fmt.Sprintf("copy %s ( %s ) from stdin binary;", quotedTableName, quotedColumnNames)) - - r.Close() - <-doneChan - - if ct.conn.copyFromTracer != nil { - ct.conn.copyFromTracer.TraceCopyFromEnd(ctx, ct.conn, TraceCopyFromEndData{ - CommandTag: commandTag, - Err: err, - }) - } - - return commandTag.RowsAffected(), err -} - -func (ct *copyFrom) buildCopyBuf(buf []byte, sd *pgconn.StatementDescription) (bool, []byte, error) { - const sendBufSize = 65536 - 5 // The packet has a 5-byte header - lastBufLen := 0 - largestRowLen := 0 - - for ct.rowSrc.Next() { - lastBufLen = len(buf) - - values, err := ct.rowSrc.Values() - if err != nil { - return false, nil, err - } - if len(values) != len(ct.columnNames) { - return false, nil, fmt.Errorf("expected %d values, got %d values", len(ct.columnNames), len(values)) - } - - buf = pgio.AppendInt16(buf, int16(len(ct.columnNames))) - for i, val := range values { - buf, err = encodeCopyValue(ct.conn.typeMap, buf, sd.Fields[i].DataTypeOID, val) - if err != nil { - return false, nil, err - } - } - - rowLen := len(buf) - lastBufLen - if rowLen > largestRowLen { - largestRowLen = rowLen - } - - // Try not to overflow size of the buffer PgConn.CopyFrom will be reading into. If that happens then the nature of - // io.Pipe means that the next Read will be short. This can lead to pathological send sizes such as 65531, 13, 65531 - // 13, 65531, 13, 65531, 13. - if len(buf) > sendBufSize-largestRowLen { - return true, buf, nil - } - } - - return false, buf, nil -} - -// CopyFrom uses the PostgreSQL copy protocol to perform bulk data insertion. It returns the number of rows copied and -// an error. -// -// CopyFrom requires all values use the binary format. A pgtype.Type that supports the binary format must be registered -// for the type of each column. Almost all types implemented by pgx support the binary format. -// -// Even though enum types appear to be strings they still must be registered to use with CopyFrom. This can be done with -// Conn.LoadType and pgtype.Map.RegisterType. -func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) { - ct := ©From{ - conn: c, - tableName: tableName, - columnNames: columnNames, - rowSrc: rowSrc, - readerErrChan: make(chan error), - mode: c.config.DefaultQueryExecMode, - } - - return ct.run(ctx) -} diff --git a/vendor/github.com/jackc/pgx/v5/derived_types.go b/vendor/github.com/jackc/pgx/v5/derived_types.go deleted file mode 100644 index 22ab069cf..000000000 --- a/vendor/github.com/jackc/pgx/v5/derived_types.go +++ /dev/null @@ -1,262 +0,0 @@ -package pgx - -import ( - "context" - "fmt" - "regexp" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/pgtype" -) - -/* -buildLoadDerivedTypesSQL generates the correct query for retrieving type information. - - pgVersion: the major version of the PostgreSQL server - typeNames: the names of the types to load. If nil, load all types. -*/ -func buildLoadDerivedTypesSQL(pgVersion int64, typeNames []string) string { - supportsMultirange := (pgVersion >= 14) - var typeNamesClause string - - if typeNames == nil { - // This should not occur; this will not return any types - typeNamesClause = "= ''" - } else { - typeNamesClause = "= ANY($1)" - } - parts := make([]string, 0, 10) - - // Each of the type names provided might be found in pg_class or pg_type. - // Additionally, it may or may not include a schema portion. - parts = append(parts, ` -WITH RECURSIVE --- find the OIDs in pg_class which match one of the provided type names -selected_classes(oid,reltype) AS ( - -- this query uses the namespace search path, so will match type names without a schema prefix - SELECT pg_class.oid, pg_class.reltype - FROM pg_catalog.pg_class - LEFT JOIN pg_catalog.pg_namespace n ON n.oid = pg_class.relnamespace - WHERE pg_catalog.pg_table_is_visible(pg_class.oid) - AND relname `, typeNamesClause, ` -UNION ALL - -- this query will only match type names which include the schema prefix - SELECT pg_class.oid, pg_class.reltype - FROM pg_class - INNER JOIN pg_namespace ON (pg_class.relnamespace = pg_namespace.oid) - WHERE nspname || '.' || relname `, typeNamesClause, ` -), -selected_types(oid) AS ( - -- collect the OIDs from pg_types which correspond to the selected classes - SELECT reltype AS oid - FROM selected_classes -UNION ALL - -- as well as any other type names which match our criteria - SELECT pg_type.oid - FROM pg_type - LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid) - WHERE typname `, typeNamesClause, ` - OR nspname || '.' || typname `, typeNamesClause, ` -), --- this builds a parent/child mapping of objects, allowing us to know --- all the child (ie: dependent) types that a parent (type) requires --- As can be seen, there are 3 ways this can occur (the last of which --- is due to being a composite class, where the composite fields are children) -pc(parent, child) AS ( - SELECT parent.oid, parent.typelem - FROM pg_type parent - WHERE parent.typtype = 'b' AND parent.typelem != 0 -UNION ALL - SELECT parent.oid, parent.typbasetype - FROM pg_type parent - WHERE parent.typtypmod = -1 AND parent.typbasetype != 0 -UNION ALL - SELECT pg_type.oid, atttypid - FROM pg_attribute - INNER JOIN pg_class ON (pg_class.oid = pg_attribute.attrelid) - INNER JOIN pg_type ON (pg_type.oid = pg_class.reltype) - WHERE NOT attisdropped - AND attnum > 0 -), --- Now construct a recursive query which includes a 'depth' element. --- This is used to ensure that the "youngest" children are registered before --- their parents. -relationships(parent, child, depth) AS ( - SELECT DISTINCT 0::OID, selected_types.oid, 0 - FROM selected_types -UNION ALL - SELECT pg_type.oid AS parent, pg_attribute.atttypid AS child, 1 - FROM selected_classes c - inner join pg_type ON (c.reltype = pg_type.oid) - inner join pg_attribute on (c.oid = pg_attribute.attrelid) -UNION ALL - SELECT pc.parent, pc.child, relationships.depth + 1 - FROM pc - INNER JOIN relationships ON (pc.parent = relationships.child) -), --- composite fields need to be encapsulated as a couple of arrays to provide the required information for registration -composite AS ( - SELECT pg_type.oid, ARRAY_AGG(attname ORDER BY attnum) AS attnames, ARRAY_AGG(atttypid ORDER BY ATTNUM) AS atttypids - FROM pg_attribute - INNER JOIN pg_class ON (pg_class.oid = pg_attribute.attrelid) - INNER JOIN pg_type ON (pg_type.oid = pg_class.reltype) - WHERE NOT attisdropped - AND attnum > 0 - GROUP BY pg_type.oid -) --- Bring together this information, showing all the information which might possibly be required --- to complete the registration, applying filters to only show the items which relate to the selected --- types/classes. -SELECT typname, - pg_namespace.nspname, - typtype, - typbasetype, - typelem, - pg_type.oid,`) - if supportsMultirange { - parts = append(parts, ` - COALESCE(multirange.rngtypid, 0) AS rngtypid,`) - } else { - parts = append(parts, ` - 0 AS rngtypid,`) - } - parts = append(parts, ` - COALESCE(pg_range.rngsubtype, 0) AS rngsubtype, - attnames, atttypids - FROM relationships - INNER JOIN pg_type ON (pg_type.oid = relationships.child) - LEFT OUTER JOIN pg_range ON (pg_type.oid = pg_range.rngtypid)`) - if supportsMultirange { - parts = append(parts, ` - LEFT OUTER JOIN pg_range multirange ON (pg_type.oid = multirange.rngmultitypid)`) - } - - parts = append(parts, ` - LEFT OUTER JOIN composite USING (oid) - LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid) - WHERE NOT (typtype = 'b' AND typelem = 0)`) - parts = append(parts, ` - GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, pg_type.oid, pg_range.rngsubtype,`) - if supportsMultirange { - parts = append(parts, ` - multirange.rngtypid,`) - } - parts = append(parts, ` - attnames, atttypids - ORDER BY MAX(depth) desc, typname;`) - return strings.Join(parts, "") -} - -type derivedTypeInfo struct { - Oid, Typbasetype, Typelem, Rngsubtype, Rngtypid uint32 - TypeName, Typtype, NspName string - Attnames []string - Atttypids []uint32 -} - -// LoadTypes performs a single (complex) query, returning all the required -// information to register the named types, as well as any other types directly -// or indirectly required to complete the registration. -// The result of this call can be passed into RegisterTypes to complete the process. -func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Type, error) { - m := c.TypeMap() - if typeNames == nil || len(typeNames) == 0 { - return nil, fmt.Errorf("No type names were supplied.") - } - - // Disregard server version errors. This will result in - // the SQL not support recent structures such as multirange - serverVersion, _ := serverVersion(c) - sql := buildLoadDerivedTypesSQL(serverVersion, typeNames) - var rows Rows - var err error - if typeNames == nil { - rows, err = c.Query(ctx, sql, QueryExecModeSimpleProtocol) - } else { - rows, err = c.Query(ctx, sql, QueryExecModeSimpleProtocol, typeNames) - } - if err != nil { - return nil, fmt.Errorf("While generating load types query: %w", err) - } - defer rows.Close() - result := make([]*pgtype.Type, 0, 100) - for rows.Next() { - ti := derivedTypeInfo{} - err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids) - if err != nil { - return nil, fmt.Errorf("While scanning type information: %w", err) - } - var type_ *pgtype.Type - switch ti.Typtype { - case "b": // array - dt, ok := m.TypeForOID(ti.Typelem) - if !ok { - return nil, fmt.Errorf("Array element OID %v not registered while loading pgtype %q", ti.Typelem, ti.TypeName) - } - type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt}} - case "c": // composite - var fields []pgtype.CompositeCodecField - for i, fieldName := range ti.Attnames { - dt, ok := m.TypeForOID(ti.Atttypids[i]) - if !ok { - return nil, fmt.Errorf("Unknown field for composite type %q: field %q (OID %v) is not already registered.", ti.TypeName, fieldName, ti.Atttypids[i]) - } - fields = append(fields, pgtype.CompositeCodecField{Name: fieldName, Type: dt}) - } - - type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.CompositeCodec{Fields: fields}} - case "d": // domain - dt, ok := m.TypeForOID(ti.Typbasetype) - if !ok { - return nil, fmt.Errorf("Domain base type OID %v was not already registered, needed for %q", ti.Typbasetype, ti.TypeName) - } - - type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: dt.Codec} - case "e": // enum - type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.EnumCodec{}} - case "r": // range - dt, ok := m.TypeForOID(ti.Rngsubtype) - if !ok { - return nil, fmt.Errorf("Range element OID %v was not already registered, needed for %q", ti.Rngsubtype, ti.TypeName) - } - - type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.RangeCodec{ElementType: dt}} - case "m": // multirange - dt, ok := m.TypeForOID(ti.Rngtypid) - if !ok { - return nil, fmt.Errorf("Multirange element OID %v was not already registered, needed for %q", ti.Rngtypid, ti.TypeName) - } - - type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.MultirangeCodec{ElementType: dt}} - default: - return nil, fmt.Errorf("Unknown typtype %q was found while registering %q", ti.Typtype, ti.TypeName) - } - if type_ != nil { - m.RegisterType(type_) - if ti.NspName != "" { - nspType := &pgtype.Type{Name: ti.NspName + "." + type_.Name, OID: type_.OID, Codec: type_.Codec} - m.RegisterType(nspType) - result = append(result, nspType) - } - result = append(result, type_) - } - } - return result, nil -} - -// serverVersion returns the postgresql server version. -func serverVersion(c *Conn) (int64, error) { - serverVersionStr := c.PgConn().ParameterStatus("server_version") - serverVersionStr = regexp.MustCompile(`^[0-9]+`).FindString(serverVersionStr) - // if not PostgreSQL do nothing - if serverVersionStr == "" { - return 0, fmt.Errorf("Cannot identify server version in %q", serverVersionStr) - } - - version, err := strconv.ParseInt(serverVersionStr, 10, 64) - if err != nil { - return 0, fmt.Errorf("postgres version parsing failed: %w", err) - } - return version, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/doc.go b/vendor/github.com/jackc/pgx/v5/doc.go deleted file mode 100644 index 0e91d64e8..000000000 --- a/vendor/github.com/jackc/pgx/v5/doc.go +++ /dev/null @@ -1,194 +0,0 @@ -// Package pgx is a PostgreSQL database driver. -/* -pgx provides a native PostgreSQL driver and can act as a database/sql driver. The native PostgreSQL interface is similar -to the database/sql interface while providing better speed and access to PostgreSQL specific features. Use -github.com/jackc/pgx/v5/stdlib to use pgx as a database/sql compatible driver. See that package's documentation for -details. - -Establishing a Connection - -The primary way of establishing a connection is with [pgx.Connect]: - - conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) - -The database connection string can be in URL or key/value format. Both PostgreSQL settings and pgx settings can be -specified here. In addition, a config struct can be created by [ParseConfig] and modified before establishing the -connection with [ConnectConfig] to configure settings such as tracing that cannot be configured with a connection -string. - -Connection Pool - -[*pgx.Conn] represents a single connection to the database and is not concurrency safe. Use package -github.com/jackc/pgx/v5/pgxpool for a concurrency safe connection pool. - -Query Interface - -pgx implements Query in the familiar database/sql style. However, pgx provides generic functions such as CollectRows and -ForEachRow that are a simpler and safer way of processing rows than manually calling defer rows.Close(), rows.Next(), -rows.Scan, and rows.Err(). - -CollectRows can be used collect all returned rows into a slice. - - rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 5) - numbers, err := pgx.CollectRows(rows, pgx.RowTo[int32]) - if err != nil { - return err - } - // numbers => [1 2 3 4 5] - -ForEachRow can be used to execute a callback function for every row. This is often easier than iterating over rows -directly. - - var sum, n int32 - rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 10) - _, err := pgx.ForEachRow(rows, []any{&n}, func() error { - sum += n - return nil - }) - if err != nil { - return err - } - -pgx also implements QueryRow in the same style as database/sql. - - var name string - var weight int64 - err := conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight) - if err != nil { - return err - } - -Use Exec to execute a query that does not return a result set. - - commandTag, err := conn.Exec(context.Background(), "delete from widgets where id=$1", 42) - if err != nil { - return err - } - if commandTag.RowsAffected() != 1 { - return errors.New("No row found to delete") - } - -PostgreSQL Data Types - -pgx uses the pgtype package to converting Go values to and from PostgreSQL values. It supports many PostgreSQL types -directly and is customizable and extendable. User defined data types such as enums, domains, and composite types may -require type registration. See that package's documentation for details. - -Transactions - -Transactions are started by calling Begin. - - tx, err := conn.Begin(context.Background()) - if err != nil { - return err - } - // Rollback is safe to call even if the tx is already closed, so if - // the tx commits successfully, this is a no-op - defer tx.Rollback(context.Background()) - - _, err = tx.Exec(context.Background(), "insert into foo(id) values (1)") - if err != nil { - return err - } - - err = tx.Commit(context.Background()) - if err != nil { - return err - } - -The Tx returned from Begin also implements the Begin method. This can be used to implement pseudo nested transactions. -These are internally implemented with savepoints. - -Use BeginTx to control the transaction mode. BeginTx also can be used to ensure a new transaction is created instead of -a pseudo nested transaction. - -BeginFunc and BeginTxFunc are functions that begin a transaction, execute a function, and commit or rollback the -transaction depending on the return value of the function. These can be simpler and less error prone to use. - - err = pgx.BeginFunc(context.Background(), conn, func(tx pgx.Tx) error { - _, err := tx.Exec(context.Background(), "insert into foo(id) values (1)") - return err - }) - if err != nil { - return err - } - -Prepared Statements - -Prepared statements can be manually created with the Prepare method. However, this is rarely necessary because pgx -includes an automatic statement cache by default. Queries run through the normal Query, QueryRow, and Exec functions are -automatically prepared on first execution and the prepared statement is reused on subsequent executions. See ParseConfig -for information on how to customize or disable the statement cache. - -Copy Protocol - -Use CopyFrom to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. CopyFrom accepts a -CopyFromSource interface. If the data is already in a [][]any use CopyFromRows to wrap it in a CopyFromSource interface. -Or implement CopyFromSource to avoid buffering the entire data set in memory. - - rows := [][]any{ - {"John", "Smith", int32(36)}, - {"Jane", "Doe", int32(29)}, - } - - copyCount, err := conn.CopyFrom( - context.Background(), - pgx.Identifier{"people"}, - []string{"first_name", "last_name", "age"}, - pgx.CopyFromRows(rows), - ) - -When you already have a typed array using CopyFromSlice can be more convenient. - - rows := []User{ - {"John", "Smith", 36}, - {"Jane", "Doe", 29}, - } - - copyCount, err := conn.CopyFrom( - context.Background(), - pgx.Identifier{"people"}, - []string{"first_name", "last_name", "age"}, - pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) { - return []any{rows[i].FirstName, rows[i].LastName, rows[i].Age}, nil - }), - ) - -CopyFrom can be faster than an insert with as few as 5 rows. - -Listen and Notify - -pgx can listen to the PostgreSQL notification system with the `Conn.WaitForNotification` method. It blocks until a -notification is received or the context is canceled. - - _, err := conn.Exec(context.Background(), "listen channelname") - if err != nil { - return err - } - - notification, err := conn.WaitForNotification(context.Background()) - if err != nil { - return err - } - // do something with notification - - -Tracing and Logging - -pgx supports tracing by setting ConnConfig.Tracer. To combine several tracers you can use the multitracer.Tracer. - -In addition, the tracelog package provides the TraceLog type which lets a traditional logger act as a Tracer. - -For debug tracing of the actual PostgreSQL wire protocol messages see github.com/jackc/pgx/v5/pgproto3. - -Lower Level PostgreSQL Functionality - -github.com/jackc/pgx/v5/pgconn contains a lower level PostgreSQL driver roughly at the level of libpq. pgx.Conn in -implemented on top of pgconn. The Conn.PgConn() method can be used to access this lower layer. - -PgBouncer - -By default pgx automatically uses prepared statements. Prepared statements are incompatible with PgBouncer. This can be -disabled by setting a different QueryExecMode in ConnConfig.DefaultQueryExecMode. -*/ -package pgx diff --git a/vendor/github.com/jackc/pgx/v5/extended_query_builder.go b/vendor/github.com/jackc/pgx/v5/extended_query_builder.go deleted file mode 100644 index 526b0e953..000000000 --- a/vendor/github.com/jackc/pgx/v5/extended_query_builder.go +++ /dev/null @@ -1,146 +0,0 @@ -package pgx - -import ( - "fmt" - - "github.com/jackc/pgx/v5/pgconn" - "github.com/jackc/pgx/v5/pgtype" -) - -// ExtendedQueryBuilder is used to choose the parameter formats, to format the parameters and to choose the result -// formats for an extended query. -type ExtendedQueryBuilder struct { - ParamValues [][]byte - paramValueBytes []byte - ParamFormats []int16 - ResultFormats []int16 -} - -// Build sets ParamValues, ParamFormats, and ResultFormats for use with *PgConn.ExecParams or *PgConn.ExecPrepared. If -// sd is nil then QueryExecModeExec behavior will be used. -func (eqb *ExtendedQueryBuilder) Build(m *pgtype.Map, sd *pgconn.StatementDescription, args []any) error { - eqb.reset() - - if sd == nil { - for i := range args { - err := eqb.appendParam(m, 0, pgtype.TextFormatCode, args[i]) - if err != nil { - err = fmt.Errorf("failed to encode args[%d]: %w", i, err) - return err - } - } - return nil - } - - if len(sd.ParamOIDs) != len(args) { - return fmt.Errorf("mismatched param and argument count") - } - - for i := range args { - err := eqb.appendParam(m, sd.ParamOIDs[i], -1, args[i]) - if err != nil { - err = fmt.Errorf("failed to encode args[%d]: %w", i, err) - return err - } - } - - for i := range sd.Fields { - eqb.appendResultFormat(m.FormatCodeForOID(sd.Fields[i].DataTypeOID)) - } - - return nil -} - -// appendParam appends a parameter to the query. format may be -1 to automatically choose the format. If arg is nil it -// must be an untyped nil. -func (eqb *ExtendedQueryBuilder) appendParam(m *pgtype.Map, oid uint32, format int16, arg any) error { - if format == -1 { - preferredFormat := eqb.chooseParameterFormatCode(m, oid, arg) - preferredErr := eqb.appendParam(m, oid, preferredFormat, arg) - if preferredErr == nil { - return nil - } - - var otherFormat int16 - if preferredFormat == TextFormatCode { - otherFormat = BinaryFormatCode - } else { - otherFormat = TextFormatCode - } - - otherErr := eqb.appendParam(m, oid, otherFormat, arg) - if otherErr == nil { - return nil - } - - return preferredErr // return the error from the preferred format - } - - v, err := eqb.encodeExtendedParamValue(m, oid, format, arg) - if err != nil { - return err - } - - eqb.ParamFormats = append(eqb.ParamFormats, format) - eqb.ParamValues = append(eqb.ParamValues, v) - - return nil -} - -// appendResultFormat appends a result format to the query. -func (eqb *ExtendedQueryBuilder) appendResultFormat(format int16) { - eqb.ResultFormats = append(eqb.ResultFormats, format) -} - -// reset readies eqb to build another query. -func (eqb *ExtendedQueryBuilder) reset() { - eqb.ParamValues = eqb.ParamValues[0:0] - eqb.paramValueBytes = eqb.paramValueBytes[0:0] - eqb.ParamFormats = eqb.ParamFormats[0:0] - eqb.ResultFormats = eqb.ResultFormats[0:0] - - if cap(eqb.ParamValues) > 64 { - eqb.ParamValues = make([][]byte, 0, 64) - } - - if cap(eqb.paramValueBytes) > 256 { - eqb.paramValueBytes = make([]byte, 0, 256) - } - - if cap(eqb.ParamFormats) > 64 { - eqb.ParamFormats = make([]int16, 0, 64) - } - if cap(eqb.ResultFormats) > 64 { - eqb.ResultFormats = make([]int16, 0, 64) - } -} - -func (eqb *ExtendedQueryBuilder) encodeExtendedParamValue(m *pgtype.Map, oid uint32, formatCode int16, arg any) ([]byte, error) { - if eqb.paramValueBytes == nil { - eqb.paramValueBytes = make([]byte, 0, 128) - } - - pos := len(eqb.paramValueBytes) - - buf, err := m.Encode(oid, formatCode, arg, eqb.paramValueBytes) - if err != nil { - return nil, err - } - if buf == nil { - return nil, nil - } - eqb.paramValueBytes = buf - return eqb.paramValueBytes[pos:], nil -} - -// chooseParameterFormatCode determines the correct format code for an -// argument to a prepared statement. It defaults to TextFormatCode if no -// determination can be made. -func (eqb *ExtendedQueryBuilder) chooseParameterFormatCode(m *pgtype.Map, oid uint32, arg any) int16 { - switch arg.(type) { - case string, *string: - return TextFormatCode - } - - return m.FormatCodeForOID(oid) -} diff --git a/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go b/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go deleted file mode 100644 index 89e0c2273..000000000 --- a/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go +++ /dev/null @@ -1,70 +0,0 @@ -// Package iobufpool implements a global segregated-fit pool of buffers for IO. -// -// It uses *[]byte instead of []byte to avoid the sync.Pool allocation with Put. Unfortunately, using a pointer to avoid -// an allocation is purposely not documented. https://github.com/golang/go/issues/16323 -package iobufpool - -import "sync" - -const minPoolExpOf2 = 8 - -var pools [18]*sync.Pool - -func init() { - for i := range pools { - bufLen := 1 << (minPoolExpOf2 + i) - pools[i] = &sync.Pool{ - New: func() any { - buf := make([]byte, bufLen) - return &buf - }, - } - } -} - -// Get gets a []byte of len size with cap <= size*2. -func Get(size int) *[]byte { - i := getPoolIdx(size) - if i >= len(pools) { - buf := make([]byte, size) - return &buf - } - - ptrBuf := (pools[i].Get().(*[]byte)) - *ptrBuf = (*ptrBuf)[:size] - - return ptrBuf -} - -func getPoolIdx(size int) int { - size-- - size >>= minPoolExpOf2 - i := 0 - for size > 0 { - size >>= 1 - i++ - } - - return i -} - -// Put returns buf to the pool. -func Put(buf *[]byte) { - i := putPoolIdx(cap(*buf)) - if i < 0 { - return - } - - pools[i].Put(buf) -} - -func putPoolIdx(size int) int { - minPoolSize := 1 << minPoolExpOf2 - for i := range pools { - if size == minPoolSize< 0") - } - - if argIdx >= len(args) { - return "", fmt.Errorf("insufficient arguments") - } - arg := args[argIdx] - switch arg := arg.(type) { - case nil: - str = "null" - case int64: - str = strconv.FormatInt(arg, 10) - case float64: - str = strconv.FormatFloat(arg, 'f', -1, 64) - case bool: - str = strconv.FormatBool(arg) - case []byte: - str = QuoteBytes(arg) - case string: - str = QuoteString(arg) - case time.Time: - str = arg.Truncate(time.Microsecond).Format("'2006-01-02 15:04:05.999999999Z07:00:00'") - default: - return "", fmt.Errorf("invalid arg type: %T", arg) - } - argUse[argIdx] = true - - // Prevent SQL injection via Line Comment Creation - // https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p - str = " " + str + " " - default: - return "", fmt.Errorf("invalid Part type: %T", part) - } - buf.WriteString(str) - } - - for i, used := range argUse { - if !used { - return "", fmt.Errorf("unused argument: %d", i) - } - } - return buf.String(), nil -} - -func NewQuery(sql string) (*Query, error) { - l := &sqlLexer{ - src: sql, - stateFn: rawState, - } - - for l.stateFn != nil { - l.stateFn = l.stateFn(l) - } - - query := &Query{Parts: l.parts} - - return query, nil -} - -func QuoteString(str string) string { - return "'" + strings.ReplaceAll(str, "'", "''") + "'" -} - -func QuoteBytes(buf []byte) string { - return `'\x` + hex.EncodeToString(buf) + "'" -} - -type sqlLexer struct { - src string - start int - pos int - nested int // multiline comment nesting level. - stateFn stateFn - parts []Part -} - -type stateFn func(*sqlLexer) stateFn - -func rawState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case 'e', 'E': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune == '\'' { - l.pos += width - return escapeStringState - } - case '\'': - return singleQuoteState - case '"': - return doubleQuoteState - case '$': - nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:]) - if '0' <= nextRune && nextRune <= '9' { - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos-width]) - } - l.start = l.pos - return placeholderState - } - case '-': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune == '-' { - l.pos += width - return oneLineCommentState - } - case '/': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune == '*' { - l.pos += width - return multilineCommentState - } - case utf8.RuneError: - if width != replacementcharacterwidth { - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } - } -} - -func singleQuoteState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '\'': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune != '\'' { - return rawState - } - l.pos += width - case utf8.RuneError: - if width != replacementcharacterwidth { - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } - } -} - -func doubleQuoteState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '"': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune != '"' { - return rawState - } - l.pos += width - case utf8.RuneError: - if width != replacementcharacterwidth { - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } - } -} - -// placeholderState consumes a placeholder value. The $ must have already has -// already been consumed. The first rune must be a digit. -func placeholderState(l *sqlLexer) stateFn { - num := 0 - - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - if '0' <= r && r <= '9' { - num *= 10 - num += int(r - '0') - } else { - l.parts = append(l.parts, num) - l.pos -= width - l.start = l.pos - return rawState - } - } -} - -func escapeStringState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '\\': - _, width = utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - case '\'': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune != '\'' { - return rawState - } - l.pos += width - case utf8.RuneError: - if width != replacementcharacterwidth { - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } - } -} - -func oneLineCommentState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '\\': - _, width = utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - case '\n', '\r': - return rawState - case utf8.RuneError: - if width != replacementcharacterwidth { - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } - } -} - -func multilineCommentState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '/': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune == '*' { - l.pos += width - l.nested++ - } - case '*': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune != '/' { - continue - } - - l.pos += width - if l.nested == 0 { - return rawState - } - l.nested-- - - case utf8.RuneError: - if width != replacementcharacterwidth { - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } - } -} - -// SanitizeSQL replaces placeholder values with args. It quotes and escapes args -// as necessary. This function is only safe when standard_conforming_strings is -// on. -func SanitizeSQL(sql string, args ...any) (string, error) { - query, err := NewQuery(sql) - if err != nil { - return "", err - } - return query.Sanitize(args...) -} diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go deleted file mode 100644 index dec83f47b..000000000 --- a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go +++ /dev/null @@ -1,112 +0,0 @@ -package stmtcache - -import ( - "container/list" - - "github.com/jackc/pgx/v5/pgconn" -) - -// LRUCache implements Cache with a Least Recently Used (LRU) cache. -type LRUCache struct { - cap int - m map[string]*list.Element - l *list.List - invalidStmts []*pgconn.StatementDescription -} - -// NewLRUCache creates a new LRUCache. cap is the maximum size of the cache. -func NewLRUCache(cap int) *LRUCache { - return &LRUCache{ - cap: cap, - m: make(map[string]*list.Element), - l: list.New(), - } -} - -// Get returns the statement description for sql. Returns nil if not found. -func (c *LRUCache) Get(key string) *pgconn.StatementDescription { - if el, ok := c.m[key]; ok { - c.l.MoveToFront(el) - return el.Value.(*pgconn.StatementDescription) - } - - return nil - -} - -// Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache or -// sd.SQL has been invalidated and HandleInvalidated has not been called yet. -func (c *LRUCache) Put(sd *pgconn.StatementDescription) { - if sd.SQL == "" { - panic("cannot store statement description with empty SQL") - } - - if _, present := c.m[sd.SQL]; present { - return - } - - // The statement may have been invalidated but not yet handled. Do not readd it to the cache. - for _, invalidSD := range c.invalidStmts { - if invalidSD.SQL == sd.SQL { - return - } - } - - if c.l.Len() == c.cap { - c.invalidateOldest() - } - - el := c.l.PushFront(sd) - c.m[sd.SQL] = el -} - -// Invalidate invalidates statement description identified by sql. Does nothing if not found. -func (c *LRUCache) Invalidate(sql string) { - if el, ok := c.m[sql]; ok { - delete(c.m, sql) - c.invalidStmts = append(c.invalidStmts, el.Value.(*pgconn.StatementDescription)) - c.l.Remove(el) - } -} - -// InvalidateAll invalidates all statement descriptions. -func (c *LRUCache) InvalidateAll() { - el := c.l.Front() - for el != nil { - c.invalidStmts = append(c.invalidStmts, el.Value.(*pgconn.StatementDescription)) - el = el.Next() - } - - c.m = make(map[string]*list.Element) - c.l = list.New() -} - -// GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. -func (c *LRUCache) GetInvalidated() []*pgconn.StatementDescription { - return c.invalidStmts -} - -// RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a -// call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were -// never seen by the call to GetInvalidated. -func (c *LRUCache) RemoveInvalidated() { - c.invalidStmts = nil -} - -// Len returns the number of cached prepared statement descriptions. -func (c *LRUCache) Len() int { - return c.l.Len() -} - -// Cap returns the maximum number of cached prepared statement descriptions. -func (c *LRUCache) Cap() int { - return c.cap -} - -func (c *LRUCache) invalidateOldest() { - oldest := c.l.Back() - sd := oldest.Value.(*pgconn.StatementDescription) - c.invalidStmts = append(c.invalidStmts, sd) - delete(c.m, sd.SQL) - c.l.Remove(oldest) -} diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go deleted file mode 100644 index d57bdd29e..000000000 --- a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package stmtcache is a cache for statement descriptions. -package stmtcache - -import ( - "crypto/sha256" - "encoding/hex" - - "github.com/jackc/pgx/v5/pgconn" -) - -// StatementName returns a statement name that will be stable for sql across multiple connections and program -// executions. -func StatementName(sql string) string { - digest := sha256.Sum256([]byte(sql)) - return "stmtcache_" + hex.EncodeToString(digest[0:24]) -} - -// Cache caches statement descriptions. -type Cache interface { - // Get returns the statement description for sql. Returns nil if not found. - Get(sql string) *pgconn.StatementDescription - - // Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache. - Put(sd *pgconn.StatementDescription) - - // Invalidate invalidates statement description identified by sql. Does nothing if not found. - Invalidate(sql string) - - // InvalidateAll invalidates all statement descriptions. - InvalidateAll() - - // GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. - GetInvalidated() []*pgconn.StatementDescription - - // RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a - // call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were - // never seen by the call to GetInvalidated. - RemoveInvalidated() - - // Len returns the number of cached prepared statement descriptions. - Len() int - - // Cap returns the maximum number of cached prepared statement descriptions. - Cap() int -} diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/unlimited_cache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/unlimited_cache.go deleted file mode 100644 index 696413291..000000000 --- a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/unlimited_cache.go +++ /dev/null @@ -1,77 +0,0 @@ -package stmtcache - -import ( - "math" - - "github.com/jackc/pgx/v5/pgconn" -) - -// UnlimitedCache implements Cache with no capacity limit. -type UnlimitedCache struct { - m map[string]*pgconn.StatementDescription - invalidStmts []*pgconn.StatementDescription -} - -// NewUnlimitedCache creates a new UnlimitedCache. -func NewUnlimitedCache() *UnlimitedCache { - return &UnlimitedCache{ - m: make(map[string]*pgconn.StatementDescription), - } -} - -// Get returns the statement description for sql. Returns nil if not found. -func (c *UnlimitedCache) Get(sql string) *pgconn.StatementDescription { - return c.m[sql] -} - -// Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache. -func (c *UnlimitedCache) Put(sd *pgconn.StatementDescription) { - if sd.SQL == "" { - panic("cannot store statement description with empty SQL") - } - - if _, present := c.m[sd.SQL]; present { - return - } - - c.m[sd.SQL] = sd -} - -// Invalidate invalidates statement description identified by sql. Does nothing if not found. -func (c *UnlimitedCache) Invalidate(sql string) { - if sd, ok := c.m[sql]; ok { - delete(c.m, sql) - c.invalidStmts = append(c.invalidStmts, sd) - } -} - -// InvalidateAll invalidates all statement descriptions. -func (c *UnlimitedCache) InvalidateAll() { - for _, sd := range c.m { - c.invalidStmts = append(c.invalidStmts, sd) - } - - c.m = make(map[string]*pgconn.StatementDescription) -} - -// GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. -func (c *UnlimitedCache) GetInvalidated() []*pgconn.StatementDescription { - return c.invalidStmts -} - -// RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a -// call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were -// never seen by the call to GetInvalidated. -func (c *UnlimitedCache) RemoveInvalidated() { - c.invalidStmts = nil -} - -// Len returns the number of cached prepared statement descriptions. -func (c *UnlimitedCache) Len() int { - return len(c.m) -} - -// Cap returns the maximum number of cached prepared statement descriptions. -func (c *UnlimitedCache) Cap() int { - return math.MaxInt -} diff --git a/vendor/github.com/jackc/pgx/v5/large_objects.go b/vendor/github.com/jackc/pgx/v5/large_objects.go deleted file mode 100644 index 9d21afdce..000000000 --- a/vendor/github.com/jackc/pgx/v5/large_objects.go +++ /dev/null @@ -1,161 +0,0 @@ -package pgx - -import ( - "context" - "errors" - "io" - - "github.com/jackc/pgx/v5/pgtype" -) - -// The PostgreSQL wire protocol has a limit of 1 GB - 1 per message. See definition of -// PQ_LARGE_MESSAGE_LIMIT in the PostgreSQL source code. To allow for the other data -// in the message,maxLargeObjectMessageLength should be no larger than 1 GB - 1 KB. -var maxLargeObjectMessageLength = 1024*1024*1024 - 1024 - -// LargeObjects is a structure used to access the large objects API. It is only valid within the transaction where it -// was created. -// -// For more details see: http://www.postgresql.org/docs/current/static/largeobjects.html -type LargeObjects struct { - tx Tx -} - -type LargeObjectMode int32 - -const ( - LargeObjectModeWrite LargeObjectMode = 0x20000 - LargeObjectModeRead LargeObjectMode = 0x40000 -) - -// Create creates a new large object. If oid is zero, the server assigns an unused OID. -func (o *LargeObjects) Create(ctx context.Context, oid uint32) (uint32, error) { - err := o.tx.QueryRow(ctx, "select lo_create($1)", oid).Scan(&oid) - return oid, err -} - -// Open opens an existing large object with the given mode. ctx will also be used for all operations on the opened large -// object. -func (o *LargeObjects) Open(ctx context.Context, oid uint32, mode LargeObjectMode) (*LargeObject, error) { - var fd int32 - err := o.tx.QueryRow(ctx, "select lo_open($1, $2)", oid, mode).Scan(&fd) - if err != nil { - return nil, err - } - return &LargeObject{fd: fd, tx: o.tx, ctx: ctx}, nil -} - -// Unlink removes a large object from the database. -func (o *LargeObjects) Unlink(ctx context.Context, oid uint32) error { - var result int32 - err := o.tx.QueryRow(ctx, "select lo_unlink($1)", oid).Scan(&result) - if err != nil { - return err - } - - if result != 1 { - return errors.New("failed to remove large object") - } - - return nil -} - -// A LargeObject is a large object stored on the server. It is only valid within the transaction that it was initialized -// in. It uses the context it was initialized with for all operations. It implements these interfaces: -// -// io.Writer -// io.Reader -// io.Seeker -// io.Closer -type LargeObject struct { - ctx context.Context - tx Tx - fd int32 -} - -// Write writes p to the large object and returns the number of bytes written and an error if not all of p was written. -func (o *LargeObject) Write(p []byte) (int, error) { - nTotal := 0 - for { - expected := len(p) - nTotal - if expected == 0 { - break - } else if expected > maxLargeObjectMessageLength { - expected = maxLargeObjectMessageLength - } - - var n int - err := o.tx.QueryRow(o.ctx, "select lowrite($1, $2)", o.fd, p[nTotal:nTotal+expected]).Scan(&n) - if err != nil { - return nTotal, err - } - - if n < 0 { - return nTotal, errors.New("failed to write to large object") - } - - nTotal += n - - if n < expected { - return nTotal, errors.New("short write to large object") - } else if n > expected { - return nTotal, errors.New("invalid write to large object") - } - } - - return nTotal, nil -} - -// Read reads up to len(p) bytes into p returning the number of bytes read. -func (o *LargeObject) Read(p []byte) (int, error) { - nTotal := 0 - for { - expected := len(p) - nTotal - if expected == 0 { - break - } else if expected > maxLargeObjectMessageLength { - expected = maxLargeObjectMessageLength - } - - res := pgtype.PreallocBytes(p[nTotal:]) - err := o.tx.QueryRow(o.ctx, "select loread($1, $2)", o.fd, expected).Scan(&res) - // We compute expected so that it always fits into p, so it should never happen - // that PreallocBytes's ScanBytes had to allocate a new slice. - nTotal += len(res) - if err != nil { - return nTotal, err - } - - if len(res) < expected { - return nTotal, io.EOF - } else if len(res) > expected { - return nTotal, errors.New("invalid read of large object") - } - } - - return nTotal, nil -} - -// Seek moves the current location pointer to the new location specified by offset. -func (o *LargeObject) Seek(offset int64, whence int) (n int64, err error) { - err = o.tx.QueryRow(o.ctx, "select lo_lseek64($1, $2, $3)", o.fd, offset, whence).Scan(&n) - return n, err -} - -// Tell returns the current read or write location of the large object descriptor. -func (o *LargeObject) Tell() (n int64, err error) { - err = o.tx.QueryRow(o.ctx, "select lo_tell64($1)", o.fd).Scan(&n) - return n, err -} - -// Truncate the large object to size. -func (o *LargeObject) Truncate(size int64) (err error) { - _, err = o.tx.Exec(o.ctx, "select lo_truncate64($1, $2)", o.fd, size) - return err -} - -// Close the large object descriptor. -func (o *LargeObject) Close() error { - _, err := o.tx.Exec(o.ctx, "select lo_close($1)", o.fd) - return err -} diff --git a/vendor/github.com/jackc/pgx/v5/named_args.go b/vendor/github.com/jackc/pgx/v5/named_args.go deleted file mode 100644 index c88991ee4..000000000 --- a/vendor/github.com/jackc/pgx/v5/named_args.go +++ /dev/null @@ -1,295 +0,0 @@ -package pgx - -import ( - "context" - "fmt" - "strconv" - "strings" - "unicode/utf8" -) - -// NamedArgs can be used as the first argument to a query method. It will replace every '@' named placeholder with a '$' -// ordinal placeholder and construct the appropriate arguments. -// -// For example, the following two queries are equivalent: -// -// conn.Query(ctx, "select * from widgets where foo = @foo and bar = @bar", pgx.NamedArgs{"foo": 1, "bar": 2}) -// conn.Query(ctx, "select * from widgets where foo = $1 and bar = $2", 1, 2) -// -// Named placeholders are case sensitive and must start with a letter or underscore. Subsequent characters can be -// letters, numbers, or underscores. -type NamedArgs map[string]any - -// RewriteQuery implements the QueryRewriter interface. -func (na NamedArgs) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) { - return rewriteQuery(na, sql, false) -} - -// StrictNamedArgs can be used in the same way as NamedArgs, but provided arguments are also checked to include all -// named arguments that the sql query uses, and no extra arguments. -type StrictNamedArgs map[string]any - -// RewriteQuery implements the QueryRewriter interface. -func (sna StrictNamedArgs) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) { - return rewriteQuery(sna, sql, true) -} - -type namedArg string - -type sqlLexer struct { - src string - start int - pos int - nested int // multiline comment nesting level. - stateFn stateFn - parts []any - - nameToOrdinal map[namedArg]int -} - -type stateFn func(*sqlLexer) stateFn - -func rewriteQuery(na map[string]any, sql string, isStrict bool) (newSQL string, newArgs []any, err error) { - l := &sqlLexer{ - src: sql, - stateFn: rawState, - nameToOrdinal: make(map[namedArg]int, len(na)), - } - - for l.stateFn != nil { - l.stateFn = l.stateFn(l) - } - - sb := strings.Builder{} - for _, p := range l.parts { - switch p := p.(type) { - case string: - sb.WriteString(p) - case namedArg: - sb.WriteRune('$') - sb.WriteString(strconv.Itoa(l.nameToOrdinal[p])) - } - } - - newArgs = make([]any, len(l.nameToOrdinal)) - for name, ordinal := range l.nameToOrdinal { - var found bool - newArgs[ordinal-1], found = na[string(name)] - if isStrict && !found { - return "", nil, fmt.Errorf("argument %s found in sql query but not present in StrictNamedArgs", name) - } - } - - if isStrict { - for name := range na { - if _, found := l.nameToOrdinal[namedArg(name)]; !found { - return "", nil, fmt.Errorf("argument %s of StrictNamedArgs not found in sql query", name) - } - } - } - - return sb.String(), newArgs, nil -} - -func rawState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case 'e', 'E': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune == '\'' { - l.pos += width - return escapeStringState - } - case '\'': - return singleQuoteState - case '"': - return doubleQuoteState - case '@': - nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:]) - if isLetter(nextRune) || nextRune == '_' { - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos-width]) - } - l.start = l.pos - return namedArgState - } - case '-': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune == '-' { - l.pos += width - return oneLineCommentState - } - case '/': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune == '*' { - l.pos += width - return multilineCommentState - } - case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } -} - -func isLetter(r rune) bool { - return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') -} - -func namedArgState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - if r == utf8.RuneError { - if l.pos-l.start > 0 { - na := namedArg(l.src[l.start:l.pos]) - if _, found := l.nameToOrdinal[na]; !found { - l.nameToOrdinal[na] = len(l.nameToOrdinal) + 1 - } - l.parts = append(l.parts, na) - l.start = l.pos - } - return nil - } else if !(isLetter(r) || (r >= '0' && r <= '9') || r == '_') { - l.pos -= width - na := namedArg(l.src[l.start:l.pos]) - if _, found := l.nameToOrdinal[na]; !found { - l.nameToOrdinal[na] = len(l.nameToOrdinal) + 1 - } - l.parts = append(l.parts, namedArg(na)) - l.start = l.pos - return rawState - } - } -} - -func singleQuoteState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '\'': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune != '\'' { - return rawState - } - l.pos += width - case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } -} - -func doubleQuoteState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '"': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune != '"' { - return rawState - } - l.pos += width - case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } -} - -func escapeStringState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '\\': - _, width = utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - case '\'': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune != '\'' { - return rawState - } - l.pos += width - case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } -} - -func oneLineCommentState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '\\': - _, width = utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - case '\n', '\r': - return rawState - case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } -} - -func multilineCommentState(l *sqlLexer) stateFn { - for { - r, width := utf8.DecodeRuneInString(l.src[l.pos:]) - l.pos += width - - switch r { - case '/': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune == '*' { - l.pos += width - l.nested++ - } - case '*': - nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) - if nextRune != '/' { - continue - } - - l.pos += width - if l.nested == 0 { - return rawState - } - l.nested-- - - case utf8.RuneError: - if l.pos-l.start > 0 { - l.parts = append(l.parts, l.src[l.start:l.pos]) - l.start = l.pos - } - return nil - } - } -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/README.md b/vendor/github.com/jackc/pgx/v5/pgconn/README.md deleted file mode 100644 index 1fe15c268..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# pgconn - -Package pgconn is a low-level PostgreSQL database driver. It operates at nearly the same level as the C library libpq. -It is primarily intended to serve as the foundation for higher level libraries such as https://github.com/jackc/pgx. -Applications should handle normal queries with a higher level library and only use pgconn directly when required for -low-level access to PostgreSQL functionality. - -## Example Usage - -```go -pgConn, err := pgconn.Connect(context.Background(), os.Getenv("DATABASE_URL")) -if err != nil { - log.Fatalln("pgconn failed to connect:", err) -} -defer pgConn.Close(context.Background()) - -result := pgConn.ExecParams(context.Background(), "SELECT email FROM users WHERE id=$1", [][]byte{[]byte("123")}, nil, nil, nil) -for result.NextRow() { - fmt.Println("User 123 has email:", string(result.Values()[0])) -} -_, err = result.Close() -if err != nil { - log.Fatalln("failed reading result:", err) -} -``` - -## Testing - -See CONTRIBUTING.md for setup instructions. diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go b/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go deleted file mode 100644 index 064983615..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go +++ /dev/null @@ -1,272 +0,0 @@ -// SCRAM-SHA-256 authentication -// -// Resources: -// https://tools.ietf.org/html/rfc5802 -// https://tools.ietf.org/html/rfc8265 -// https://www.postgresql.org/docs/current/sasl-authentication.html -// -// Inspiration drawn from other implementations: -// https://github.com/lib/pq/pull/608 -// https://github.com/lib/pq/pull/788 -// https://github.com/lib/pq/pull/833 - -package pgconn - -import ( - "bytes" - "crypto/hmac" - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "errors" - "fmt" - "strconv" - - "github.com/jackc/pgx/v5/pgproto3" - "golang.org/x/crypto/pbkdf2" - "golang.org/x/text/secure/precis" -) - -const clientNonceLen = 18 - -// Perform SCRAM authentication. -func (c *PgConn) scramAuth(serverAuthMechanisms []string) error { - sc, err := newScramClient(serverAuthMechanisms, c.config.Password) - if err != nil { - return err - } - - // Send client-first-message in a SASLInitialResponse - saslInitialResponse := &pgproto3.SASLInitialResponse{ - AuthMechanism: "SCRAM-SHA-256", - Data: sc.clientFirstMessage(), - } - c.frontend.Send(saslInitialResponse) - err = c.flushWithPotentialWriteReadDeadlock() - if err != nil { - return err - } - - // Receive server-first-message payload in an AuthenticationSASLContinue. - saslContinue, err := c.rxSASLContinue() - if err != nil { - return err - } - err = sc.recvServerFirstMessage(saslContinue.Data) - if err != nil { - return err - } - - // Send client-final-message in a SASLResponse - saslResponse := &pgproto3.SASLResponse{ - Data: []byte(sc.clientFinalMessage()), - } - c.frontend.Send(saslResponse) - err = c.flushWithPotentialWriteReadDeadlock() - if err != nil { - return err - } - - // Receive server-final-message payload in an AuthenticationSASLFinal. - saslFinal, err := c.rxSASLFinal() - if err != nil { - return err - } - return sc.recvServerFinalMessage(saslFinal.Data) -} - -func (c *PgConn) rxSASLContinue() (*pgproto3.AuthenticationSASLContinue, error) { - msg, err := c.receiveMessage() - if err != nil { - return nil, err - } - switch m := msg.(type) { - case *pgproto3.AuthenticationSASLContinue: - return m, nil - case *pgproto3.ErrorResponse: - return nil, ErrorResponseToPgError(m) - } - - return nil, fmt.Errorf("expected AuthenticationSASLContinue message but received unexpected message %T", msg) -} - -func (c *PgConn) rxSASLFinal() (*pgproto3.AuthenticationSASLFinal, error) { - msg, err := c.receiveMessage() - if err != nil { - return nil, err - } - switch m := msg.(type) { - case *pgproto3.AuthenticationSASLFinal: - return m, nil - case *pgproto3.ErrorResponse: - return nil, ErrorResponseToPgError(m) - } - - return nil, fmt.Errorf("expected AuthenticationSASLFinal message but received unexpected message %T", msg) -} - -type scramClient struct { - serverAuthMechanisms []string - password []byte - clientNonce []byte - - clientFirstMessageBare []byte - - serverFirstMessage []byte - clientAndServerNonce []byte - salt []byte - iterations int - - saltedPassword []byte - authMessage []byte -} - -func newScramClient(serverAuthMechanisms []string, password string) (*scramClient, error) { - sc := &scramClient{ - serverAuthMechanisms: serverAuthMechanisms, - } - - // Ensure server supports SCRAM-SHA-256 - hasScramSHA256 := false - for _, mech := range sc.serverAuthMechanisms { - if mech == "SCRAM-SHA-256" { - hasScramSHA256 = true - break - } - } - if !hasScramSHA256 { - return nil, errors.New("server does not support SCRAM-SHA-256") - } - - // precis.OpaqueString is equivalent to SASLprep for password. - var err error - sc.password, err = precis.OpaqueString.Bytes([]byte(password)) - if err != nil { - // PostgreSQL allows passwords invalid according to SCRAM / SASLprep. - sc.password = []byte(password) - } - - buf := make([]byte, clientNonceLen) - _, err = rand.Read(buf) - if err != nil { - return nil, err - } - sc.clientNonce = make([]byte, base64.RawStdEncoding.EncodedLen(len(buf))) - base64.RawStdEncoding.Encode(sc.clientNonce, buf) - - return sc, nil -} - -func (sc *scramClient) clientFirstMessage() []byte { - sc.clientFirstMessageBare = []byte(fmt.Sprintf("n=,r=%s", sc.clientNonce)) - return []byte(fmt.Sprintf("n,,%s", sc.clientFirstMessageBare)) -} - -func (sc *scramClient) recvServerFirstMessage(serverFirstMessage []byte) error { - sc.serverFirstMessage = serverFirstMessage - buf := serverFirstMessage - if !bytes.HasPrefix(buf, []byte("r=")) { - return errors.New("invalid SCRAM server-first-message received from server: did not include r=") - } - buf = buf[2:] - - idx := bytes.IndexByte(buf, ',') - if idx == -1 { - return errors.New("invalid SCRAM server-first-message received from server: did not include s=") - } - sc.clientAndServerNonce = buf[:idx] - buf = buf[idx+1:] - - if !bytes.HasPrefix(buf, []byte("s=")) { - return errors.New("invalid SCRAM server-first-message received from server: did not include s=") - } - buf = buf[2:] - - idx = bytes.IndexByte(buf, ',') - if idx == -1 { - return errors.New("invalid SCRAM server-first-message received from server: did not include i=") - } - saltStr := buf[:idx] - buf = buf[idx+1:] - - if !bytes.HasPrefix(buf, []byte("i=")) { - return errors.New("invalid SCRAM server-first-message received from server: did not include i=") - } - buf = buf[2:] - iterationsStr := buf - - var err error - sc.salt, err = base64.StdEncoding.DecodeString(string(saltStr)) - if err != nil { - return fmt.Errorf("invalid SCRAM salt received from server: %w", err) - } - - sc.iterations, err = strconv.Atoi(string(iterationsStr)) - if err != nil || sc.iterations <= 0 { - return fmt.Errorf("invalid SCRAM iteration count received from server: %w", err) - } - - if !bytes.HasPrefix(sc.clientAndServerNonce, sc.clientNonce) { - return errors.New("invalid SCRAM nonce: did not start with client nonce") - } - - if len(sc.clientAndServerNonce) <= len(sc.clientNonce) { - return errors.New("invalid SCRAM nonce: did not include server nonce") - } - - return nil -} - -func (sc *scramClient) clientFinalMessage() string { - clientFinalMessageWithoutProof := []byte(fmt.Sprintf("c=biws,r=%s", sc.clientAndServerNonce)) - - sc.saltedPassword = pbkdf2.Key([]byte(sc.password), sc.salt, sc.iterations, 32, sha256.New) - sc.authMessage = bytes.Join([][]byte{sc.clientFirstMessageBare, sc.serverFirstMessage, clientFinalMessageWithoutProof}, []byte(",")) - - clientProof := computeClientProof(sc.saltedPassword, sc.authMessage) - - return fmt.Sprintf("%s,p=%s", clientFinalMessageWithoutProof, clientProof) -} - -func (sc *scramClient) recvServerFinalMessage(serverFinalMessage []byte) error { - if !bytes.HasPrefix(serverFinalMessage, []byte("v=")) { - return errors.New("invalid SCRAM server-final-message received from server") - } - - serverSignature := serverFinalMessage[2:] - - if !hmac.Equal(serverSignature, computeServerSignature(sc.saltedPassword, sc.authMessage)) { - return errors.New("invalid SCRAM ServerSignature received from server") - } - - return nil -} - -func computeHMAC(key, msg []byte) []byte { - mac := hmac.New(sha256.New, key) - mac.Write(msg) - return mac.Sum(nil) -} - -func computeClientProof(saltedPassword, authMessage []byte) []byte { - clientKey := computeHMAC(saltedPassword, []byte("Client Key")) - storedKey := sha256.Sum256(clientKey) - clientSignature := computeHMAC(storedKey[:], authMessage) - - clientProof := make([]byte, len(clientSignature)) - for i := 0; i < len(clientSignature); i++ { - clientProof[i] = clientKey[i] ^ clientSignature[i] - } - - buf := make([]byte, base64.StdEncoding.EncodedLen(len(clientProof))) - base64.StdEncoding.Encode(buf, clientProof) - return buf -} - -func computeServerSignature(saltedPassword []byte, authMessage []byte) []byte { - serverKey := computeHMAC(saltedPassword, []byte("Server Key")) - serverSignature := computeHMAC(serverKey, authMessage) - buf := make([]byte, base64.StdEncoding.EncodedLen(len(serverSignature))) - base64.StdEncoding.Encode(buf, serverSignature) - return buf -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/config.go b/vendor/github.com/jackc/pgx/v5/pgconn/config.go deleted file mode 100644 index 46b39f14e..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/config.go +++ /dev/null @@ -1,934 +0,0 @@ -package pgconn - -import ( - "context" - "crypto/tls" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "io" - "math" - "net" - "net/url" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/jackc/pgpassfile" - "github.com/jackc/pgservicefile" - "github.com/jackc/pgx/v5/pgconn/ctxwatch" - "github.com/jackc/pgx/v5/pgproto3" -) - -type AfterConnectFunc func(ctx context.Context, pgconn *PgConn) error -type ValidateConnectFunc func(ctx context.Context, pgconn *PgConn) error -type GetSSLPasswordFunc func(ctx context.Context) string - -// Config is the settings used to establish a connection to a PostgreSQL server. It must be created by [ParseConfig]. A -// manually initialized Config will cause ConnectConfig to panic. -type Config struct { - Host string // host (e.g. localhost) or absolute path to unix domain socket directory (e.g. /private/tmp) - Port uint16 - Database string - User string - Password string - TLSConfig *tls.Config // nil disables TLS - ConnectTimeout time.Duration - DialFunc DialFunc // e.g. net.Dialer.DialContext - LookupFunc LookupFunc // e.g. net.Resolver.LookupHost - BuildFrontend BuildFrontendFunc - - // BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called - // when a context passed to a PgConn method is canceled. - BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler - - RuntimeParams map[string]string // Run-time parameters to set on connection as session default values (e.g. search_path or application_name) - - KerberosSrvName string - KerberosSpn string - Fallbacks []*FallbackConfig - - // ValidateConnect is called during a connection attempt after a successful authentication with the PostgreSQL server. - // It can be used to validate that the server is acceptable. If this returns an error the connection is closed and the next - // fallback config is tried. This allows implementing high availability behavior such as libpq does with target_session_attrs. - ValidateConnect ValidateConnectFunc - - // AfterConnect is called after ValidateConnect. It can be used to set up the connection (e.g. Set session variables - // or prepare statements). If this returns an error the connection attempt fails. - AfterConnect AfterConnectFunc - - // OnNotice is a callback function called when a notice response is received. - OnNotice NoticeHandler - - // OnNotification is a callback function called when a notification from the LISTEN/NOTIFY system is received. - OnNotification NotificationHandler - - // OnPgError is a callback function called when a Postgres error is received by the server. The default handler will close - // the connection on any FATAL errors. If you override this handler you should call the previously set handler or ensure - // that you close on FATAL errors by returning false. - OnPgError PgErrorHandler - - createdByParseConfig bool // Used to enforce created by ParseConfig rule. -} - -// ParseConfigOptions contains options that control how a config is built such as GetSSLPassword. -type ParseConfigOptions struct { - // GetSSLPassword gets the password to decrypt a SSL client certificate. This is analogous to the libpq function - // PQsetSSLKeyPassHook_OpenSSL. - GetSSLPassword GetSSLPasswordFunc -} - -// Copy returns a deep copy of the config that is safe to use and modify. -// The only exception is the TLSConfig field: -// according to the tls.Config docs it must not be modified after creation. -func (c *Config) Copy() *Config { - newConf := new(Config) - *newConf = *c - if newConf.TLSConfig != nil { - newConf.TLSConfig = c.TLSConfig.Clone() - } - if newConf.RuntimeParams != nil { - newConf.RuntimeParams = make(map[string]string, len(c.RuntimeParams)) - for k, v := range c.RuntimeParams { - newConf.RuntimeParams[k] = v - } - } - if newConf.Fallbacks != nil { - newConf.Fallbacks = make([]*FallbackConfig, len(c.Fallbacks)) - for i, fallback := range c.Fallbacks { - newFallback := new(FallbackConfig) - *newFallback = *fallback - if newFallback.TLSConfig != nil { - newFallback.TLSConfig = fallback.TLSConfig.Clone() - } - newConf.Fallbacks[i] = newFallback - } - } - return newConf -} - -// FallbackConfig is additional settings to attempt a connection with when the primary Config fails to establish a -// network connection. It is used for TLS fallback such as sslmode=prefer and high availability (HA) connections. -type FallbackConfig struct { - Host string // host (e.g. localhost) or path to unix domain socket directory (e.g. /private/tmp) - Port uint16 - TLSConfig *tls.Config // nil disables TLS -} - -// connectOneConfig is the configuration for a single attempt to connect to a single host. -type connectOneConfig struct { - network string - address string - originalHostname string // original hostname before resolving - tlsConfig *tls.Config // nil disables TLS -} - -// isAbsolutePath checks if the provided value is an absolute path either -// beginning with a forward slash (as on Linux-based systems) or with a capital -// letter A-Z followed by a colon and a backslash, e.g., "C:\", (as on Windows). -func isAbsolutePath(path string) bool { - isWindowsPath := func(p string) bool { - if len(p) < 3 { - return false - } - drive := p[0] - colon := p[1] - backslash := p[2] - if drive >= 'A' && drive <= 'Z' && colon == ':' && backslash == '\\' { - return true - } - return false - } - return strings.HasPrefix(path, "/") || isWindowsPath(path) -} - -// NetworkAddress converts a PostgreSQL host and port into network and address suitable for use with -// net.Dial. -func NetworkAddress(host string, port uint16) (network, address string) { - if isAbsolutePath(host) { - network = "unix" - address = filepath.Join(host, ".s.PGSQL.") + strconv.FormatInt(int64(port), 10) - } else { - network = "tcp" - address = net.JoinHostPort(host, strconv.Itoa(int(port))) - } - return network, address -} - -// ParseConfig builds a *Config from connString with similar behavior to the PostgreSQL standard C library libpq. It -// uses the same defaults as libpq (e.g. port=5432) and understands most PG* environment variables. ParseConfig closely -// matches the parsing behavior of libpq. connString may either be in URL format or keyword = value format. See -// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING for details. connString also may be empty -// to only read from the environment. If a password is not supplied it will attempt to read the .pgpass file. -// -// # Example Keyword/Value -// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca -// -// # Example URL -// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca -// -// The returned *Config may be modified. However, it is strongly recommended that any configuration that can be done -// through the connection string be done there. In particular the fields Host, Port, TLSConfig, and Fallbacks can be -// interdependent (e.g. TLSConfig needs knowledge of the host to validate the server certificate). These fields should -// not be modified individually. They should all be modified or all left unchanged. -// -// ParseConfig supports specifying multiple hosts in similar manner to libpq. Host and port may include comma separated -// values that will be tried in order. This can be used as part of a high availability system. See -// https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS for more information. -// -// # Example URL -// postgres://jack:secret@foo.example.com:5432,bar.example.com:5432/mydb -// -// ParseConfig currently recognizes the following environment variable and their parameter key word equivalents passed -// via database URL or keyword/value: -// -// PGHOST -// PGPORT -// PGDATABASE -// PGUSER -// PGPASSWORD -// PGPASSFILE -// PGSERVICE -// PGSERVICEFILE -// PGSSLMODE -// PGSSLCERT -// PGSSLKEY -// PGSSLROOTCERT -// PGSSLPASSWORD -// PGAPPNAME -// PGCONNECT_TIMEOUT -// PGTARGETSESSIONATTRS -// -// See http://www.postgresql.org/docs/11/static/libpq-envars.html for details on the meaning of environment variables. -// -// See https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-PARAMKEYWORDS for parameter key word names. They are -// usually but not always the environment variable name downcased and without the "PG" prefix. -// -// Important Security Notes: -// -// ParseConfig tries to match libpq behavior with regard to PGSSLMODE. This includes defaulting to "prefer" behavior if -// not set. -// -// See http://www.postgresql.org/docs/11/static/libpq-ssl.html#LIBPQ-SSL-PROTECTION for details on what level of -// security each sslmode provides. -// -// The sslmode "prefer" (the default), sslmode "allow", and multiple hosts are implemented via the Fallbacks field of -// the Config struct. If TLSConfig is manually changed it will not affect the fallbacks. For example, in the case of -// sslmode "prefer" this means it will first try the main Config settings which use TLS, then it will try the fallback -// which does not use TLS. This can lead to an unexpected unencrypted connection if the main TLS config is manually -// changed later but the unencrypted fallback is present. Ensure there are no stale fallbacks when manually setting -// TLSConfig. -// -// Other known differences with libpq: -// -// When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn -// does not. -// -// In addition, ParseConfig accepts the following options: -// -// - servicefile. -// libpq only reads servicefile from the PGSERVICEFILE environment variable. ParseConfig accepts servicefile as a -// part of the connection string. -func ParseConfig(connString string) (*Config, error) { - var parseConfigOptions ParseConfigOptions - return ParseConfigWithOptions(connString, parseConfigOptions) -} - -// ParseConfigWithOptions builds a *Config from connString and options with similar behavior to the PostgreSQL standard -// C library libpq. options contains settings that cannot be specified in a connString such as providing a function to -// get the SSL password. -func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error) { - defaultSettings := defaultSettings() - envSettings := parseEnvSettings() - - connStringSettings := make(map[string]string) - if connString != "" { - var err error - // connString may be a database URL or in PostgreSQL keyword/value format - if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { - connStringSettings, err = parseURLSettings(connString) - if err != nil { - return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err} - } - } else { - connStringSettings, err = parseKeywordValueSettings(connString) - if err != nil { - return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as keyword/value", err: err} - } - } - } - - settings := mergeSettings(defaultSettings, envSettings, connStringSettings) - if service, present := settings["service"]; present { - serviceSettings, err := parseServiceSettings(settings["servicefile"], service) - if err != nil { - return nil, &ParseConfigError{ConnString: connString, msg: "failed to read service", err: err} - } - - settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings) - } - - config := &Config{ - createdByParseConfig: true, - Database: settings["database"], - User: settings["user"], - Password: settings["password"], - RuntimeParams: make(map[string]string), - BuildFrontend: func(r io.Reader, w io.Writer) *pgproto3.Frontend { - return pgproto3.NewFrontend(r, w) - }, - BuildContextWatcherHandler: func(pgConn *PgConn) ctxwatch.Handler { - return &DeadlineContextWatcherHandler{Conn: pgConn.conn} - }, - OnPgError: func(_ *PgConn, pgErr *PgError) bool { - // we want to automatically close any fatal errors - if strings.EqualFold(pgErr.Severity, "FATAL") { - return false - } - return true - }, - } - - if connectTimeoutSetting, present := settings["connect_timeout"]; present { - connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting) - if err != nil { - return nil, &ParseConfigError{ConnString: connString, msg: "invalid connect_timeout", err: err} - } - config.ConnectTimeout = connectTimeout - config.DialFunc = makeConnectTimeoutDialFunc(connectTimeout) - } else { - defaultDialer := makeDefaultDialer() - config.DialFunc = defaultDialer.DialContext - } - - config.LookupFunc = makeDefaultResolver().LookupHost - - notRuntimeParams := map[string]struct{}{ - "host": {}, - "port": {}, - "database": {}, - "user": {}, - "password": {}, - "passfile": {}, - "connect_timeout": {}, - "sslmode": {}, - "sslkey": {}, - "sslcert": {}, - "sslrootcert": {}, - "sslpassword": {}, - "sslsni": {}, - "krbspn": {}, - "krbsrvname": {}, - "target_session_attrs": {}, - "service": {}, - "servicefile": {}, - } - - // Adding kerberos configuration - if _, present := settings["krbsrvname"]; present { - config.KerberosSrvName = settings["krbsrvname"] - } - if _, present := settings["krbspn"]; present { - config.KerberosSpn = settings["krbspn"] - } - - for k, v := range settings { - if _, present := notRuntimeParams[k]; present { - continue - } - config.RuntimeParams[k] = v - } - - fallbacks := []*FallbackConfig{} - - hosts := strings.Split(settings["host"], ",") - ports := strings.Split(settings["port"], ",") - - for i, host := range hosts { - var portStr string - if i < len(ports) { - portStr = ports[i] - } else { - portStr = ports[0] - } - - port, err := parsePort(portStr) - if err != nil { - return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err} - } - - var tlsConfigs []*tls.Config - - // Ignore TLS settings if Unix domain socket like libpq - if network, _ := NetworkAddress(host, port); network == "unix" { - tlsConfigs = append(tlsConfigs, nil) - } else { - var err error - tlsConfigs, err = configTLS(settings, host, options) - if err != nil { - return nil, &ParseConfigError{ConnString: connString, msg: "failed to configure TLS", err: err} - } - } - - for _, tlsConfig := range tlsConfigs { - fallbacks = append(fallbacks, &FallbackConfig{ - Host: host, - Port: port, - TLSConfig: tlsConfig, - }) - } - } - - config.Host = fallbacks[0].Host - config.Port = fallbacks[0].Port - config.TLSConfig = fallbacks[0].TLSConfig - config.Fallbacks = fallbacks[1:] - - passfile, err := pgpassfile.ReadPassfile(settings["passfile"]) - if err == nil { - if config.Password == "" { - host := config.Host - if network, _ := NetworkAddress(config.Host, config.Port); network == "unix" { - host = "localhost" - } - - config.Password = passfile.FindPassword(host, strconv.Itoa(int(config.Port)), config.Database, config.User) - } - } - - switch tsa := settings["target_session_attrs"]; tsa { - case "read-write": - config.ValidateConnect = ValidateConnectTargetSessionAttrsReadWrite - case "read-only": - config.ValidateConnect = ValidateConnectTargetSessionAttrsReadOnly - case "primary": - config.ValidateConnect = ValidateConnectTargetSessionAttrsPrimary - case "standby": - config.ValidateConnect = ValidateConnectTargetSessionAttrsStandby - case "prefer-standby": - config.ValidateConnect = ValidateConnectTargetSessionAttrsPreferStandby - case "any": - // do nothing - default: - return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("unknown target_session_attrs value: %v", tsa)} - } - - return config, nil -} - -func mergeSettings(settingSets ...map[string]string) map[string]string { - settings := make(map[string]string) - - for _, s2 := range settingSets { - for k, v := range s2 { - settings[k] = v - } - } - - return settings -} - -func parseEnvSettings() map[string]string { - settings := make(map[string]string) - - nameMap := map[string]string{ - "PGHOST": "host", - "PGPORT": "port", - "PGDATABASE": "database", - "PGUSER": "user", - "PGPASSWORD": "password", - "PGPASSFILE": "passfile", - "PGAPPNAME": "application_name", - "PGCONNECT_TIMEOUT": "connect_timeout", - "PGSSLMODE": "sslmode", - "PGSSLKEY": "sslkey", - "PGSSLCERT": "sslcert", - "PGSSLSNI": "sslsni", - "PGSSLROOTCERT": "sslrootcert", - "PGSSLPASSWORD": "sslpassword", - "PGTARGETSESSIONATTRS": "target_session_attrs", - "PGSERVICE": "service", - "PGSERVICEFILE": "servicefile", - } - - for envname, realname := range nameMap { - value := os.Getenv(envname) - if value != "" { - settings[realname] = value - } - } - - return settings -} - -func parseURLSettings(connString string) (map[string]string, error) { - settings := make(map[string]string) - - parsedURL, err := url.Parse(connString) - if err != nil { - if urlErr := new(url.Error); errors.As(err, &urlErr) { - return nil, urlErr.Err - } - return nil, err - } - - if parsedURL.User != nil { - settings["user"] = parsedURL.User.Username() - if password, present := parsedURL.User.Password(); present { - settings["password"] = password - } - } - - // Handle multiple host:port's in url.Host by splitting them into host,host,host and port,port,port. - var hosts []string - var ports []string - for _, host := range strings.Split(parsedURL.Host, ",") { - if host == "" { - continue - } - if isIPOnly(host) { - hosts = append(hosts, strings.Trim(host, "[]")) - continue - } - h, p, err := net.SplitHostPort(host) - if err != nil { - return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err) - } - if h != "" { - hosts = append(hosts, h) - } - if p != "" { - ports = append(ports, p) - } - } - if len(hosts) > 0 { - settings["host"] = strings.Join(hosts, ",") - } - if len(ports) > 0 { - settings["port"] = strings.Join(ports, ",") - } - - database := strings.TrimLeft(parsedURL.Path, "/") - if database != "" { - settings["database"] = database - } - - nameMap := map[string]string{ - "dbname": "database", - } - - for k, v := range parsedURL.Query() { - if k2, present := nameMap[k]; present { - k = k2 - } - - settings[k] = v[0] - } - - return settings, nil -} - -func isIPOnly(host string) bool { - return net.ParseIP(strings.Trim(host, "[]")) != nil || !strings.Contains(host, ":") -} - -var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} - -func parseKeywordValueSettings(s string) (map[string]string, error) { - settings := make(map[string]string) - - nameMap := map[string]string{ - "dbname": "database", - } - - for len(s) > 0 { - var key, val string - eqIdx := strings.IndexRune(s, '=') - if eqIdx < 0 { - return nil, errors.New("invalid keyword/value") - } - - key = strings.Trim(s[:eqIdx], " \t\n\r\v\f") - s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f") - if len(s) == 0 { - } else if s[0] != '\'' { - end := 0 - for ; end < len(s); end++ { - if asciiSpace[s[end]] == 1 { - break - } - if s[end] == '\\' { - end++ - if end == len(s) { - return nil, errors.New("invalid backslash") - } - } - } - val = strings.Replace(strings.Replace(s[:end], "\\\\", "\\", -1), "\\'", "'", -1) - if end == len(s) { - s = "" - } else { - s = s[end+1:] - } - } else { // quoted string - s = s[1:] - end := 0 - for ; end < len(s); end++ { - if s[end] == '\'' { - break - } - if s[end] == '\\' { - end++ - } - } - if end == len(s) { - return nil, errors.New("unterminated quoted string in connection info string") - } - val = strings.Replace(strings.Replace(s[:end], "\\\\", "\\", -1), "\\'", "'", -1) - if end == len(s) { - s = "" - } else { - s = s[end+1:] - } - } - - if k, ok := nameMap[key]; ok { - key = k - } - - if key == "" { - return nil, errors.New("invalid keyword/value") - } - - settings[key] = val - } - - return settings, nil -} - -func parseServiceSettings(servicefilePath, serviceName string) (map[string]string, error) { - servicefile, err := pgservicefile.ReadServicefile(servicefilePath) - if err != nil { - return nil, fmt.Errorf("failed to read service file: %v", servicefilePath) - } - - service, err := servicefile.GetService(serviceName) - if err != nil { - return nil, fmt.Errorf("unable to find service: %v", serviceName) - } - - nameMap := map[string]string{ - "dbname": "database", - } - - settings := make(map[string]string, len(service.Settings)) - for k, v := range service.Settings { - if k2, present := nameMap[k]; present { - k = k2 - } - settings[k] = v - } - - return settings, nil -} - -// configTLS uses libpq's TLS parameters to construct []*tls.Config. It is -// necessary to allow returning multiple TLS configs as sslmode "allow" and -// "prefer" allow fallback. -func configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error) { - host := thisHost - sslmode := settings["sslmode"] - sslrootcert := settings["sslrootcert"] - sslcert := settings["sslcert"] - sslkey := settings["sslkey"] - sslpassword := settings["sslpassword"] - sslsni := settings["sslsni"] - - // Match libpq default behavior - if sslmode == "" { - sslmode = "prefer" - } - if sslsni == "" { - sslsni = "1" - } - - tlsConfig := &tls.Config{} - - if sslrootcert != "" { - var caCertPool *x509.CertPool - - if sslrootcert == "system" { - var err error - - caCertPool, err = x509.SystemCertPool() - if err != nil { - return nil, fmt.Errorf("unable to load system certificate pool: %w", err) - } - - sslmode = "verify-full" - } else { - caCertPool = x509.NewCertPool() - - caPath := sslrootcert - caCert, err := os.ReadFile(caPath) - if err != nil { - return nil, fmt.Errorf("unable to read CA file: %w", err) - } - - if !caCertPool.AppendCertsFromPEM(caCert) { - return nil, errors.New("unable to add CA to cert pool") - } - } - - tlsConfig.RootCAs = caCertPool - tlsConfig.ClientCAs = caCertPool - } - - switch sslmode { - case "disable": - return []*tls.Config{nil}, nil - case "allow", "prefer": - tlsConfig.InsecureSkipVerify = true - case "require": - // According to PostgreSQL documentation, if a root CA file exists, - // the behavior of sslmode=require should be the same as that of verify-ca - // - // See https://www.postgresql.org/docs/12/libpq-ssl.html - if sslrootcert != "" { - goto nextCase - } - tlsConfig.InsecureSkipVerify = true - break - nextCase: - fallthrough - case "verify-ca": - // Don't perform the default certificate verification because it - // will verify the hostname. Instead, verify the server's - // certificate chain ourselves in VerifyPeerCertificate and - // ignore the server name. This emulates libpq's verify-ca - // behavior. - // - // See https://github.com/golang/go/issues/21971#issuecomment-332693931 - // and https://pkg.go.dev/crypto/tls?tab=doc#example-Config-VerifyPeerCertificate - // for more info. - tlsConfig.InsecureSkipVerify = true - tlsConfig.VerifyPeerCertificate = func(certificates [][]byte, _ [][]*x509.Certificate) error { - certs := make([]*x509.Certificate, len(certificates)) - for i, asn1Data := range certificates { - cert, err := x509.ParseCertificate(asn1Data) - if err != nil { - return errors.New("failed to parse certificate from server: " + err.Error()) - } - certs[i] = cert - } - - // Leave DNSName empty to skip hostname verification. - opts := x509.VerifyOptions{ - Roots: tlsConfig.RootCAs, - Intermediates: x509.NewCertPool(), - } - // Skip the first cert because it's the leaf. All others - // are intermediates. - for _, cert := range certs[1:] { - opts.Intermediates.AddCert(cert) - } - _, err := certs[0].Verify(opts) - return err - } - case "verify-full": - tlsConfig.ServerName = host - default: - return nil, errors.New("sslmode is invalid") - } - - if (sslcert != "" && sslkey == "") || (sslcert == "" && sslkey != "") { - return nil, errors.New(`both "sslcert" and "sslkey" are required`) - } - - if sslcert != "" && sslkey != "" { - buf, err := os.ReadFile(sslkey) - if err != nil { - return nil, fmt.Errorf("unable to read sslkey: %w", err) - } - block, _ := pem.Decode(buf) - if block == nil { - return nil, errors.New("failed to decode sslkey") - } - var pemKey []byte - var decryptedKey []byte - var decryptedError error - // If PEM is encrypted, attempt to decrypt using pass phrase - if x509.IsEncryptedPEMBlock(block) { - // Attempt decryption with pass phrase - // NOTE: only supports RSA (PKCS#1) - if sslpassword != "" { - decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) - } - //if sslpassword not provided or has decryption error when use it - //try to find sslpassword with callback function - if sslpassword == "" || decryptedError != nil { - if parseConfigOptions.GetSSLPassword != nil { - sslpassword = parseConfigOptions.GetSSLPassword(context.Background()) - } - if sslpassword == "" { - return nil, fmt.Errorf("unable to find sslpassword") - } - } - decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) - // Should we also provide warning for PKCS#1 needed? - if decryptedError != nil { - return nil, fmt.Errorf("unable to decrypt key: %w", err) - } - - pemBytes := pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: decryptedKey, - } - pemKey = pem.EncodeToMemory(&pemBytes) - } else { - pemKey = pem.EncodeToMemory(block) - } - certfile, err := os.ReadFile(sslcert) - if err != nil { - return nil, fmt.Errorf("unable to read cert: %w", err) - } - cert, err := tls.X509KeyPair(certfile, pemKey) - if err != nil { - return nil, fmt.Errorf("unable to load cert: %w", err) - } - tlsConfig.Certificates = []tls.Certificate{cert} - } - - // Set Server Name Indication (SNI), if enabled by connection parameters. - // Per RFC 6066, do not set it if the host is a literal IP address (IPv4 - // or IPv6). - if sslsni == "1" && net.ParseIP(host) == nil { - tlsConfig.ServerName = host - } - - switch sslmode { - case "allow": - return []*tls.Config{nil, tlsConfig}, nil - case "prefer": - return []*tls.Config{tlsConfig, nil}, nil - case "require", "verify-ca", "verify-full": - return []*tls.Config{tlsConfig}, nil - default: - panic("BUG: bad sslmode should already have been caught") - } -} - -func parsePort(s string) (uint16, error) { - port, err := strconv.ParseUint(s, 10, 16) - if err != nil { - return 0, err - } - if port < 1 || port > math.MaxUint16 { - return 0, errors.New("outside range") - } - return uint16(port), nil -} - -func makeDefaultDialer() *net.Dialer { - // rely on GOLANG KeepAlive settings - return &net.Dialer{} -} - -func makeDefaultResolver() *net.Resolver { - return net.DefaultResolver -} - -func parseConnectTimeoutSetting(s string) (time.Duration, error) { - timeout, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return 0, err - } - if timeout < 0 { - return 0, errors.New("negative timeout") - } - return time.Duration(timeout) * time.Second, nil -} - -func makeConnectTimeoutDialFunc(timeout time.Duration) DialFunc { - d := makeDefaultDialer() - d.Timeout = timeout - return d.DialContext -} - -// ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible -// target_session_attrs=read-write. -func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error { - result, err := pgConn.Exec(ctx, "show transaction_read_only").ReadAll() - if err != nil { - return err - } - - if string(result[0].Rows[0][0]) == "on" { - return errors.New("read only connection") - } - - return nil -} - -// ValidateConnectTargetSessionAttrsReadOnly is a ValidateConnectFunc that implements libpq compatible -// target_session_attrs=read-only. -func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgConn) error { - result, err := pgConn.Exec(ctx, "show transaction_read_only").ReadAll() - if err != nil { - return err - } - - if string(result[0].Rows[0][0]) != "on" { - return errors.New("connection is not read only") - } - - return nil -} - -// ValidateConnectTargetSessionAttrsStandby is a ValidateConnectFunc that implements libpq compatible -// target_session_attrs=standby. -func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgConn) error { - result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll() - if err != nil { - return err - } - - if string(result[0].Rows[0][0]) != "t" { - return errors.New("server is not in hot standby mode") - } - - return nil -} - -// ValidateConnectTargetSessionAttrsPrimary is a ValidateConnectFunc that implements libpq compatible -// target_session_attrs=primary. -func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgConn) error { - result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll() - if err != nil { - return err - } - - if string(result[0].Rows[0][0]) == "t" { - return errors.New("server is in standby mode") - } - - return nil -} - -// ValidateConnectTargetSessionAttrsPreferStandby is a ValidateConnectFunc that implements libpq compatible -// target_session_attrs=prefer-standby. -func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn *PgConn) error { - result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll() - if err != nil { - return err - } - - if string(result[0].Rows[0][0]) != "t" { - return &NotPreferredError{err: errors.New("server is not in hot standby mode")} - } - - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/ctxwatch/context_watcher.go b/vendor/github.com/jackc/pgx/v5/pgconn/ctxwatch/context_watcher.go deleted file mode 100644 index db8884eb8..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/ctxwatch/context_watcher.go +++ /dev/null @@ -1,80 +0,0 @@ -package ctxwatch - -import ( - "context" - "sync" -) - -// ContextWatcher watches a context and performs an action when the context is canceled. It can watch one context at a -// time. -type ContextWatcher struct { - handler Handler - unwatchChan chan struct{} - - lock sync.Mutex - watchInProgress bool - onCancelWasCalled bool -} - -// NewContextWatcher returns a ContextWatcher. onCancel will be called when a watched context is canceled. -// OnUnwatchAfterCancel will be called when Unwatch is called and the watched context had already been canceled and -// onCancel called. -func NewContextWatcher(handler Handler) *ContextWatcher { - cw := &ContextWatcher{ - handler: handler, - unwatchChan: make(chan struct{}), - } - - return cw -} - -// Watch starts watching ctx. If ctx is canceled then the onCancel function passed to NewContextWatcher will be called. -func (cw *ContextWatcher) Watch(ctx context.Context) { - cw.lock.Lock() - defer cw.lock.Unlock() - - if cw.watchInProgress { - panic("Watch already in progress") - } - - cw.onCancelWasCalled = false - - if ctx.Done() != nil { - cw.watchInProgress = true - go func() { - select { - case <-ctx.Done(): - cw.handler.HandleCancel(ctx) - cw.onCancelWasCalled = true - <-cw.unwatchChan - case <-cw.unwatchChan: - } - }() - } else { - cw.watchInProgress = false - } -} - -// Unwatch stops watching the previously watched context. If the onCancel function passed to NewContextWatcher was -// called then onUnwatchAfterCancel will also be called. -func (cw *ContextWatcher) Unwatch() { - cw.lock.Lock() - defer cw.lock.Unlock() - - if cw.watchInProgress { - cw.unwatchChan <- struct{}{} - if cw.onCancelWasCalled { - cw.handler.HandleUnwatchAfterCancel() - } - cw.watchInProgress = false - } -} - -type Handler interface { - // HandleCancel is called when the context that a ContextWatcher is currently watching is canceled. canceledCtx is the - // context that was canceled. - HandleCancel(canceledCtx context.Context) - - // HandleUnwatchAfterCancel is called when a ContextWatcher that called HandleCancel on this Handler is unwatched. - HandleUnwatchAfterCancel() -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go b/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go deleted file mode 100644 index 1dd514ff4..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go +++ /dev/null @@ -1,63 +0,0 @@ -//go:build !windows -// +build !windows - -package pgconn - -import ( - "os" - "os/user" - "path/filepath" -) - -func defaultSettings() map[string]string { - settings := make(map[string]string) - - settings["host"] = defaultHost() - settings["port"] = "5432" - - // Default to the OS user name. Purposely ignoring err getting user name from - // OS. The client application will simply have to specify the user in that - // case (which they typically will be doing anyway). - user, err := user.Current() - if err == nil { - settings["user"] = user.Username - settings["passfile"] = filepath.Join(user.HomeDir, ".pgpass") - settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf") - sslcert := filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") - sslkey := filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") - if _, err := os.Stat(sslcert); err == nil { - if _, err := os.Stat(sslkey); err == nil { - // Both the cert and key must be present to use them, or do not use either - settings["sslcert"] = sslcert - settings["sslkey"] = sslkey - } - } - sslrootcert := filepath.Join(user.HomeDir, ".postgresql", "root.crt") - if _, err := os.Stat(sslrootcert); err == nil { - settings["sslrootcert"] = sslrootcert - } - } - - settings["target_session_attrs"] = "any" - - return settings -} - -// defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost -// on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it -// checks the existence of common locations. -func defaultHost() string { - candidatePaths := []string{ - "/var/run/postgresql", // Debian - "/private/tmp", // OSX - homebrew - "/tmp", // standard PostgreSQL - } - - for _, path := range candidatePaths { - if _, err := os.Stat(path); err == nil { - return path - } - } - - return "localhost" -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go b/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go deleted file mode 100644 index 33b4a1ff8..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go +++ /dev/null @@ -1,57 +0,0 @@ -package pgconn - -import ( - "os" - "os/user" - "path/filepath" - "strings" -) - -func defaultSettings() map[string]string { - settings := make(map[string]string) - - settings["host"] = defaultHost() - settings["port"] = "5432" - - // Default to the OS user name. Purposely ignoring err getting user name from - // OS. The client application will simply have to specify the user in that - // case (which they typically will be doing anyway). - user, err := user.Current() - appData := os.Getenv("APPDATA") - if err == nil { - // Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`, - // but the libpq default is just the `user` portion, so we strip off the first part. - username := user.Username - if strings.Contains(username, "\\") { - username = username[strings.LastIndex(username, "\\")+1:] - } - - settings["user"] = username - settings["passfile"] = filepath.Join(appData, "postgresql", "pgpass.conf") - settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf") - sslcert := filepath.Join(appData, "postgresql", "postgresql.crt") - sslkey := filepath.Join(appData, "postgresql", "postgresql.key") - if _, err := os.Stat(sslcert); err == nil { - if _, err := os.Stat(sslkey); err == nil { - // Both the cert and key must be present to use them, or do not use either - settings["sslcert"] = sslcert - settings["sslkey"] = sslkey - } - } - sslrootcert := filepath.Join(appData, "postgresql", "root.crt") - if _, err := os.Stat(sslrootcert); err == nil { - settings["sslrootcert"] = sslrootcert - } - } - - settings["target_session_attrs"] = "any" - - return settings -} - -// defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost -// on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it -// checks the existence of common locations. -func defaultHost() string { - return "localhost" -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/doc.go b/vendor/github.com/jackc/pgx/v5/pgconn/doc.go deleted file mode 100644 index 701375019..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/doc.go +++ /dev/null @@ -1,38 +0,0 @@ -// Package pgconn is a low-level PostgreSQL database driver. -/* -pgconn provides lower level access to a PostgreSQL connection than a database/sql or pgx connection. It operates at -nearly the same level is the C library libpq. - -Establishing a Connection - -Use Connect to establish a connection. It accepts a connection string in URL or keyword/value format and will read the -environment for libpq style environment variables. - -Executing a Query - -ExecParams and ExecPrepared execute a single query. They return readers that iterate over each row. The Read method -reads all rows into memory. - -Executing Multiple Queries in a Single Round Trip - -Exec and ExecBatch can execute multiple queries in a single round trip. They return readers that iterate over each query -result. The ReadAll method reads all query results into memory. - -Pipeline Mode - -Pipeline mode allows sending queries without having read the results of previously sent queries. It allows control of -exactly how many and when network round trips occur. - -Context Support - -All potentially blocking operations take a context.Context. The default behavior when a context is canceled is for the -method to immediately return. In most circumstances, this will also close the underlying connection. This behavior can -be customized by using BuildContextWatcherHandler on the Config to create a ctxwatch.Handler with different behavior. -This can be especially useful when queries that are frequently canceled and the overhead of creating new connections is -a problem. DeadlineContextWatcherHandler and CancelRequestContextWatcherHandler can be used to introduce a delay before -interrupting the query in such a way as to close the connection. - -The CancelRequest method may be used to request the PostgreSQL server cancel an in-progress query without forcing the -client to abort. -*/ -package pgconn diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go deleted file mode 100644 index ec4a6d47c..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go +++ /dev/null @@ -1,248 +0,0 @@ -package pgconn - -import ( - "context" - "errors" - "fmt" - "net" - "net/url" - "regexp" - "strings" -) - -// SafeToRetry checks if the err is guaranteed to have occurred before sending any data to the server. -func SafeToRetry(err error) bool { - var retryableErr interface{ SafeToRetry() bool } - if errors.As(err, &retryableErr) { - return retryableErr.SafeToRetry() - } - return false -} - -// Timeout checks if err was caused by a timeout. To be specific, it is true if err was caused within pgconn by a -// context.DeadlineExceeded or an implementer of net.Error where Timeout() is true. -func Timeout(err error) bool { - var timeoutErr *errTimeout - return errors.As(err, &timeoutErr) -} - -// PgError represents an error reported by the PostgreSQL server. See -// http://www.postgresql.org/docs/11/static/protocol-error-fields.html for -// detailed field description. -type PgError struct { - Severity string - SeverityUnlocalized string - Code string - Message string - Detail string - Hint string - Position int32 - InternalPosition int32 - InternalQuery string - Where string - SchemaName string - TableName string - ColumnName string - DataTypeName string - ConstraintName string - File string - Line int32 - Routine string -} - -func (pe *PgError) Error() string { - return pe.Severity + ": " + pe.Message + " (SQLSTATE " + pe.Code + ")" -} - -// SQLState returns the SQLState of the error. -func (pe *PgError) SQLState() string { - return pe.Code -} - -// ConnectError is the error returned when a connection attempt fails. -type ConnectError struct { - Config *Config // The configuration that was used in the connection attempt. - err error -} - -func (e *ConnectError) Error() string { - prefix := fmt.Sprintf("failed to connect to `user=%s database=%s`:", e.Config.User, e.Config.Database) - details := e.err.Error() - if strings.Contains(details, "\n") { - return prefix + "\n\t" + strings.ReplaceAll(details, "\n", "\n\t") - } else { - return prefix + " " + details - } -} - -func (e *ConnectError) Unwrap() error { - return e.err -} - -type perDialConnectError struct { - address string - originalHostname string - err error -} - -func (e *perDialConnectError) Error() string { - return fmt.Sprintf("%s (%s): %s", e.address, e.originalHostname, e.err.Error()) -} - -func (e *perDialConnectError) Unwrap() error { - return e.err -} - -type connLockError struct { - status string -} - -func (e *connLockError) SafeToRetry() bool { - return true // a lock failure by definition happens before the connection is used. -} - -func (e *connLockError) Error() string { - return e.status -} - -// ParseConfigError is the error returned when a connection string cannot be parsed. -type ParseConfigError struct { - ConnString string // The connection string that could not be parsed. - msg string - err error -} - -func (e *ParseConfigError) Error() string { - // Now that ParseConfigError is public and ConnString is available to the developer, perhaps it would be better only - // return a static string. That would ensure that the error message cannot leak a password. The ConnString field would - // allow access to the original string if desired and Unwrap would allow access to the underlying error. - connString := redactPW(e.ConnString) - if e.err == nil { - return fmt.Sprintf("cannot parse `%s`: %s", connString, e.msg) - } - return fmt.Sprintf("cannot parse `%s`: %s (%s)", connString, e.msg, e.err.Error()) -} - -func (e *ParseConfigError) Unwrap() error { - return e.err -} - -func normalizeTimeoutError(ctx context.Context, err error) error { - var netErr net.Error - if errors.As(err, &netErr) && netErr.Timeout() { - if ctx.Err() == context.Canceled { - // Since the timeout was caused by a context cancellation, the actual error is context.Canceled not the timeout error. - return context.Canceled - } else if ctx.Err() == context.DeadlineExceeded { - return &errTimeout{err: ctx.Err()} - } else { - return &errTimeout{err: netErr} - } - } - return err -} - -type pgconnError struct { - msg string - err error - safeToRetry bool -} - -func (e *pgconnError) Error() string { - if e.msg == "" { - return e.err.Error() - } - if e.err == nil { - return e.msg - } - return fmt.Sprintf("%s: %s", e.msg, e.err.Error()) -} - -func (e *pgconnError) SafeToRetry() bool { - return e.safeToRetry -} - -func (e *pgconnError) Unwrap() error { - return e.err -} - -// errTimeout occurs when an error was caused by a timeout. Specifically, it wraps an error which is -// context.Canceled, context.DeadlineExceeded, or an implementer of net.Error where Timeout() is true. -type errTimeout struct { - err error -} - -func (e *errTimeout) Error() string { - return fmt.Sprintf("timeout: %s", e.err.Error()) -} - -func (e *errTimeout) SafeToRetry() bool { - return SafeToRetry(e.err) -} - -func (e *errTimeout) Unwrap() error { - return e.err -} - -type contextAlreadyDoneError struct { - err error -} - -func (e *contextAlreadyDoneError) Error() string { - return fmt.Sprintf("context already done: %s", e.err.Error()) -} - -func (e *contextAlreadyDoneError) SafeToRetry() bool { - return true -} - -func (e *contextAlreadyDoneError) Unwrap() error { - return e.err -} - -// newContextAlreadyDoneError double-wraps a context error in `contextAlreadyDoneError` and `errTimeout`. -func newContextAlreadyDoneError(ctx context.Context) (err error) { - return &errTimeout{&contextAlreadyDoneError{err: ctx.Err()}} -} - -func redactPW(connString string) string { - if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { - if u, err := url.Parse(connString); err == nil { - return redactURL(u) - } - } - quotedKV := regexp.MustCompile(`password='[^']*'`) - connString = quotedKV.ReplaceAllLiteralString(connString, "password=xxxxx") - plainKV := regexp.MustCompile(`password=[^ ]*`) - connString = plainKV.ReplaceAllLiteralString(connString, "password=xxxxx") - brokenURL := regexp.MustCompile(`:[^:@]+?@`) - connString = brokenURL.ReplaceAllLiteralString(connString, ":xxxxxx@") - return connString -} - -func redactURL(u *url.URL) string { - if u == nil { - return "" - } - if _, pwSet := u.User.Password(); pwSet { - u.User = url.UserPassword(u.User.Username(), "xxxxx") - } - return u.String() -} - -type NotPreferredError struct { - err error - safeToRetry bool -} - -func (e *NotPreferredError) Error() string { - return fmt.Sprintf("standby server not found: %s", e.err.Error()) -} - -func (e *NotPreferredError) SafeToRetry() bool { - return e.safeToRetry -} - -func (e *NotPreferredError) Unwrap() error { - return e.err -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go b/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go deleted file mode 100644 index e65c2c2bf..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go +++ /dev/null @@ -1,139 +0,0 @@ -// Package bgreader provides a io.Reader that can optionally buffer reads in the background. -package bgreader - -import ( - "io" - "sync" - - "github.com/jackc/pgx/v5/internal/iobufpool" -) - -const ( - StatusStopped = iota - StatusRunning - StatusStopping -) - -// BGReader is an io.Reader that can optionally buffer reads in the background. It is safe for concurrent use. -type BGReader struct { - r io.Reader - - cond *sync.Cond - status int32 - readResults []readResult -} - -type readResult struct { - buf *[]byte - err error -} - -// Start starts the backgrounder reader. If the background reader is already running this is a no-op. The background -// reader will stop automatically when the underlying reader returns an error. -func (r *BGReader) Start() { - r.cond.L.Lock() - defer r.cond.L.Unlock() - - switch r.status { - case StatusStopped: - r.status = StatusRunning - go r.bgRead() - case StatusRunning: - // no-op - case StatusStopping: - r.status = StatusRunning - } -} - -// Stop tells the background reader to stop after the in progress Read returns. It is safe to call Stop when the -// background reader is not running. -func (r *BGReader) Stop() { - r.cond.L.Lock() - defer r.cond.L.Unlock() - - switch r.status { - case StatusStopped: - // no-op - case StatusRunning: - r.status = StatusStopping - case StatusStopping: - // no-op - } -} - -// Status returns the current status of the background reader. -func (r *BGReader) Status() int32 { - r.cond.L.Lock() - defer r.cond.L.Unlock() - return r.status -} - -func (r *BGReader) bgRead() { - keepReading := true - for keepReading { - buf := iobufpool.Get(8192) - n, err := r.r.Read(*buf) - *buf = (*buf)[:n] - - r.cond.L.Lock() - r.readResults = append(r.readResults, readResult{buf: buf, err: err}) - if r.status == StatusStopping || err != nil { - r.status = StatusStopped - keepReading = false - } - r.cond.L.Unlock() - r.cond.Broadcast() - } -} - -// Read implements the io.Reader interface. -func (r *BGReader) Read(p []byte) (int, error) { - r.cond.L.Lock() - defer r.cond.L.Unlock() - - if len(r.readResults) > 0 { - return r.readFromReadResults(p) - } - - // There are no unread background read results and the background reader is stopped. - if r.status == StatusStopped { - return r.r.Read(p) - } - - // Wait for results from the background reader - for len(r.readResults) == 0 { - r.cond.Wait() - } - return r.readFromReadResults(p) -} - -// readBackgroundResults reads a result previously read by the background reader. r.cond.L must be held. -func (r *BGReader) readFromReadResults(p []byte) (int, error) { - buf := r.readResults[0].buf - var err error - - n := copy(p, *buf) - if n == len(*buf) { - err = r.readResults[0].err - iobufpool.Put(buf) - if len(r.readResults) == 1 { - r.readResults = nil - } else { - r.readResults = r.readResults[1:] - } - } else { - *buf = (*buf)[n:] - r.readResults[0].buf = buf - } - - return n, err -} - -func New(r io.Reader) *BGReader { - return &BGReader{ - r: r, - cond: &sync.Cond{ - L: &sync.Mutex{}, - }, - } -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/krb5.go b/vendor/github.com/jackc/pgx/v5/pgconn/krb5.go deleted file mode 100644 index 3c1af3477..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/krb5.go +++ /dev/null @@ -1,100 +0,0 @@ -package pgconn - -import ( - "errors" - "fmt" - - "github.com/jackc/pgx/v5/pgproto3" -) - -// NewGSSFunc creates a GSS authentication provider, for use with -// RegisterGSSProvider. -type NewGSSFunc func() (GSS, error) - -var newGSS NewGSSFunc - -// RegisterGSSProvider registers a GSS authentication provider. For example, if -// you need to use Kerberos to authenticate with your server, add this to your -// main package: -// -// import "github.com/otan/gopgkrb5" -// -// func init() { -// pgconn.RegisterGSSProvider(func() (pgconn.GSS, error) { return gopgkrb5.NewGSS() }) -// } -func RegisterGSSProvider(newGSSArg NewGSSFunc) { - newGSS = newGSSArg -} - -// GSS provides GSSAPI authentication (e.g., Kerberos). -type GSS interface { - GetInitToken(host string, service string) ([]byte, error) - GetInitTokenFromSPN(spn string) ([]byte, error) - Continue(inToken []byte) (done bool, outToken []byte, err error) -} - -func (c *PgConn) gssAuth() error { - if newGSS == nil { - return errors.New("kerberos error: no GSSAPI provider registered, see https://github.com/otan/gopgkrb5") - } - cli, err := newGSS() - if err != nil { - return err - } - - var nextData []byte - if c.config.KerberosSpn != "" { - // Use the supplied SPN if provided. - nextData, err = cli.GetInitTokenFromSPN(c.config.KerberosSpn) - } else { - // Allow the kerberos service name to be overridden - service := "postgres" - if c.config.KerberosSrvName != "" { - service = c.config.KerberosSrvName - } - nextData, err = cli.GetInitToken(c.config.Host, service) - } - if err != nil { - return err - } - - for { - gssResponse := &pgproto3.GSSResponse{ - Data: nextData, - } - c.frontend.Send(gssResponse) - err = c.flushWithPotentialWriteReadDeadlock() - if err != nil { - return err - } - resp, err := c.rxGSSContinue() - if err != nil { - return err - } - var done bool - done, nextData, err = cli.Continue(resp.Data) - if err != nil { - return err - } - if done { - break - } - } - return nil -} - -func (c *PgConn) rxGSSContinue() (*pgproto3.AuthenticationGSSContinue, error) { - msg, err := c.receiveMessage() - if err != nil { - return nil, err - } - - switch m := msg.(type) { - case *pgproto3.AuthenticationGSSContinue: - return m, nil - case *pgproto3.ErrorResponse: - return nil, ErrorResponseToPgError(m) - } - - return nil, fmt.Errorf("expected AuthenticationGSSContinue message but received unexpected message %T", msg) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go deleted file mode 100644 index 7efb522a4..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go +++ /dev/null @@ -1,2346 +0,0 @@ -package pgconn - -import ( - "context" - "crypto/md5" - "crypto/tls" - "encoding/binary" - "encoding/hex" - "errors" - "fmt" - "io" - "math" - "net" - "strconv" - "strings" - "sync" - "time" - - "github.com/jackc/pgx/v5/internal/iobufpool" - "github.com/jackc/pgx/v5/internal/pgio" - "github.com/jackc/pgx/v5/pgconn/ctxwatch" - "github.com/jackc/pgx/v5/pgconn/internal/bgreader" - "github.com/jackc/pgx/v5/pgproto3" -) - -const ( - connStatusUninitialized = iota - connStatusConnecting - connStatusClosed - connStatusIdle - connStatusBusy -) - -// Notice represents a notice response message reported by the PostgreSQL server. Be aware that this is distinct from -// LISTEN/NOTIFY notification. -type Notice PgError - -// Notification is a message received from the PostgreSQL LISTEN/NOTIFY system -type Notification struct { - PID uint32 // backend pid that sent the notification - Channel string // channel from which notification was received - Payload string -} - -// DialFunc is a function that can be used to connect to a PostgreSQL server. -type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error) - -// LookupFunc is a function that can be used to lookup IPs addrs from host. Optionally an ip:port combination can be -// returned in order to override the connection string's port. -type LookupFunc func(ctx context.Context, host string) (addrs []string, err error) - -// BuildFrontendFunc is a function that can be used to create Frontend implementation for connection. -type BuildFrontendFunc func(r io.Reader, w io.Writer) *pgproto3.Frontend - -// PgErrorHandler is a function that handles errors returned from Postgres. This function must return true to keep -// the connection open. Returning false will cause the connection to be closed immediately. You should return -// false on any FATAL-severity errors. This will not receive network errors. The *PgConn is provided so the handler is -// aware of the origin of the error, but it must not invoke any query method. -type PgErrorHandler func(*PgConn, *PgError) bool - -// NoticeHandler is a function that can handle notices received from the PostgreSQL server. Notices can be received at -// any time, usually during handling of a query response. The *PgConn is provided so the handler is aware of the origin -// of the notice, but it must not invoke any query method. Be aware that this is distinct from LISTEN/NOTIFY -// notification. -type NoticeHandler func(*PgConn, *Notice) - -// NotificationHandler is a function that can handle notifications received from the PostgreSQL server. Notifications -// can be received at any time, usually during handling of a query response. The *PgConn is provided so the handler is -// aware of the origin of the notice, but it must not invoke any query method. Be aware that this is distinct from a -// notice event. -type NotificationHandler func(*PgConn, *Notification) - -// PgConn is a low-level PostgreSQL connection handle. It is not safe for concurrent usage. -type PgConn struct { - conn net.Conn - pid uint32 // backend pid - secretKey uint32 // key to use to send a cancel query message to the server - parameterStatuses map[string]string // parameters that have been reported by the server - txStatus byte - frontend *pgproto3.Frontend - bgReader *bgreader.BGReader - slowWriteTimer *time.Timer - bgReaderStarted chan struct{} - - customData map[string]any - - config *Config - - status byte // One of connStatus* constants - - bufferingReceive bool - bufferingReceiveMux sync.Mutex - bufferingReceiveMsg pgproto3.BackendMessage - bufferingReceiveErr error - - peekedMsg pgproto3.BackendMessage - - // Reusable / preallocated resources - resultReader ResultReader - multiResultReader MultiResultReader - pipeline Pipeline - contextWatcher *ctxwatch.ContextWatcher - fieldDescriptions [16]FieldDescription - - cleanupDone chan struct{} -} - -// Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value -// format) to provide configuration. See documentation for [ParseConfig] for details. ctx can be used to cancel a -// connect attempt. -func Connect(ctx context.Context, connString string) (*PgConn, error) { - config, err := ParseConfig(connString) - if err != nil { - return nil, err - } - - return ConnectConfig(ctx, config) -} - -// Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value -// format) and ParseConfigOptions to provide additional configuration. See documentation for [ParseConfig] for details. -// ctx can be used to cancel a connect attempt. -func ConnectWithOptions(ctx context.Context, connString string, parseConfigOptions ParseConfigOptions) (*PgConn, error) { - config, err := ParseConfigWithOptions(connString, parseConfigOptions) - if err != nil { - return nil, err - } - - return ConnectConfig(ctx, config) -} - -// Connect establishes a connection to a PostgreSQL server using config. config must have been constructed with -// [ParseConfig]. ctx can be used to cancel a connect attempt. -// -// If config.Fallbacks are present they will sequentially be tried in case of error establishing network connection. An -// authentication error will terminate the chain of attempts (like libpq: -// https://www.postgresql.org/docs/11/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS) and be returned as the error. -func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error) { - // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from - // zero values. - if !config.createdByParseConfig { - panic("config must be created by ParseConfig") - } - - var allErrors []error - - connectConfigs, errs := buildConnectOneConfigs(ctx, config) - if len(errs) > 0 { - allErrors = append(allErrors, errs...) - } - - if len(connectConfigs) == 0 { - return nil, &ConnectError{Config: config, err: fmt.Errorf("hostname resolving error: %w", errors.Join(allErrors...))} - } - - pgConn, errs := connectPreferred(ctx, config, connectConfigs) - if len(errs) > 0 { - allErrors = append(allErrors, errs...) - return nil, &ConnectError{Config: config, err: errors.Join(allErrors...)} - } - - if config.AfterConnect != nil { - err := config.AfterConnect(ctx, pgConn) - if err != nil { - pgConn.conn.Close() - return nil, &ConnectError{Config: config, err: fmt.Errorf("AfterConnect error: %w", err)} - } - } - - return pgConn, nil -} - -// buildConnectOneConfigs resolves hostnames and builds a list of connectOneConfigs to try connecting to. It returns a -// slice of successfully resolved connectOneConfigs and a slice of errors. It is possible for both slices to contain -// values if some hosts were successfully resolved and others were not. -func buildConnectOneConfigs(ctx context.Context, config *Config) ([]*connectOneConfig, []error) { - // Simplify usage by treating primary config and fallbacks the same. - fallbackConfigs := []*FallbackConfig{ - { - Host: config.Host, - Port: config.Port, - TLSConfig: config.TLSConfig, - }, - } - fallbackConfigs = append(fallbackConfigs, config.Fallbacks...) - - var configs []*connectOneConfig - - var allErrors []error - - for _, fb := range fallbackConfigs { - // skip resolve for unix sockets - if isAbsolutePath(fb.Host) { - network, address := NetworkAddress(fb.Host, fb.Port) - configs = append(configs, &connectOneConfig{ - network: network, - address: address, - originalHostname: fb.Host, - tlsConfig: fb.TLSConfig, - }) - - continue - } - - ips, err := config.LookupFunc(ctx, fb.Host) - if err != nil { - allErrors = append(allErrors, err) - continue - } - - for _, ip := range ips { - splitIP, splitPort, err := net.SplitHostPort(ip) - if err == nil { - port, err := strconv.ParseUint(splitPort, 10, 16) - if err != nil { - return nil, []error{fmt.Errorf("error parsing port (%s) from lookup: %w", splitPort, err)} - } - network, address := NetworkAddress(splitIP, uint16(port)) - configs = append(configs, &connectOneConfig{ - network: network, - address: address, - originalHostname: fb.Host, - tlsConfig: fb.TLSConfig, - }) - } else { - network, address := NetworkAddress(ip, fb.Port) - configs = append(configs, &connectOneConfig{ - network: network, - address: address, - originalHostname: fb.Host, - tlsConfig: fb.TLSConfig, - }) - } - } - } - - return configs, allErrors -} - -// connectPreferred attempts to connect to the preferred host from connectOneConfigs. The connections are attempted in -// order. If a connection is successful it is returned. If no connection is successful then all errors are returned. If -// a connection attempt returns a [NotPreferredError], then that host will be used if no other hosts are successful. -func connectPreferred(ctx context.Context, config *Config, connectOneConfigs []*connectOneConfig) (*PgConn, []error) { - octx := ctx - var allErrors []error - - var fallbackConnectOneConfig *connectOneConfig - for i, c := range connectOneConfigs { - // ConnectTimeout restricts the whole connection process. - if config.ConnectTimeout != 0 { - // create new context first time or when previous host was different - if i == 0 || (connectOneConfigs[i].address != connectOneConfigs[i-1].address) { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(octx, config.ConnectTimeout) - defer cancel() - } - } else { - ctx = octx - } - - pgConn, err := connectOne(ctx, config, c, false) - if pgConn != nil { - return pgConn, nil - } - - allErrors = append(allErrors, err) - - var pgErr *PgError - if errors.As(err, &pgErr) { - const ERRCODE_INVALID_PASSWORD = "28P01" // wrong password - const ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION = "28000" // wrong password or bad pg_hba.conf settings - const ERRCODE_INVALID_CATALOG_NAME = "3D000" // db does not exist - const ERRCODE_INSUFFICIENT_PRIVILEGE = "42501" // missing connect privilege - if pgErr.Code == ERRCODE_INVALID_PASSWORD || - pgErr.Code == ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION && c.tlsConfig != nil || - pgErr.Code == ERRCODE_INVALID_CATALOG_NAME || - pgErr.Code == ERRCODE_INSUFFICIENT_PRIVILEGE { - return nil, allErrors - } - } - - var npErr *NotPreferredError - if errors.As(err, &npErr) { - fallbackConnectOneConfig = c - } - } - - if fallbackConnectOneConfig != nil { - pgConn, err := connectOne(ctx, config, fallbackConnectOneConfig, true) - if err == nil { - return pgConn, nil - } - allErrors = append(allErrors, err) - } - - return nil, allErrors -} - -// connectOne makes one connection attempt to a single host. -func connectOne(ctx context.Context, config *Config, connectConfig *connectOneConfig, - ignoreNotPreferredErr bool, -) (*PgConn, error) { - pgConn := new(PgConn) - pgConn.config = config - pgConn.cleanupDone = make(chan struct{}) - pgConn.customData = make(map[string]any) - - var err error - - newPerDialConnectError := func(msg string, err error) *perDialConnectError { - err = normalizeTimeoutError(ctx, err) - e := &perDialConnectError{address: connectConfig.address, originalHostname: connectConfig.originalHostname, err: fmt.Errorf("%s: %w", msg, err)} - return e - } - - pgConn.conn, err = config.DialFunc(ctx, connectConfig.network, connectConfig.address) - if err != nil { - return nil, newPerDialConnectError("dial error", err) - } - - if connectConfig.tlsConfig != nil { - pgConn.contextWatcher = ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: pgConn.conn}) - pgConn.contextWatcher.Watch(ctx) - tlsConn, err := startTLS(pgConn.conn, connectConfig.tlsConfig) - pgConn.contextWatcher.Unwatch() // Always unwatch `netConn` after TLS. - if err != nil { - pgConn.conn.Close() - return nil, newPerDialConnectError("tls error", err) - } - - pgConn.conn = tlsConn - } - - pgConn.contextWatcher = ctxwatch.NewContextWatcher(config.BuildContextWatcherHandler(pgConn)) - pgConn.contextWatcher.Watch(ctx) - defer pgConn.contextWatcher.Unwatch() - - pgConn.parameterStatuses = make(map[string]string) - pgConn.status = connStatusConnecting - pgConn.bgReader = bgreader.New(pgConn.conn) - pgConn.slowWriteTimer = time.AfterFunc(time.Duration(math.MaxInt64), - func() { - pgConn.bgReader.Start() - pgConn.bgReaderStarted <- struct{}{} - }, - ) - pgConn.slowWriteTimer.Stop() - pgConn.bgReaderStarted = make(chan struct{}) - pgConn.frontend = config.BuildFrontend(pgConn.bgReader, pgConn.conn) - - startupMsg := pgproto3.StartupMessage{ - ProtocolVersion: pgproto3.ProtocolVersionNumber, - Parameters: make(map[string]string), - } - - // Copy default run-time params - for k, v := range config.RuntimeParams { - startupMsg.Parameters[k] = v - } - - startupMsg.Parameters["user"] = config.User - if config.Database != "" { - startupMsg.Parameters["database"] = config.Database - } - - pgConn.frontend.Send(&startupMsg) - if err := pgConn.flushWithPotentialWriteReadDeadlock(); err != nil { - pgConn.conn.Close() - return nil, newPerDialConnectError("failed to write startup message", err) - } - - for { - msg, err := pgConn.receiveMessage() - if err != nil { - pgConn.conn.Close() - if err, ok := err.(*PgError); ok { - return nil, newPerDialConnectError("server error", err) - } - return nil, newPerDialConnectError("failed to receive message", err) - } - - switch msg := msg.(type) { - case *pgproto3.BackendKeyData: - pgConn.pid = msg.ProcessID - pgConn.secretKey = msg.SecretKey - - case *pgproto3.AuthenticationOk: - case *pgproto3.AuthenticationCleartextPassword: - err = pgConn.txPasswordMessage(pgConn.config.Password) - if err != nil { - pgConn.conn.Close() - return nil, newPerDialConnectError("failed to write password message", err) - } - case *pgproto3.AuthenticationMD5Password: - digestedPassword := "md5" + hexMD5(hexMD5(pgConn.config.Password+pgConn.config.User)+string(msg.Salt[:])) - err = pgConn.txPasswordMessage(digestedPassword) - if err != nil { - pgConn.conn.Close() - return nil, newPerDialConnectError("failed to write password message", err) - } - case *pgproto3.AuthenticationSASL: - err = pgConn.scramAuth(msg.AuthMechanisms) - if err != nil { - pgConn.conn.Close() - return nil, newPerDialConnectError("failed SASL auth", err) - } - case *pgproto3.AuthenticationGSS: - err = pgConn.gssAuth() - if err != nil { - pgConn.conn.Close() - return nil, newPerDialConnectError("failed GSS auth", err) - } - case *pgproto3.ReadyForQuery: - pgConn.status = connStatusIdle - if config.ValidateConnect != nil { - // ValidateConnect may execute commands that cause the context to be watched again. Unwatch first to avoid - // the watch already in progress panic. This is that last thing done by this method so there is no need to - // restart the watch after ValidateConnect returns. - // - // See https://github.com/jackc/pgconn/issues/40. - pgConn.contextWatcher.Unwatch() - - err := config.ValidateConnect(ctx, pgConn) - if err != nil { - if _, ok := err.(*NotPreferredError); ignoreNotPreferredErr && ok { - return pgConn, nil - } - pgConn.conn.Close() - return nil, newPerDialConnectError("ValidateConnect failed", err) - } - } - return pgConn, nil - case *pgproto3.ParameterStatus, *pgproto3.NoticeResponse: - // handled by ReceiveMessage - case *pgproto3.ErrorResponse: - pgConn.conn.Close() - return nil, newPerDialConnectError("server error", ErrorResponseToPgError(msg)) - default: - pgConn.conn.Close() - return nil, newPerDialConnectError("received unexpected message", err) - } - } -} - -func startTLS(conn net.Conn, tlsConfig *tls.Config) (net.Conn, error) { - err := binary.Write(conn, binary.BigEndian, []int32{8, 80877103}) - if err != nil { - return nil, err - } - - response := make([]byte, 1) - if _, err = io.ReadFull(conn, response); err != nil { - return nil, err - } - - if response[0] != 'S' { - return nil, errors.New("server refused TLS connection") - } - - return tls.Client(conn, tlsConfig), nil -} - -func (pgConn *PgConn) txPasswordMessage(password string) (err error) { - pgConn.frontend.Send(&pgproto3.PasswordMessage{Password: password}) - return pgConn.flushWithPotentialWriteReadDeadlock() -} - -func hexMD5(s string) string { - hash := md5.New() - io.WriteString(hash, s) - return hex.EncodeToString(hash.Sum(nil)) -} - -func (pgConn *PgConn) signalMessage() chan struct{} { - if pgConn.bufferingReceive { - panic("BUG: signalMessage when already in progress") - } - - pgConn.bufferingReceive = true - pgConn.bufferingReceiveMux.Lock() - - ch := make(chan struct{}) - go func() { - pgConn.bufferingReceiveMsg, pgConn.bufferingReceiveErr = pgConn.frontend.Receive() - pgConn.bufferingReceiveMux.Unlock() - close(ch) - }() - - return ch -} - -// ReceiveMessage receives one wire protocol message from the PostgreSQL server. It must only be used when the -// connection is not busy. e.g. It is an error to call ReceiveMessage while reading the result of a query. The messages -// are still handled by the core pgconn message handling system so receiving a NotificationResponse will still trigger -// the OnNotification callback. -// -// This is a very low level method that requires deep understanding of the PostgreSQL wire protocol to use correctly. -// See https://www.postgresql.org/docs/current/protocol.html. -func (pgConn *PgConn) ReceiveMessage(ctx context.Context) (pgproto3.BackendMessage, error) { - if err := pgConn.lock(); err != nil { - return nil, err - } - defer pgConn.unlock() - - if ctx != context.Background() { - select { - case <-ctx.Done(): - return nil, newContextAlreadyDoneError(ctx) - default: - } - pgConn.contextWatcher.Watch(ctx) - defer pgConn.contextWatcher.Unwatch() - } - - msg, err := pgConn.receiveMessage() - if err != nil { - err = &pgconnError{ - msg: "receive message failed", - err: normalizeTimeoutError(ctx, err), - safeToRetry: true, - } - } - return msg, err -} - -// peekMessage peeks at the next message without setting up context cancellation. -func (pgConn *PgConn) peekMessage() (pgproto3.BackendMessage, error) { - if pgConn.peekedMsg != nil { - return pgConn.peekedMsg, nil - } - - var msg pgproto3.BackendMessage - var err error - if pgConn.bufferingReceive { - pgConn.bufferingReceiveMux.Lock() - msg = pgConn.bufferingReceiveMsg - err = pgConn.bufferingReceiveErr - pgConn.bufferingReceiveMux.Unlock() - pgConn.bufferingReceive = false - - // If a timeout error happened in the background try the read again. - var netErr net.Error - if errors.As(err, &netErr) && netErr.Timeout() { - msg, err = pgConn.frontend.Receive() - } - } else { - msg, err = pgConn.frontend.Receive() - } - - if err != nil { - // Close on anything other than timeout error - everything else is fatal - var netErr net.Error - isNetErr := errors.As(err, &netErr) - if !(isNetErr && netErr.Timeout()) { - pgConn.asyncClose() - } - - return nil, err - } - - pgConn.peekedMsg = msg - return msg, nil -} - -// receiveMessage receives a message without setting up context cancellation -func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) { - msg, err := pgConn.peekMessage() - if err != nil { - return nil, err - } - pgConn.peekedMsg = nil - - switch msg := msg.(type) { - case *pgproto3.ReadyForQuery: - pgConn.txStatus = msg.TxStatus - case *pgproto3.ParameterStatus: - pgConn.parameterStatuses[msg.Name] = msg.Value - case *pgproto3.ErrorResponse: - err := ErrorResponseToPgError(msg) - if pgConn.config.OnPgError != nil && !pgConn.config.OnPgError(pgConn, err) { - pgConn.status = connStatusClosed - pgConn.conn.Close() // Ignore error as the connection is already broken and there is already an error to return. - close(pgConn.cleanupDone) - return nil, err - } - case *pgproto3.NoticeResponse: - if pgConn.config.OnNotice != nil { - pgConn.config.OnNotice(pgConn, noticeResponseToNotice(msg)) - } - case *pgproto3.NotificationResponse: - if pgConn.config.OnNotification != nil { - pgConn.config.OnNotification(pgConn, &Notification{PID: msg.PID, Channel: msg.Channel, Payload: msg.Payload}) - } - } - - return msg, nil -} - -// Conn returns the underlying net.Conn. This rarely necessary. If the connection will be directly used for reading or -// writing then SyncConn should usually be called before Conn. -func (pgConn *PgConn) Conn() net.Conn { - return pgConn.conn -} - -// PID returns the backend PID. -func (pgConn *PgConn) PID() uint32 { - return pgConn.pid -} - -// TxStatus returns the current TxStatus as reported by the server in the ReadyForQuery message. -// -// Possible return values: -// -// 'I' - idle / not in transaction -// 'T' - in a transaction -// 'E' - in a failed transaction -// -// See https://www.postgresql.org/docs/current/protocol-message-formats.html. -func (pgConn *PgConn) TxStatus() byte { - return pgConn.txStatus -} - -// SecretKey returns the backend secret key used to send a cancel query message to the server. -func (pgConn *PgConn) SecretKey() uint32 { - return pgConn.secretKey -} - -// Frontend returns the underlying *pgproto3.Frontend. This rarely necessary. -func (pgConn *PgConn) Frontend() *pgproto3.Frontend { - return pgConn.frontend -} - -// Close closes a connection. It is safe to call Close on an already closed connection. Close attempts a clean close by -// sending the exit message to PostgreSQL. However, this could block so ctx is available to limit the time to wait. The -// underlying net.Conn.Close() will always be called regardless of any other errors. -func (pgConn *PgConn) Close(ctx context.Context) error { - if pgConn.status == connStatusClosed { - return nil - } - pgConn.status = connStatusClosed - - defer close(pgConn.cleanupDone) - defer pgConn.conn.Close() - - if ctx != context.Background() { - // Close may be called while a cancellable query is in progress. This will most often be triggered by panic when - // a defer closes the connection (possibly indirectly via a transaction or a connection pool). Unwatch to end any - // previous watch. It is safe to Unwatch regardless of whether a watch is already is progress. - // - // See https://github.com/jackc/pgconn/issues/29 - pgConn.contextWatcher.Unwatch() - - pgConn.contextWatcher.Watch(ctx) - defer pgConn.contextWatcher.Unwatch() - } - - // Ignore any errors sending Terminate message and waiting for server to close connection. - // This mimics the behavior of libpq PQfinish. It calls closePGconn which calls sendTerminateConn which purposefully - // ignores errors. - // - // See https://github.com/jackc/pgx/issues/637 - pgConn.frontend.Send(&pgproto3.Terminate{}) - pgConn.flushWithPotentialWriteReadDeadlock() - - return pgConn.conn.Close() -} - -// asyncClose marks the connection as closed and asynchronously sends a cancel query message and closes the underlying -// connection. -func (pgConn *PgConn) asyncClose() { - if pgConn.status == connStatusClosed { - return - } - pgConn.status = connStatusClosed - - go func() { - defer close(pgConn.cleanupDone) - defer pgConn.conn.Close() - - deadline := time.Now().Add(time.Second * 15) - - ctx, cancel := context.WithDeadline(context.Background(), deadline) - defer cancel() - - pgConn.CancelRequest(ctx) - - pgConn.conn.SetDeadline(deadline) - - pgConn.frontend.Send(&pgproto3.Terminate{}) - pgConn.flushWithPotentialWriteReadDeadlock() - }() -} - -// CleanupDone returns a channel that will be closed after all underlying resources have been cleaned up. A closed -// connection is no longer usable, but underlying resources, in particular the net.Conn, may not have finished closing -// yet. This is because certain errors such as a context cancellation require that the interrupted function call return -// immediately, but the error may also cause the connection to be closed. In these cases the underlying resources are -// closed asynchronously. -// -// This is only likely to be useful to connection pools. It gives them a way avoid establishing a new connection while -// an old connection is still being cleaned up and thereby exceeding the maximum pool size. -func (pgConn *PgConn) CleanupDone() chan (struct{}) { - return pgConn.cleanupDone -} - -// IsClosed reports if the connection has been closed. -// -// CleanupDone() can be used to determine if all cleanup has been completed. -func (pgConn *PgConn) IsClosed() bool { - return pgConn.status < connStatusIdle -} - -// IsBusy reports if the connection is busy. -func (pgConn *PgConn) IsBusy() bool { - return pgConn.status == connStatusBusy -} - -// lock locks the connection. -func (pgConn *PgConn) lock() error { - switch pgConn.status { - case connStatusBusy: - return &connLockError{status: "conn busy"} // This only should be possible in case of an application bug. - case connStatusClosed: - return &connLockError{status: "conn closed"} - case connStatusUninitialized: - return &connLockError{status: "conn uninitialized"} - } - pgConn.status = connStatusBusy - return nil -} - -func (pgConn *PgConn) unlock() { - switch pgConn.status { - case connStatusBusy: - pgConn.status = connStatusIdle - case connStatusClosed: - default: - panic("BUG: cannot unlock unlocked connection") // This should only be possible if there is a bug in this package. - } -} - -// ParameterStatus returns the value of a parameter reported by the server (e.g. -// server_version). Returns an empty string for unknown parameters. -func (pgConn *PgConn) ParameterStatus(key string) string { - return pgConn.parameterStatuses[key] -} - -// CommandTag is the status text returned by PostgreSQL for a query. -type CommandTag struct { - s string -} - -// NewCommandTag makes a CommandTag from s. -func NewCommandTag(s string) CommandTag { - return CommandTag{s: s} -} - -// RowsAffected returns the number of rows affected. If the CommandTag was not -// for a row affecting command (e.g. "CREATE TABLE") then it returns 0. -func (ct CommandTag) RowsAffected() int64 { - // Find last non-digit - idx := -1 - for i := len(ct.s) - 1; i >= 0; i-- { - if ct.s[i] >= '0' && ct.s[i] <= '9' { - idx = i - } else { - break - } - } - - if idx == -1 { - return 0 - } - - var n int64 - for _, b := range ct.s[idx:] { - n = n*10 + int64(b-'0') - } - - return n -} - -func (ct CommandTag) String() string { - return ct.s -} - -// Insert is true if the command tag starts with "INSERT". -func (ct CommandTag) Insert() bool { - return strings.HasPrefix(ct.s, "INSERT") -} - -// Update is true if the command tag starts with "UPDATE". -func (ct CommandTag) Update() bool { - return strings.HasPrefix(ct.s, "UPDATE") -} - -// Delete is true if the command tag starts with "DELETE". -func (ct CommandTag) Delete() bool { - return strings.HasPrefix(ct.s, "DELETE") -} - -// Select is true if the command tag starts with "SELECT". -func (ct CommandTag) Select() bool { - return strings.HasPrefix(ct.s, "SELECT") -} - -type FieldDescription struct { - Name string - TableOID uint32 - TableAttributeNumber uint16 - DataTypeOID uint32 - DataTypeSize int16 - TypeModifier int32 - Format int16 -} - -func (pgConn *PgConn) convertRowDescription(dst []FieldDescription, rd *pgproto3.RowDescription) []FieldDescription { - if cap(dst) >= len(rd.Fields) { - dst = dst[:len(rd.Fields):len(rd.Fields)] - } else { - dst = make([]FieldDescription, len(rd.Fields)) - } - - for i := range rd.Fields { - dst[i].Name = string(rd.Fields[i].Name) - dst[i].TableOID = rd.Fields[i].TableOID - dst[i].TableAttributeNumber = rd.Fields[i].TableAttributeNumber - dst[i].DataTypeOID = rd.Fields[i].DataTypeOID - dst[i].DataTypeSize = rd.Fields[i].DataTypeSize - dst[i].TypeModifier = rd.Fields[i].TypeModifier - dst[i].Format = rd.Fields[i].Format - } - - return dst -} - -type StatementDescription struct { - Name string - SQL string - ParamOIDs []uint32 - Fields []FieldDescription -} - -// Prepare creates a prepared statement. If the name is empty, the anonymous prepared statement will be used. This -// allows Prepare to also to describe statements without creating a server-side prepared statement. -// -// Prepare does not send a PREPARE statement to the server. It uses the PostgreSQL Parse and Describe protocol messages -// directly. -func (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs []uint32) (*StatementDescription, error) { - if err := pgConn.lock(); err != nil { - return nil, err - } - defer pgConn.unlock() - - if ctx != context.Background() { - select { - case <-ctx.Done(): - return nil, newContextAlreadyDoneError(ctx) - default: - } - pgConn.contextWatcher.Watch(ctx) - defer pgConn.contextWatcher.Unwatch() - } - - pgConn.frontend.SendParse(&pgproto3.Parse{Name: name, Query: sql, ParameterOIDs: paramOIDs}) - pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'S', Name: name}) - pgConn.frontend.SendSync(&pgproto3.Sync{}) - err := pgConn.flushWithPotentialWriteReadDeadlock() - if err != nil { - pgConn.asyncClose() - return nil, err - } - - psd := &StatementDescription{Name: name, SQL: sql} - - var parseErr error - -readloop: - for { - msg, err := pgConn.receiveMessage() - if err != nil { - pgConn.asyncClose() - return nil, normalizeTimeoutError(ctx, err) - } - - switch msg := msg.(type) { - case *pgproto3.ParameterDescription: - psd.ParamOIDs = make([]uint32, len(msg.ParameterOIDs)) - copy(psd.ParamOIDs, msg.ParameterOIDs) - case *pgproto3.RowDescription: - psd.Fields = pgConn.convertRowDescription(nil, msg) - case *pgproto3.ErrorResponse: - parseErr = ErrorResponseToPgError(msg) - case *pgproto3.ReadyForQuery: - break readloop - } - } - - if parseErr != nil { - return nil, parseErr - } - return psd, nil -} - -// Deallocate deallocates a prepared statement. -// -// Deallocate does not send a DEALLOCATE statement to the server. It uses the PostgreSQL Close protocol message -// directly. This has slightly different behavior than executing DEALLOCATE statement. -// - Deallocate can succeed in an aborted transaction. -// - Deallocating a non-existent prepared statement is not an error. -func (pgConn *PgConn) Deallocate(ctx context.Context, name string) error { - if err := pgConn.lock(); err != nil { - return err - } - defer pgConn.unlock() - - if ctx != context.Background() { - select { - case <-ctx.Done(): - return newContextAlreadyDoneError(ctx) - default: - } - pgConn.contextWatcher.Watch(ctx) - defer pgConn.contextWatcher.Unwatch() - } - - pgConn.frontend.SendClose(&pgproto3.Close{ObjectType: 'S', Name: name}) - pgConn.frontend.SendSync(&pgproto3.Sync{}) - err := pgConn.flushWithPotentialWriteReadDeadlock() - if err != nil { - pgConn.asyncClose() - return err - } - - for { - msg, err := pgConn.receiveMessage() - if err != nil { - pgConn.asyncClose() - return normalizeTimeoutError(ctx, err) - } - - switch msg := msg.(type) { - case *pgproto3.ErrorResponse: - return ErrorResponseToPgError(msg) - case *pgproto3.ReadyForQuery: - return nil - } - } -} - -// ErrorResponseToPgError converts a wire protocol error message to a *PgError. -func ErrorResponseToPgError(msg *pgproto3.ErrorResponse) *PgError { - return &PgError{ - Severity: msg.Severity, - SeverityUnlocalized: msg.SeverityUnlocalized, - Code: string(msg.Code), - Message: string(msg.Message), - Detail: string(msg.Detail), - Hint: msg.Hint, - Position: msg.Position, - InternalPosition: msg.InternalPosition, - InternalQuery: string(msg.InternalQuery), - Where: string(msg.Where), - SchemaName: string(msg.SchemaName), - TableName: string(msg.TableName), - ColumnName: string(msg.ColumnName), - DataTypeName: string(msg.DataTypeName), - ConstraintName: msg.ConstraintName, - File: string(msg.File), - Line: msg.Line, - Routine: string(msg.Routine), - } -} - -func noticeResponseToNotice(msg *pgproto3.NoticeResponse) *Notice { - pgerr := ErrorResponseToPgError((*pgproto3.ErrorResponse)(msg)) - return (*Notice)(pgerr) -} - -// CancelRequest sends a cancel request to the PostgreSQL server. It returns an error if unable to deliver the cancel -// request, but lack of an error does not ensure that the query was canceled. As specified in the documentation, there -// is no way to be sure a query was canceled. See https://www.postgresql.org/docs/11/protocol-flow.html#id-1.10.5.7.9 -func (pgConn *PgConn) CancelRequest(ctx context.Context) error { - // Open a cancellation request to the same server. The address is taken from the net.Conn directly instead of reusing - // the connection config. This is important in high availability configurations where fallback connections may be - // specified or DNS may be used to load balance. - serverAddr := pgConn.conn.RemoteAddr() - var serverNetwork string - var serverAddress string - if serverAddr.Network() == "unix" { - // for unix sockets, RemoteAddr() calls getpeername() which returns the name the - // server passed to bind(). For Postgres, this is always a relative path "./.s.PGSQL.5432" - // so connecting to it will fail. Fall back to the config's value - serverNetwork, serverAddress = NetworkAddress(pgConn.config.Host, pgConn.config.Port) - } else { - serverNetwork, serverAddress = serverAddr.Network(), serverAddr.String() - } - cancelConn, err := pgConn.config.DialFunc(ctx, serverNetwork, serverAddress) - if err != nil { - // In case of unix sockets, RemoteAddr() returns only the file part of the path. If the - // first connect failed, try the config. - if serverAddr.Network() != "unix" { - return err - } - serverNetwork, serverAddr := NetworkAddress(pgConn.config.Host, pgConn.config.Port) - cancelConn, err = pgConn.config.DialFunc(ctx, serverNetwork, serverAddr) - if err != nil { - return err - } - } - defer cancelConn.Close() - - if ctx != context.Background() { - contextWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: cancelConn}) - contextWatcher.Watch(ctx) - defer contextWatcher.Unwatch() - } - - buf := make([]byte, 16) - binary.BigEndian.PutUint32(buf[0:4], 16) - binary.BigEndian.PutUint32(buf[4:8], 80877102) - binary.BigEndian.PutUint32(buf[8:12], pgConn.pid) - binary.BigEndian.PutUint32(buf[12:16], pgConn.secretKey) - - if _, err := cancelConn.Write(buf); err != nil { - return fmt.Errorf("write to connection for cancellation: %w", err) - } - - // Wait for the cancel request to be acknowledged by the server. - // It copies the behavior of the libpq: https://github.com/postgres/postgres/blob/REL_16_0/src/interfaces/libpq/fe-connect.c#L4946-L4960 - _, _ = cancelConn.Read(buf) - - return nil -} - -// WaitForNotification waits for a LISTEN/NOTIFY message to be received. It returns an error if a notification was not -// received. -func (pgConn *PgConn) WaitForNotification(ctx context.Context) error { - if err := pgConn.lock(); err != nil { - return err - } - defer pgConn.unlock() - - if ctx != context.Background() { - select { - case <-ctx.Done(): - return newContextAlreadyDoneError(ctx) - default: - } - - pgConn.contextWatcher.Watch(ctx) - defer pgConn.contextWatcher.Unwatch() - } - - for { - msg, err := pgConn.receiveMessage() - if err != nil { - return normalizeTimeoutError(ctx, err) - } - - switch msg.(type) { - case *pgproto3.NotificationResponse: - return nil - } - } -} - -// Exec executes SQL via the PostgreSQL simple query protocol. SQL may contain multiple queries. Execution is -// implicitly wrapped in a transaction unless a transaction is already in progress or SQL contains transaction control -// statements. -// -// Prefer ExecParams unless executing arbitrary SQL that may contain multiple queries. -func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader { - if err := pgConn.lock(); err != nil { - return &MultiResultReader{ - closed: true, - err: err, - } - } - - pgConn.multiResultReader = MultiResultReader{ - pgConn: pgConn, - ctx: ctx, - } - multiResult := &pgConn.multiResultReader - if ctx != context.Background() { - select { - case <-ctx.Done(): - multiResult.closed = true - multiResult.err = newContextAlreadyDoneError(ctx) - pgConn.unlock() - return multiResult - default: - } - pgConn.contextWatcher.Watch(ctx) - } - - pgConn.frontend.SendQuery(&pgproto3.Query{String: sql}) - err := pgConn.flushWithPotentialWriteReadDeadlock() - if err != nil { - pgConn.asyncClose() - pgConn.contextWatcher.Unwatch() - multiResult.closed = true - multiResult.err = err - pgConn.unlock() - return multiResult - } - - return multiResult -} - -// ExecParams executes a command via the PostgreSQL extended query protocol. -// -// sql is a SQL command string. It may only contain one query. Parameter substitution is positional using $1, $2, $3, -// etc. -// -// paramValues are the parameter values. It must be encoded in the format given by paramFormats. -// -// paramOIDs is a slice of data type OIDs for paramValues. If paramOIDs is nil, the server will infer the data type for -// all parameters. Any paramOID element that is 0 that will cause the server to infer the data type for that parameter. -// ExecParams will panic if len(paramOIDs) is not 0, 1, or len(paramValues). -// -// paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or -// binary format. If paramFormats is nil all params are text format. ExecParams will panic if -// len(paramFormats) is not 0, 1, or len(paramValues). -// -// resultFormats is a slice of format codes determining for each result column whether it is encoded in text or -// binary format. If resultFormats is nil all results will be in text format. -// -// ResultReader must be closed before PgConn can be used again. -func (pgConn *PgConn) ExecParams(ctx context.Context, sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats []int16, resultFormats []int16) *ResultReader { - result := pgConn.execExtendedPrefix(ctx, paramValues) - if result.closed { - return result - } - - pgConn.frontend.SendParse(&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}) - pgConn.frontend.SendBind(&pgproto3.Bind{ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) - - pgConn.execExtendedSuffix(result) - - return result -} - -// ExecPrepared enqueues the execution of a prepared statement via the PostgreSQL extended query protocol. -// -// paramValues are the parameter values. It must be encoded in the format given by paramFormats. -// -// paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or -// binary format. If paramFormats is nil all params are text format. ExecPrepared will panic if -// len(paramFormats) is not 0, 1, or len(paramValues). -// -// resultFormats is a slice of format codes determining for each result column whether it is encoded in text or -// binary format. If resultFormats is nil all results will be in text format. -// -// ResultReader must be closed before PgConn can be used again. -func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramValues [][]byte, paramFormats []int16, resultFormats []int16) *ResultReader { - result := pgConn.execExtendedPrefix(ctx, paramValues) - if result.closed { - return result - } - - pgConn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) - - pgConn.execExtendedSuffix(result) - - return result -} - -func (pgConn *PgConn) execExtendedPrefix(ctx context.Context, paramValues [][]byte) *ResultReader { - pgConn.resultReader = ResultReader{ - pgConn: pgConn, - ctx: ctx, - } - result := &pgConn.resultReader - - if err := pgConn.lock(); err != nil { - result.concludeCommand(CommandTag{}, err) - result.closed = true - return result - } - - if len(paramValues) > math.MaxUint16 { - result.concludeCommand(CommandTag{}, fmt.Errorf("extended protocol limited to %v parameters", math.MaxUint16)) - result.closed = true - pgConn.unlock() - return result - } - - if ctx != context.Background() { - select { - case <-ctx.Done(): - result.concludeCommand(CommandTag{}, newContextAlreadyDoneError(ctx)) - result.closed = true - pgConn.unlock() - return result - default: - } - pgConn.contextWatcher.Watch(ctx) - } - - return result -} - -func (pgConn *PgConn) execExtendedSuffix(result *ResultReader) { - pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) - pgConn.frontend.SendExecute(&pgproto3.Execute{}) - pgConn.frontend.SendSync(&pgproto3.Sync{}) - - err := pgConn.flushWithPotentialWriteReadDeadlock() - if err != nil { - pgConn.asyncClose() - result.concludeCommand(CommandTag{}, err) - pgConn.contextWatcher.Unwatch() - result.closed = true - pgConn.unlock() - return - } - - result.readUntilRowDescription() -} - -// CopyTo executes the copy command sql and copies the results to w. -func (pgConn *PgConn) CopyTo(ctx context.Context, w io.Writer, sql string) (CommandTag, error) { - if err := pgConn.lock(); err != nil { - return CommandTag{}, err - } - - if ctx != context.Background() { - select { - case <-ctx.Done(): - pgConn.unlock() - return CommandTag{}, newContextAlreadyDoneError(ctx) - default: - } - pgConn.contextWatcher.Watch(ctx) - defer pgConn.contextWatcher.Unwatch() - } - - // Send copy to command - pgConn.frontend.SendQuery(&pgproto3.Query{String: sql}) - - err := pgConn.flushWithPotentialWriteReadDeadlock() - if err != nil { - pgConn.asyncClose() - pgConn.unlock() - return CommandTag{}, err - } - - // Read results - var commandTag CommandTag - var pgErr error - for { - msg, err := pgConn.receiveMessage() - if err != nil { - pgConn.asyncClose() - return CommandTag{}, normalizeTimeoutError(ctx, err) - } - - switch msg := msg.(type) { - case *pgproto3.CopyDone: - case *pgproto3.CopyData: - _, err := w.Write(msg.Data) - if err != nil { - pgConn.asyncClose() - return CommandTag{}, err - } - case *pgproto3.ReadyForQuery: - pgConn.unlock() - return commandTag, pgErr - case *pgproto3.CommandComplete: - commandTag = pgConn.makeCommandTag(msg.CommandTag) - case *pgproto3.ErrorResponse: - pgErr = ErrorResponseToPgError(msg) - } - } -} - -// CopyFrom executes the copy command sql and copies all of r to the PostgreSQL server. -// -// Note: context cancellation will only interrupt operations on the underlying PostgreSQL network connection. Reads on r -// could still block. -func (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (CommandTag, error) { - if err := pgConn.lock(); err != nil { - return CommandTag{}, err - } - defer pgConn.unlock() - - if ctx != context.Background() { - select { - case <-ctx.Done(): - return CommandTag{}, newContextAlreadyDoneError(ctx) - default: - } - pgConn.contextWatcher.Watch(ctx) - defer pgConn.contextWatcher.Unwatch() - } - - // Send copy from query - pgConn.frontend.SendQuery(&pgproto3.Query{String: sql}) - err := pgConn.flushWithPotentialWriteReadDeadlock() - if err != nil { - pgConn.asyncClose() - return CommandTag{}, err - } - - // Send copy data - abortCopyChan := make(chan struct{}) - copyErrChan := make(chan error, 1) - signalMessageChan := pgConn.signalMessage() - var wg sync.WaitGroup - wg.Add(1) - - go func() { - defer wg.Done() - buf := iobufpool.Get(65536) - defer iobufpool.Put(buf) - (*buf)[0] = 'd' - - for { - n, readErr := r.Read((*buf)[5:cap(*buf)]) - if n > 0 { - *buf = (*buf)[0 : n+5] - pgio.SetInt32((*buf)[1:], int32(n+4)) - - writeErr := pgConn.frontend.SendUnbufferedEncodedCopyData(*buf) - if writeErr != nil { - // Write errors are always fatal, but we can't use asyncClose because we are in a different goroutine. Not - // setting pgConn.status or closing pgConn.cleanupDone for the same reason. - pgConn.conn.Close() - - copyErrChan <- writeErr - return - } - } - if readErr != nil { - copyErrChan <- readErr - return - } - - select { - case <-abortCopyChan: - return - default: - } - } - }() - - var pgErr error - var copyErr error - for copyErr == nil && pgErr == nil { - select { - case copyErr = <-copyErrChan: - case <-signalMessageChan: - // If pgConn.receiveMessage encounters an error it will call pgConn.asyncClose. But that is a race condition with - // the goroutine. So instead check pgConn.bufferingReceiveErr which will have been set by the signalMessage. If an - // error is found then forcibly close the connection without sending the Terminate message. - if err := pgConn.bufferingReceiveErr; err != nil { - pgConn.status = connStatusClosed - pgConn.conn.Close() - close(pgConn.cleanupDone) - return CommandTag{}, normalizeTimeoutError(ctx, err) - } - msg, _ := pgConn.receiveMessage() - - switch msg := msg.(type) { - case *pgproto3.ErrorResponse: - pgErr = ErrorResponseToPgError(msg) - default: - signalMessageChan = pgConn.signalMessage() - } - } - } - close(abortCopyChan) - // Make sure io goroutine finishes before writing. - wg.Wait() - - if copyErr == io.EOF || pgErr != nil { - pgConn.frontend.Send(&pgproto3.CopyDone{}) - } else { - pgConn.frontend.Send(&pgproto3.CopyFail{Message: copyErr.Error()}) - } - err = pgConn.flushWithPotentialWriteReadDeadlock() - if err != nil { - pgConn.asyncClose() - return CommandTag{}, err - } - - // Read results - var commandTag CommandTag - for { - msg, err := pgConn.receiveMessage() - if err != nil { - pgConn.asyncClose() - return CommandTag{}, normalizeTimeoutError(ctx, err) - } - - switch msg := msg.(type) { - case *pgproto3.ReadyForQuery: - return commandTag, pgErr - case *pgproto3.CommandComplete: - commandTag = pgConn.makeCommandTag(msg.CommandTag) - case *pgproto3.ErrorResponse: - pgErr = ErrorResponseToPgError(msg) - } - } -} - -// MultiResultReader is a reader for a command that could return multiple results such as Exec or ExecBatch. -type MultiResultReader struct { - pgConn *PgConn - ctx context.Context - pipeline *Pipeline - - rr *ResultReader - - closed bool - err error -} - -// ReadAll reads all available results. Calling ReadAll is mutually exclusive with all other MultiResultReader methods. -func (mrr *MultiResultReader) ReadAll() ([]*Result, error) { - var results []*Result - - for mrr.NextResult() { - results = append(results, mrr.ResultReader().Read()) - } - err := mrr.Close() - - return results, err -} - -func (mrr *MultiResultReader) receiveMessage() (pgproto3.BackendMessage, error) { - msg, err := mrr.pgConn.receiveMessage() - if err != nil { - mrr.pgConn.contextWatcher.Unwatch() - mrr.err = normalizeTimeoutError(mrr.ctx, err) - mrr.closed = true - mrr.pgConn.asyncClose() - return nil, mrr.err - } - - switch msg := msg.(type) { - case *pgproto3.ReadyForQuery: - mrr.closed = true - if mrr.pipeline != nil { - mrr.pipeline.expectedReadyForQueryCount-- - } else { - mrr.pgConn.contextWatcher.Unwatch() - mrr.pgConn.unlock() - } - case *pgproto3.ErrorResponse: - mrr.err = ErrorResponseToPgError(msg) - } - - return msg, nil -} - -// NextResult returns advances the MultiResultReader to the next result and returns true if a result is available. -func (mrr *MultiResultReader) NextResult() bool { - for !mrr.closed && mrr.err == nil { - msg, err := mrr.receiveMessage() - if err != nil { - return false - } - - switch msg := msg.(type) { - case *pgproto3.RowDescription: - mrr.pgConn.resultReader = ResultReader{ - pgConn: mrr.pgConn, - multiResultReader: mrr, - ctx: mrr.ctx, - fieldDescriptions: mrr.pgConn.convertRowDescription(mrr.pgConn.fieldDescriptions[:], msg), - } - - mrr.rr = &mrr.pgConn.resultReader - return true - case *pgproto3.CommandComplete: - mrr.pgConn.resultReader = ResultReader{ - commandTag: mrr.pgConn.makeCommandTag(msg.CommandTag), - commandConcluded: true, - closed: true, - } - mrr.rr = &mrr.pgConn.resultReader - return true - case *pgproto3.EmptyQueryResponse: - return false - } - } - - return false -} - -// ResultReader returns the current ResultReader. -func (mrr *MultiResultReader) ResultReader() *ResultReader { - return mrr.rr -} - -// Close closes the MultiResultReader and returns the first error that occurred during the MultiResultReader's use. -func (mrr *MultiResultReader) Close() error { - for !mrr.closed { - _, err := mrr.receiveMessage() - if err != nil { - return mrr.err - } - } - - return mrr.err -} - -// ResultReader is a reader for the result of a single query. -type ResultReader struct { - pgConn *PgConn - multiResultReader *MultiResultReader - pipeline *Pipeline - ctx context.Context - - fieldDescriptions []FieldDescription - rowValues [][]byte - commandTag CommandTag - commandConcluded bool - closed bool - err error -} - -// Result is the saved query response that is returned by calling Read on a ResultReader. -type Result struct { - FieldDescriptions []FieldDescription - Rows [][][]byte - CommandTag CommandTag - Err error -} - -// Read saves the query response to a Result. -func (rr *ResultReader) Read() *Result { - br := &Result{} - - for rr.NextRow() { - if br.FieldDescriptions == nil { - br.FieldDescriptions = make([]FieldDescription, len(rr.FieldDescriptions())) - copy(br.FieldDescriptions, rr.FieldDescriptions()) - } - - values := rr.Values() - row := make([][]byte, len(values)) - for i := range row { - if values[i] != nil { - row[i] = make([]byte, len(values[i])) - copy(row[i], values[i]) - } - } - br.Rows = append(br.Rows, row) - } - - br.CommandTag, br.Err = rr.Close() - - return br -} - -// NextRow advances the ResultReader to the next row and returns true if a row is available. -func (rr *ResultReader) NextRow() bool { - for !rr.commandConcluded { - msg, err := rr.receiveMessage() - if err != nil { - return false - } - - switch msg := msg.(type) { - case *pgproto3.DataRow: - rr.rowValues = msg.Values - return true - } - } - - return false -} - -// FieldDescriptions returns the field descriptions for the current result set. The returned slice is only valid until -// the ResultReader is closed. It may return nil (for example, if the query did not return a result set or an error was -// encountered.) -func (rr *ResultReader) FieldDescriptions() []FieldDescription { - return rr.fieldDescriptions -} - -// Values returns the current row data. NextRow must have been previously been called. The returned [][]byte is only -// valid until the next NextRow call or the ResultReader is closed. -func (rr *ResultReader) Values() [][]byte { - return rr.rowValues -} - -// Close consumes any remaining result data and returns the command tag or -// error. -func (rr *ResultReader) Close() (CommandTag, error) { - if rr.closed { - return rr.commandTag, rr.err - } - rr.closed = true - - for !rr.commandConcluded { - _, err := rr.receiveMessage() - if err != nil { - return CommandTag{}, rr.err - } - } - - if rr.multiResultReader == nil && rr.pipeline == nil { - for { - msg, err := rr.receiveMessage() - if err != nil { - return CommandTag{}, rr.err - } - - switch msg := msg.(type) { - // Detect a deferred constraint violation where the ErrorResponse is sent after CommandComplete. - case *pgproto3.ErrorResponse: - rr.err = ErrorResponseToPgError(msg) - case *pgproto3.ReadyForQuery: - rr.pgConn.contextWatcher.Unwatch() - rr.pgConn.unlock() - return rr.commandTag, rr.err - } - } - } - - return rr.commandTag, rr.err -} - -// readUntilRowDescription ensures the ResultReader's fieldDescriptions are loaded. It does not return an error as any -// error will be stored in the ResultReader. -func (rr *ResultReader) readUntilRowDescription() { - for !rr.commandConcluded { - // Peek before receive to avoid consuming a DataRow if the result set does not include a RowDescription method. - // This should never happen under normal pgconn usage, but it is possible if SendBytes and ReceiveResults are - // manually used to construct a query that does not issue a describe statement. - msg, _ := rr.pgConn.peekMessage() - if _, ok := msg.(*pgproto3.DataRow); ok { - return - } - - // Consume the message - msg, _ = rr.receiveMessage() - if _, ok := msg.(*pgproto3.RowDescription); ok { - return - } - } -} - -func (rr *ResultReader) receiveMessage() (msg pgproto3.BackendMessage, err error) { - if rr.multiResultReader == nil { - msg, err = rr.pgConn.receiveMessage() - } else { - msg, err = rr.multiResultReader.receiveMessage() - } - - if err != nil { - err = normalizeTimeoutError(rr.ctx, err) - rr.concludeCommand(CommandTag{}, err) - rr.pgConn.contextWatcher.Unwatch() - rr.closed = true - if rr.multiResultReader == nil { - rr.pgConn.asyncClose() - } - - return nil, rr.err - } - - switch msg := msg.(type) { - case *pgproto3.RowDescription: - rr.fieldDescriptions = rr.pgConn.convertRowDescription(rr.pgConn.fieldDescriptions[:], msg) - case *pgproto3.CommandComplete: - rr.concludeCommand(rr.pgConn.makeCommandTag(msg.CommandTag), nil) - case *pgproto3.EmptyQueryResponse: - rr.concludeCommand(CommandTag{}, nil) - case *pgproto3.ErrorResponse: - rr.concludeCommand(CommandTag{}, ErrorResponseToPgError(msg)) - } - - return msg, nil -} - -func (rr *ResultReader) concludeCommand(commandTag CommandTag, err error) { - // Keep the first error that is recorded. Store the error before checking if the command is already concluded to - // allow for receiving an error after CommandComplete but before ReadyForQuery. - if err != nil && rr.err == nil { - rr.err = err - } - - if rr.commandConcluded { - return - } - - rr.commandTag = commandTag - rr.rowValues = nil - rr.commandConcluded = true -} - -// Batch is a collection of queries that can be sent to the PostgreSQL server in a single round-trip. -type Batch struct { - buf []byte - err error -} - -// ExecParams appends an ExecParams command to the batch. See PgConn.ExecParams for parameter descriptions. -func (batch *Batch) ExecParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats []int16, resultFormats []int16) { - if batch.err != nil { - return - } - - batch.buf, batch.err = (&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}).Encode(batch.buf) - if batch.err != nil { - return - } - batch.ExecPrepared("", paramValues, paramFormats, resultFormats) -} - -// ExecPrepared appends an ExecPrepared e command to the batch. See PgConn.ExecPrepared for parameter descriptions. -func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFormats []int16, resultFormats []int16) { - if batch.err != nil { - return - } - - batch.buf, batch.err = (&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}).Encode(batch.buf) - if batch.err != nil { - return - } - - batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf) - if batch.err != nil { - return - } - - batch.buf, batch.err = (&pgproto3.Execute{}).Encode(batch.buf) - if batch.err != nil { - return - } -} - -// ExecBatch executes all the queries in batch in a single round-trip. Execution is implicitly transactional unless a -// transaction is already in progress or SQL contains transaction control statements. This is a simpler way of executing -// multiple queries in a single round trip than using pipeline mode. -func (pgConn *PgConn) ExecBatch(ctx context.Context, batch *Batch) *MultiResultReader { - if batch.err != nil { - return &MultiResultReader{ - closed: true, - err: batch.err, - } - } - - if err := pgConn.lock(); err != nil { - return &MultiResultReader{ - closed: true, - err: err, - } - } - - pgConn.multiResultReader = MultiResultReader{ - pgConn: pgConn, - ctx: ctx, - } - multiResult := &pgConn.multiResultReader - - if ctx != context.Background() { - select { - case <-ctx.Done(): - multiResult.closed = true - multiResult.err = newContextAlreadyDoneError(ctx) - pgConn.unlock() - return multiResult - default: - } - pgConn.contextWatcher.Watch(ctx) - } - - batch.buf, batch.err = (&pgproto3.Sync{}).Encode(batch.buf) - if batch.err != nil { - multiResult.closed = true - multiResult.err = batch.err - pgConn.unlock() - return multiResult - } - - pgConn.enterPotentialWriteReadDeadlock() - defer pgConn.exitPotentialWriteReadDeadlock() - _, err := pgConn.conn.Write(batch.buf) - if err != nil { - multiResult.closed = true - multiResult.err = err - pgConn.unlock() - return multiResult - } - - return multiResult -} - -// EscapeString escapes a string such that it can safely be interpolated into a SQL command string. It does not include -// the surrounding single quotes. -// -// The current implementation requires that standard_conforming_strings=on and client_encoding="UTF8". If these -// conditions are not met an error will be returned. It is possible these restrictions will be lifted in the future. -func (pgConn *PgConn) EscapeString(s string) (string, error) { - if pgConn.ParameterStatus("standard_conforming_strings") != "on" { - return "", errors.New("EscapeString must be run with standard_conforming_strings=on") - } - - if pgConn.ParameterStatus("client_encoding") != "UTF8" { - return "", errors.New("EscapeString must be run with client_encoding=UTF8") - } - - return strings.Replace(s, "'", "''", -1), nil -} - -// CheckConn checks the underlying connection without writing any bytes. This is currently implemented by doing a read -// with a very short deadline. This can be useful because a TCP connection can be broken such that a write will appear -// to succeed even though it will never actually reach the server. Reading immediately before a write will detect this -// condition. If this is done immediately before sending a query it reduces the chances a query will be sent that fails -// without the client knowing whether the server received it or not. -// -// Deprecated: CheckConn is deprecated in favor of Ping. CheckConn cannot detect all types of broken connections where -// the write would still appear to succeed. Prefer Ping unless on a high latency connection. -func (pgConn *PgConn) CheckConn() error { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) - defer cancel() - - _, err := pgConn.ReceiveMessage(ctx) - if err != nil { - if !Timeout(err) { - return err - } - } - - return nil -} - -// Ping pings the server. This can be useful because a TCP connection can be broken such that a write will appear to -// succeed even though it will never actually reach the server. Pinging immediately before sending a query reduces the -// chances a query will be sent that fails without the client knowing whether the server received it or not. -func (pgConn *PgConn) Ping(ctx context.Context) error { - return pgConn.Exec(ctx, "-- ping").Close() -} - -// makeCommandTag makes a CommandTag. It does not retain a reference to buf or buf's underlying memory. -func (pgConn *PgConn) makeCommandTag(buf []byte) CommandTag { - return CommandTag{s: string(buf)} -} - -// enterPotentialWriteReadDeadlock must be called before a write that could deadlock if the server is simultaneously -// blocked writing to us. -func (pgConn *PgConn) enterPotentialWriteReadDeadlock() { - // The time to wait is somewhat arbitrary. A Write should only take as long as the syscall and memcpy to the OS - // outbound network buffer unless the buffer is full (which potentially is a block). It needs to be long enough for - // the normal case, but short enough not to kill performance if a block occurs. - // - // In addition, on Windows the default timer resolution is 15.6ms. So setting the timer to less than that is - // ineffective. - if pgConn.slowWriteTimer.Reset(15 * time.Millisecond) { - panic("BUG: slow write timer already active") - } -} - -// exitPotentialWriteReadDeadlock must be called after a call to enterPotentialWriteReadDeadlock. -func (pgConn *PgConn) exitPotentialWriteReadDeadlock() { - if !pgConn.slowWriteTimer.Stop() { - // The timer starts its function in a separate goroutine. It is necessary to ensure the background reader has - // started before calling Stop. Otherwise, the background reader may not be stopped. That on its own is not a - // serious problem. But what is a serious problem is that the background reader may start at an inopportune time in - // a subsequent query. For example, if a subsequent query was canceled then a deadline may be set on the net.Conn to - // interrupt an in-progress read. After the read is interrupted, but before the deadline is cleared, the background - // reader could start and read a deadline error. Then the next query would receive the an unexpected deadline error. - <-pgConn.bgReaderStarted - pgConn.bgReader.Stop() - } -} - -func (pgConn *PgConn) flushWithPotentialWriteReadDeadlock() error { - pgConn.enterPotentialWriteReadDeadlock() - defer pgConn.exitPotentialWriteReadDeadlock() - err := pgConn.frontend.Flush() - return err -} - -// SyncConn prepares the underlying net.Conn for direct use. PgConn may internally buffer reads or use goroutines for -// background IO. This means that any direct use of the underlying net.Conn may be corrupted if a read is already -// buffered or a read is in progress. SyncConn drains read buffers and stops background IO. In some cases this may -// require sending a ping to the server. ctx can be used to cancel this operation. This should be called before any -// operation that will use the underlying net.Conn directly. e.g. Before Conn() or Hijack(). -// -// This should not be confused with the PostgreSQL protocol Sync message. -func (pgConn *PgConn) SyncConn(ctx context.Context) error { - for i := 0; i < 10; i++ { - if pgConn.bgReader.Status() == bgreader.StatusStopped && pgConn.frontend.ReadBufferLen() == 0 { - return nil - } - - err := pgConn.Ping(ctx) - if err != nil { - return fmt.Errorf("SyncConn: Ping failed while syncing conn: %w", err) - } - } - - // This should never happen. Only way I can imagine this occurring is if the server is constantly sending data such as - // LISTEN/NOTIFY or log notifications such that we never can get an empty buffer. - return errors.New("SyncConn: conn never synchronized") -} - -// CustomData returns a map that can be used to associate custom data with the connection. -func (pgConn *PgConn) CustomData() map[string]any { - return pgConn.customData -} - -// HijackedConn is the result of hijacking a connection. -// -// Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning -// compatibility. -type HijackedConn struct { - Conn net.Conn - PID uint32 // backend pid - SecretKey uint32 // key to use to send a cancel query message to the server - ParameterStatuses map[string]string // parameters that have been reported by the server - TxStatus byte - Frontend *pgproto3.Frontend - Config *Config - CustomData map[string]any -} - -// Hijack extracts the internal connection data. pgConn must be in an idle state. SyncConn should be called immediately -// before Hijack. pgConn is unusable after hijacking. Hijacking is typically only useful when using pgconn to establish -// a connection, but taking complete control of the raw connection after that (e.g. a load balancer or proxy). -// -// Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning -// compatibility. -func (pgConn *PgConn) Hijack() (*HijackedConn, error) { - if err := pgConn.lock(); err != nil { - return nil, err - } - pgConn.status = connStatusClosed - - return &HijackedConn{ - Conn: pgConn.conn, - PID: pgConn.pid, - SecretKey: pgConn.secretKey, - ParameterStatuses: pgConn.parameterStatuses, - TxStatus: pgConn.txStatus, - Frontend: pgConn.frontend, - Config: pgConn.config, - CustomData: pgConn.customData, - }, nil -} - -// Construct created a PgConn from an already established connection to a PostgreSQL server. This is the inverse of -// PgConn.Hijack. The connection must be in an idle state. -// -// hc.Frontend is replaced by a new pgproto3.Frontend built by hc.Config.BuildFrontend. -// -// Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning -// compatibility. -func Construct(hc *HijackedConn) (*PgConn, error) { - pgConn := &PgConn{ - conn: hc.Conn, - pid: hc.PID, - secretKey: hc.SecretKey, - parameterStatuses: hc.ParameterStatuses, - txStatus: hc.TxStatus, - frontend: hc.Frontend, - config: hc.Config, - customData: hc.CustomData, - - status: connStatusIdle, - - cleanupDone: make(chan struct{}), - } - - pgConn.contextWatcher = ctxwatch.NewContextWatcher(hc.Config.BuildContextWatcherHandler(pgConn)) - pgConn.bgReader = bgreader.New(pgConn.conn) - pgConn.slowWriteTimer = time.AfterFunc(time.Duration(math.MaxInt64), - func() { - pgConn.bgReader.Start() - pgConn.bgReaderStarted <- struct{}{} - }, - ) - pgConn.slowWriteTimer.Stop() - pgConn.bgReaderStarted = make(chan struct{}) - pgConn.frontend = hc.Config.BuildFrontend(pgConn.bgReader, pgConn.conn) - - return pgConn, nil -} - -// Pipeline represents a connection in pipeline mode. -// -// SendPrepare, SendQueryParams, and SendQueryPrepared queue requests to the server. These requests are not written until -// pipeline is flushed by Flush or Sync. Sync must be called after the last request is queued. Requests between -// synchronization points are implicitly transactional unless explicit transaction control statements have been issued. -// -// The context the pipeline was started with is in effect for the entire life of the Pipeline. -// -// For a deeper understanding of pipeline mode see the PostgreSQL documentation for the extended query protocol -// (https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) and the libpq pipeline mode -// (https://www.postgresql.org/docs/current/libpq-pipeline-mode.html). -type Pipeline struct { - conn *PgConn - ctx context.Context - - expectedReadyForQueryCount int - pendingSync bool - - err error - closed bool -} - -// PipelineSync is returned by GetResults when a ReadyForQuery message is received. -type PipelineSync struct{} - -// CloseComplete is returned by GetResults when a CloseComplete message is received. -type CloseComplete struct{} - -// StartPipeline switches the connection to pipeline mode and returns a *Pipeline. In pipeline mode requests can be sent -// to the server without waiting for a response. Close must be called on the returned *Pipeline to return the connection -// to normal mode. While in pipeline mode, no methods that communicate with the server may be called except -// CancelRequest and Close. ctx is in effect for entire life of the *Pipeline. -// -// Prefer ExecBatch when only sending one group of queries at once. -func (pgConn *PgConn) StartPipeline(ctx context.Context) *Pipeline { - if err := pgConn.lock(); err != nil { - return &Pipeline{ - closed: true, - err: err, - } - } - - pgConn.pipeline = Pipeline{ - conn: pgConn, - ctx: ctx, - } - pipeline := &pgConn.pipeline - - if ctx != context.Background() { - select { - case <-ctx.Done(): - pipeline.closed = true - pipeline.err = newContextAlreadyDoneError(ctx) - pgConn.unlock() - return pipeline - default: - } - pgConn.contextWatcher.Watch(ctx) - } - - return pipeline -} - -// SendPrepare is the pipeline version of *PgConn.Prepare. -func (p *Pipeline) SendPrepare(name, sql string, paramOIDs []uint32) { - if p.closed { - return - } - p.pendingSync = true - - p.conn.frontend.SendParse(&pgproto3.Parse{Name: name, Query: sql, ParameterOIDs: paramOIDs}) - p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'S', Name: name}) -} - -// SendDeallocate deallocates a prepared statement. -func (p *Pipeline) SendDeallocate(name string) { - if p.closed { - return - } - p.pendingSync = true - - p.conn.frontend.SendClose(&pgproto3.Close{ObjectType: 'S', Name: name}) -} - -// SendQueryParams is the pipeline version of *PgConn.QueryParams. -func (p *Pipeline) SendQueryParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats []int16, resultFormats []int16) { - if p.closed { - return - } - p.pendingSync = true - - p.conn.frontend.SendParse(&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}) - p.conn.frontend.SendBind(&pgproto3.Bind{ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) - p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) - p.conn.frontend.SendExecute(&pgproto3.Execute{}) -} - -// SendQueryPrepared is the pipeline version of *PgConn.QueryPrepared. -func (p *Pipeline) SendQueryPrepared(stmtName string, paramValues [][]byte, paramFormats []int16, resultFormats []int16) { - if p.closed { - return - } - p.pendingSync = true - - p.conn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) - p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) - p.conn.frontend.SendExecute(&pgproto3.Execute{}) -} - -// Flush flushes the queued requests without establishing a synchronization point. -func (p *Pipeline) Flush() error { - if p.closed { - if p.err != nil { - return p.err - } - return errors.New("pipeline closed") - } - - err := p.conn.flushWithPotentialWriteReadDeadlock() - if err != nil { - err = normalizeTimeoutError(p.ctx, err) - - p.conn.asyncClose() - - p.conn.contextWatcher.Unwatch() - p.conn.unlock() - p.closed = true - p.err = err - return err - } - - return nil -} - -// Sync establishes a synchronization point and flushes the queued requests. -func (p *Pipeline) Sync() error { - if p.closed { - if p.err != nil { - return p.err - } - return errors.New("pipeline closed") - } - - p.conn.frontend.SendSync(&pgproto3.Sync{}) - err := p.Flush() - if err != nil { - return err - } - - p.pendingSync = false - p.expectedReadyForQueryCount++ - - return nil -} - -// GetResults gets the next results. If results are present, results may be a *ResultReader, *StatementDescription, or -// *PipelineSync. If an ErrorResponse is received from the server, results will be nil and err will be a *PgError. If no -// results are available, results and err will both be nil. -func (p *Pipeline) GetResults() (results any, err error) { - if p.closed { - if p.err != nil { - return nil, p.err - } - return nil, errors.New("pipeline closed") - } - - if p.expectedReadyForQueryCount == 0 { - return nil, nil - } - - return p.getResults() -} - -func (p *Pipeline) getResults() (results any, err error) { - for { - msg, err := p.conn.receiveMessage() - if err != nil { - p.closed = true - p.err = err - p.conn.asyncClose() - return nil, normalizeTimeoutError(p.ctx, err) - } - - switch msg := msg.(type) { - case *pgproto3.RowDescription: - p.conn.resultReader = ResultReader{ - pgConn: p.conn, - pipeline: p, - ctx: p.ctx, - fieldDescriptions: p.conn.convertRowDescription(p.conn.fieldDescriptions[:], msg), - } - return &p.conn.resultReader, nil - case *pgproto3.CommandComplete: - p.conn.resultReader = ResultReader{ - commandTag: p.conn.makeCommandTag(msg.CommandTag), - commandConcluded: true, - closed: true, - } - return &p.conn.resultReader, nil - case *pgproto3.ParseComplete: - peekedMsg, err := p.conn.peekMessage() - if err != nil { - p.conn.asyncClose() - return nil, normalizeTimeoutError(p.ctx, err) - } - if _, ok := peekedMsg.(*pgproto3.ParameterDescription); ok { - return p.getResultsPrepare() - } - case *pgproto3.CloseComplete: - return &CloseComplete{}, nil - case *pgproto3.ReadyForQuery: - p.expectedReadyForQueryCount-- - return &PipelineSync{}, nil - case *pgproto3.ErrorResponse: - pgErr := ErrorResponseToPgError(msg) - return nil, pgErr - } - - } -} - -func (p *Pipeline) getResultsPrepare() (*StatementDescription, error) { - psd := &StatementDescription{} - - for { - msg, err := p.conn.receiveMessage() - if err != nil { - p.conn.asyncClose() - return nil, normalizeTimeoutError(p.ctx, err) - } - - switch msg := msg.(type) { - case *pgproto3.ParameterDescription: - psd.ParamOIDs = make([]uint32, len(msg.ParameterOIDs)) - copy(psd.ParamOIDs, msg.ParameterOIDs) - case *pgproto3.RowDescription: - psd.Fields = p.conn.convertRowDescription(nil, msg) - return psd, nil - - // NoData is returned instead of RowDescription when there is no expected result. e.g. An INSERT without a RETURNING - // clause. - case *pgproto3.NoData: - return psd, nil - - // These should never happen here. But don't take chances that could lead to a deadlock. - case *pgproto3.ErrorResponse: - pgErr := ErrorResponseToPgError(msg) - return nil, pgErr - case *pgproto3.CommandComplete: - p.conn.asyncClose() - return nil, errors.New("BUG: received CommandComplete while handling Describe") - case *pgproto3.ReadyForQuery: - p.conn.asyncClose() - return nil, errors.New("BUG: received ReadyForQuery while handling Describe") - } - } -} - -// Close closes the pipeline and returns the connection to normal mode. -func (p *Pipeline) Close() error { - if p.closed { - return p.err - } - - p.closed = true - - if p.pendingSync { - p.conn.asyncClose() - p.err = errors.New("pipeline has unsynced requests") - p.conn.contextWatcher.Unwatch() - p.conn.unlock() - - return p.err - } - - for p.expectedReadyForQueryCount > 0 { - _, err := p.getResults() - if err != nil { - p.err = err - var pgErr *PgError - if !errors.As(err, &pgErr) { - p.conn.asyncClose() - break - } - } - } - - p.conn.contextWatcher.Unwatch() - p.conn.unlock() - - return p.err -} - -// DeadlineContextWatcherHandler handles canceled contexts by setting a deadline on a net.Conn. -type DeadlineContextWatcherHandler struct { - Conn net.Conn - - // DeadlineDelay is the delay to set on the deadline set on net.Conn when the context is canceled. - DeadlineDelay time.Duration -} - -func (h *DeadlineContextWatcherHandler) HandleCancel(ctx context.Context) { - h.Conn.SetDeadline(time.Now().Add(h.DeadlineDelay)) -} - -func (h *DeadlineContextWatcherHandler) HandleUnwatchAfterCancel() { - h.Conn.SetDeadline(time.Time{}) -} - -// CancelRequestContextWatcherHandler handles canceled contexts by sending a cancel request to the server. It also sets -// a deadline on a net.Conn as a fallback. -type CancelRequestContextWatcherHandler struct { - Conn *PgConn - - // CancelRequestDelay is the delay before sending the cancel request to the server. - CancelRequestDelay time.Duration - - // DeadlineDelay is the delay to set on the deadline set on net.Conn when the context is canceled. - DeadlineDelay time.Duration - - cancelFinishedChan chan struct{} - handleUnwatchAfterCancelCalled func() -} - -func (h *CancelRequestContextWatcherHandler) HandleCancel(context.Context) { - h.cancelFinishedChan = make(chan struct{}) - var handleUnwatchedAfterCancelCalledCtx context.Context - handleUnwatchedAfterCancelCalledCtx, h.handleUnwatchAfterCancelCalled = context.WithCancel(context.Background()) - - deadline := time.Now().Add(h.DeadlineDelay) - h.Conn.conn.SetDeadline(deadline) - - go func() { - defer close(h.cancelFinishedChan) - - select { - case <-handleUnwatchedAfterCancelCalledCtx.Done(): - return - case <-time.After(h.CancelRequestDelay): - } - - cancelRequestCtx, cancel := context.WithDeadline(handleUnwatchedAfterCancelCalledCtx, deadline) - defer cancel() - h.Conn.CancelRequest(cancelRequestCtx) - - // CancelRequest is inherently racy. Even though the cancel request has been received by the server at this point, - // it hasn't necessarily been delivered to the other connection. If we immediately return and the connection is - // immediately used then it is possible the CancelRequest will actually cancel our next query. The - // TestCancelRequestContextWatcherHandler Stress test can produce this error without the sleep below. The sleep time - // is arbitrary, but should be sufficient to prevent this error case. - time.Sleep(100 * time.Millisecond) - }() -} - -func (h *CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel() { - h.handleUnwatchAfterCancelCalled() - <-h.cancelFinishedChan - - h.Conn.conn.SetDeadline(time.Time{}) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/README.md b/vendor/github.com/jackc/pgx/v5/pgproto3/README.md deleted file mode 100644 index 7a26f1cbd..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# pgproto3 - -Package pgproto3 is an encoder and decoder of the PostgreSQL wire protocol version 3. - -pgproto3 can be used as a foundation for PostgreSQL drivers, proxies, mock servers, load balancers and more. - -See example/pgfortune for a playful example of a fake PostgreSQL server. diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_cleartext_password.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_cleartext_password.go deleted file mode 100644 index ac2962e9e..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_cleartext_password.go +++ /dev/null @@ -1,51 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// AuthenticationCleartextPassword is a message sent from the backend indicating that a clear-text password is required. -type AuthenticationCleartextPassword struct { -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*AuthenticationCleartextPassword) Backend() {} - -// Backend identifies this message as an authentication response. -func (*AuthenticationCleartextPassword) AuthenticationResponse() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *AuthenticationCleartextPassword) Decode(src []byte) error { - if len(src) != 4 { - return errors.New("bad authentication message size") - } - - authType := binary.BigEndian.Uint32(src) - - if authType != AuthTypeCleartextPassword { - return errors.New("bad auth type") - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationCleartextPassword) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'R') - dst = pgio.AppendUint32(dst, AuthTypeCleartextPassword) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src AuthenticationCleartextPassword) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "AuthenticationCleartextPassword", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss.go deleted file mode 100644 index 178ef31d8..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss.go +++ /dev/null @@ -1,58 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type AuthenticationGSS struct{} - -func (a *AuthenticationGSS) Backend() {} - -func (a *AuthenticationGSS) AuthenticationResponse() {} - -func (a *AuthenticationGSS) Decode(src []byte) error { - if len(src) < 4 { - return errors.New("authentication message too short") - } - - authType := binary.BigEndian.Uint32(src) - - if authType != AuthTypeGSS { - return errors.New("bad auth type") - } - return nil -} - -func (a *AuthenticationGSS) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'R') - dst = pgio.AppendUint32(dst, AuthTypeGSS) - return finishMessage(dst, sp) -} - -func (a *AuthenticationGSS) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Data []byte - }{ - Type: "AuthenticationGSS", - }) -} - -func (a *AuthenticationGSS) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Type string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss_continue.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss_continue.go deleted file mode 100644 index 2ba3f3b3e..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_gss_continue.go +++ /dev/null @@ -1,67 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type AuthenticationGSSContinue struct { - Data []byte -} - -func (a *AuthenticationGSSContinue) Backend() {} - -func (a *AuthenticationGSSContinue) AuthenticationResponse() {} - -func (a *AuthenticationGSSContinue) Decode(src []byte) error { - if len(src) < 4 { - return errors.New("authentication message too short") - } - - authType := binary.BigEndian.Uint32(src) - - if authType != AuthTypeGSSCont { - return errors.New("bad auth type") - } - - a.Data = src[4:] - return nil -} - -func (a *AuthenticationGSSContinue) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'R') - dst = pgio.AppendUint32(dst, AuthTypeGSSCont) - dst = append(dst, a.Data...) - return finishMessage(dst, sp) -} - -func (a *AuthenticationGSSContinue) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Data []byte - }{ - Type: "AuthenticationGSSContinue", - Data: a.Data, - }) -} - -func (a *AuthenticationGSSContinue) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Type string - Data []byte - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - a.Data = msg.Data - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_md5_password.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_md5_password.go deleted file mode 100644 index 854c6404e..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_md5_password.go +++ /dev/null @@ -1,76 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// AuthenticationMD5Password is a message sent from the backend indicating that an MD5 hashed password is required. -type AuthenticationMD5Password struct { - Salt [4]byte -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*AuthenticationMD5Password) Backend() {} - -// Backend identifies this message as an authentication response. -func (*AuthenticationMD5Password) AuthenticationResponse() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *AuthenticationMD5Password) Decode(src []byte) error { - if len(src) != 8 { - return errors.New("bad authentication message size") - } - - authType := binary.BigEndian.Uint32(src) - - if authType != AuthTypeMD5Password { - return errors.New("bad auth type") - } - - copy(dst.Salt[:], src[4:8]) - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationMD5Password) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'R') - dst = pgio.AppendUint32(dst, AuthTypeMD5Password) - dst = append(dst, src.Salt[:]...) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src AuthenticationMD5Password) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Salt [4]byte - }{ - Type: "AuthenticationMD5Password", - Salt: src.Salt, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *AuthenticationMD5Password) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Type string - Salt [4]byte - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - dst.Salt = msg.Salt - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_ok.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_ok.go deleted file mode 100644 index ec11d39f1..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_ok.go +++ /dev/null @@ -1,51 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// AuthenticationOk is a message sent from the backend indicating that authentication was successful. -type AuthenticationOk struct { -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*AuthenticationOk) Backend() {} - -// Backend identifies this message as an authentication response. -func (*AuthenticationOk) AuthenticationResponse() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *AuthenticationOk) Decode(src []byte) error { - if len(src) != 4 { - return errors.New("bad authentication message size") - } - - authType := binary.BigEndian.Uint32(src) - - if authType != AuthTypeOk { - return errors.New("bad auth type") - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationOk) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'R') - dst = pgio.AppendUint32(dst, AuthTypeOk) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src AuthenticationOk) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "AuthenticationOK", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl.go deleted file mode 100644 index e66580f44..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl.go +++ /dev/null @@ -1,72 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// AuthenticationSASL is a message sent from the backend indicating that SASL authentication is required. -type AuthenticationSASL struct { - AuthMechanisms []string -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*AuthenticationSASL) Backend() {} - -// Backend identifies this message as an authentication response. -func (*AuthenticationSASL) AuthenticationResponse() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *AuthenticationSASL) Decode(src []byte) error { - if len(src) < 4 { - return errors.New("authentication message too short") - } - - authType := binary.BigEndian.Uint32(src) - - if authType != AuthTypeSASL { - return errors.New("bad auth type") - } - - authMechanisms := src[4:] - for len(authMechanisms) > 1 { - idx := bytes.IndexByte(authMechanisms, 0) - if idx == -1 { - return &invalidMessageFormatErr{messageType: "AuthenticationSASL", details: "unterminated string"} - } - dst.AuthMechanisms = append(dst.AuthMechanisms, string(authMechanisms[:idx])) - authMechanisms = authMechanisms[idx+1:] - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationSASL) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'R') - dst = pgio.AppendUint32(dst, AuthTypeSASL) - - for _, s := range src.AuthMechanisms { - dst = append(dst, []byte(s)...) - dst = append(dst, 0) - } - dst = append(dst, 0) - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src AuthenticationSASL) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - AuthMechanisms []string - }{ - Type: "AuthenticationSASL", - AuthMechanisms: src.AuthMechanisms, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go deleted file mode 100644 index 70fba4a67..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go +++ /dev/null @@ -1,75 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// AuthenticationSASLContinue is a message sent from the backend containing a SASL challenge. -type AuthenticationSASLContinue struct { - Data []byte -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*AuthenticationSASLContinue) Backend() {} - -// Backend identifies this message as an authentication response. -func (*AuthenticationSASLContinue) AuthenticationResponse() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *AuthenticationSASLContinue) Decode(src []byte) error { - if len(src) < 4 { - return errors.New("authentication message too short") - } - - authType := binary.BigEndian.Uint32(src) - - if authType != AuthTypeSASLContinue { - return errors.New("bad auth type") - } - - dst.Data = src[4:] - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationSASLContinue) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'R') - dst = pgio.AppendUint32(dst, AuthTypeSASLContinue) - dst = append(dst, src.Data...) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src AuthenticationSASLContinue) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Data string - }{ - Type: "AuthenticationSASLContinue", - Data: string(src.Data), - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *AuthenticationSASLContinue) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Data string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - dst.Data = []byte(msg.Data) - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go deleted file mode 100644 index 84976c2a3..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go +++ /dev/null @@ -1,75 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// AuthenticationSASLFinal is a message sent from the backend indicating a SASL authentication has completed. -type AuthenticationSASLFinal struct { - Data []byte -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*AuthenticationSASLFinal) Backend() {} - -// Backend identifies this message as an authentication response. -func (*AuthenticationSASLFinal) AuthenticationResponse() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *AuthenticationSASLFinal) Decode(src []byte) error { - if len(src) < 4 { - return errors.New("authentication message too short") - } - - authType := binary.BigEndian.Uint32(src) - - if authType != AuthTypeSASLFinal { - return errors.New("bad auth type") - } - - dst.Data = src[4:] - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *AuthenticationSASLFinal) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'R') - dst = pgio.AppendUint32(dst, AuthTypeSASLFinal) - dst = append(dst, src.Data...) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Unmarshaler. -func (src AuthenticationSASLFinal) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Data string - }{ - Type: "AuthenticationSASLFinal", - Data: string(src.Data), - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *AuthenticationSASLFinal) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Data string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - dst.Data = []byte(msg.Data) - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go b/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go deleted file mode 100644 index 28cff049a..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go +++ /dev/null @@ -1,299 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "fmt" - "io" -) - -// Backend acts as a server for the PostgreSQL wire protocol version 3. -type Backend struct { - cr *chunkReader - w io.Writer - - // tracer is used to trace messages when Send or Receive is called. This means an outbound message is traced - // before it is actually transmitted (i.e. before Flush). - tracer *tracer - - wbuf []byte - encodeError error - - // Frontend message flyweights - bind Bind - cancelRequest CancelRequest - _close Close - copyFail CopyFail - copyData CopyData - copyDone CopyDone - describe Describe - execute Execute - flush Flush - functionCall FunctionCall - gssEncRequest GSSEncRequest - parse Parse - query Query - sslRequest SSLRequest - startupMessage StartupMessage - sync Sync - terminate Terminate - - bodyLen int - maxBodyLen int // maxBodyLen is the maximum length of a message body in octets. If a message body exceeds this length, Receive will return an error. - msgType byte - partialMsg bool - authType uint32 -} - -const ( - minStartupPacketLen = 4 // minStartupPacketLen is a single 32-bit int version or code. - maxStartupPacketLen = 10000 // maxStartupPacketLen is MAX_STARTUP_PACKET_LENGTH from PG source. -) - -// NewBackend creates a new Backend. -func NewBackend(r io.Reader, w io.Writer) *Backend { - cr := newChunkReader(r, 0) - return &Backend{cr: cr, w: w} -} - -// Send sends a message to the frontend (i.e. the client). The message is buffered until Flush is called. Any error -// encountered will be returned from Flush. -func (b *Backend) Send(msg BackendMessage) { - if b.encodeError != nil { - return - } - - prevLen := len(b.wbuf) - newBuf, err := msg.Encode(b.wbuf) - if err != nil { - b.encodeError = err - return - } - b.wbuf = newBuf - - if b.tracer != nil { - b.tracer.traceMessage('B', int32(len(b.wbuf)-prevLen), msg) - } -} - -// Flush writes any pending messages to the frontend (i.e. the client). -func (b *Backend) Flush() error { - if err := b.encodeError; err != nil { - b.encodeError = nil - b.wbuf = b.wbuf[:0] - return &writeError{err: err, safeToRetry: true} - } - - n, err := b.w.Write(b.wbuf) - - const maxLen = 1024 - if len(b.wbuf) > maxLen { - b.wbuf = make([]byte, 0, maxLen) - } else { - b.wbuf = b.wbuf[:0] - } - - if err != nil { - return &writeError{err: err, safeToRetry: n == 0} - } - - return nil -} - -// Trace starts tracing the message traffic to w. It writes in a similar format to that produced by the libpq function -// PQtrace. -func (b *Backend) Trace(w io.Writer, options TracerOptions) { - b.tracer = &tracer{ - w: w, - buf: &bytes.Buffer{}, - TracerOptions: options, - } -} - -// Untrace stops tracing. -func (b *Backend) Untrace() { - b.tracer = nil -} - -// ReceiveStartupMessage receives the initial connection message. This method is used of the normal Receive method -// because the initial connection message is "special" and does not include the message type as the first byte. This -// will return either a StartupMessage, SSLRequest, GSSEncRequest, or CancelRequest. -func (b *Backend) ReceiveStartupMessage() (FrontendMessage, error) { - buf, err := b.cr.Next(4) - if err != nil { - return nil, err - } - msgSize := int(binary.BigEndian.Uint32(buf) - 4) - - if msgSize < minStartupPacketLen || msgSize > maxStartupPacketLen { - return nil, fmt.Errorf("invalid length of startup packet: %d", msgSize) - } - - buf, err = b.cr.Next(msgSize) - if err != nil { - return nil, translateEOFtoErrUnexpectedEOF(err) - } - - code := binary.BigEndian.Uint32(buf) - - switch code { - case ProtocolVersionNumber: - err = b.startupMessage.Decode(buf) - if err != nil { - return nil, err - } - return &b.startupMessage, nil - case sslRequestNumber: - err = b.sslRequest.Decode(buf) - if err != nil { - return nil, err - } - return &b.sslRequest, nil - case cancelRequestCode: - err = b.cancelRequest.Decode(buf) - if err != nil { - return nil, err - } - return &b.cancelRequest, nil - case gssEncReqNumber: - err = b.gssEncRequest.Decode(buf) - if err != nil { - return nil, err - } - return &b.gssEncRequest, nil - default: - return nil, fmt.Errorf("unknown startup message code: %d", code) - } -} - -// Receive receives a message from the frontend. The returned message is only valid until the next call to Receive. -func (b *Backend) Receive() (FrontendMessage, error) { - if !b.partialMsg { - header, err := b.cr.Next(5) - if err != nil { - return nil, translateEOFtoErrUnexpectedEOF(err) - } - - b.msgType = header[0] - - msgLength := int(binary.BigEndian.Uint32(header[1:])) - if msgLength < 4 { - return nil, fmt.Errorf("invalid message length: %d", msgLength) - } - - b.bodyLen = msgLength - 4 - if b.maxBodyLen > 0 && b.bodyLen > b.maxBodyLen { - return nil, &ExceededMaxBodyLenErr{b.maxBodyLen, b.bodyLen} - } - b.partialMsg = true - } - - var msg FrontendMessage - switch b.msgType { - case 'B': - msg = &b.bind - case 'C': - msg = &b._close - case 'D': - msg = &b.describe - case 'E': - msg = &b.execute - case 'F': - msg = &b.functionCall - case 'f': - msg = &b.copyFail - case 'd': - msg = &b.copyData - case 'c': - msg = &b.copyDone - case 'H': - msg = &b.flush - case 'P': - msg = &b.parse - case 'p': - switch b.authType { - case AuthTypeSASL: - msg = &SASLInitialResponse{} - case AuthTypeSASLContinue: - msg = &SASLResponse{} - case AuthTypeSASLFinal: - msg = &SASLResponse{} - case AuthTypeGSS, AuthTypeGSSCont: - msg = &GSSResponse{} - case AuthTypeCleartextPassword, AuthTypeMD5Password: - fallthrough - default: - // to maintain backwards compatibility - msg = &PasswordMessage{} - } - case 'Q': - msg = &b.query - case 'S': - msg = &b.sync - case 'X': - msg = &b.terminate - default: - return nil, fmt.Errorf("unknown message type: %c", b.msgType) - } - - msgBody, err := b.cr.Next(b.bodyLen) - if err != nil { - return nil, translateEOFtoErrUnexpectedEOF(err) - } - - b.partialMsg = false - - err = msg.Decode(msgBody) - if err != nil { - return nil, err - } - - if b.tracer != nil { - b.tracer.traceMessage('F', int32(5+len(msgBody)), msg) - } - - return msg, nil -} - -// SetAuthType sets the authentication type in the backend. -// Since multiple message types can start with 'p', SetAuthType allows -// contextual identification of FrontendMessages. For example, in the -// PG message flow documentation for PasswordMessage: -// -// Byte1('p') -// -// Identifies the message as a password response. Note that this is also used for -// GSSAPI, SSPI and SASL response messages. The exact message type can be deduced from -// the context. -// -// Since the Frontend does not know about the state of a backend, it is important -// to call SetAuthType() after an authentication request is received by the Frontend. -func (b *Backend) SetAuthType(authType uint32) error { - switch authType { - case AuthTypeOk, - AuthTypeCleartextPassword, - AuthTypeMD5Password, - AuthTypeSCMCreds, - AuthTypeGSS, - AuthTypeGSSCont, - AuthTypeSSPI, - AuthTypeSASL, - AuthTypeSASLContinue, - AuthTypeSASLFinal: - b.authType = authType - default: - return fmt.Errorf("authType not recognized: %d", authType) - } - - return nil -} - -// SetMaxBodyLen sets the maximum length of a message body in octets. -// If a message body exceeds this length, Receive will return an error. -// This is useful for protecting against malicious clients that send -// large messages with the intent of causing memory exhaustion. -// The default value is 0. -// If maxBodyLen is 0, then no maximum is enforced. -func (b *Backend) SetMaxBodyLen(maxBodyLen int) { - b.maxBodyLen = maxBodyLen -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go deleted file mode 100644 index 23f5da677..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go +++ /dev/null @@ -1,50 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type BackendKeyData struct { - ProcessID uint32 - SecretKey uint32 -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*BackendKeyData) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *BackendKeyData) Decode(src []byte) error { - if len(src) != 8 { - return &invalidMessageLenErr{messageType: "BackendKeyData", expectedLen: 8, actualLen: len(src)} - } - - dst.ProcessID = binary.BigEndian.Uint32(src[:4]) - dst.SecretKey = binary.BigEndian.Uint32(src[4:]) - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *BackendKeyData) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'K') - dst = pgio.AppendUint32(dst, src.ProcessID) - dst = pgio.AppendUint32(dst, src.SecretKey) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src BackendKeyData) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ProcessID uint32 - SecretKey uint32 - }{ - Type: "BackendKeyData", - ProcessID: src.ProcessID, - SecretKey: src.SecretKey, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/big_endian.go b/vendor/github.com/jackc/pgx/v5/pgproto3/big_endian.go deleted file mode 100644 index f7bdb97eb..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/big_endian.go +++ /dev/null @@ -1,37 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" -) - -type BigEndianBuf [8]byte - -func (b BigEndianBuf) Int16(n int16) []byte { - buf := b[0:2] - binary.BigEndian.PutUint16(buf, uint16(n)) - return buf -} - -func (b BigEndianBuf) Uint16(n uint16) []byte { - buf := b[0:2] - binary.BigEndian.PutUint16(buf, n) - return buf -} - -func (b BigEndianBuf) Int32(n int32) []byte { - buf := b[0:4] - binary.BigEndian.PutUint32(buf, uint32(n)) - return buf -} - -func (b BigEndianBuf) Uint32(n uint32) []byte { - buf := b[0:4] - binary.BigEndian.PutUint32(buf, n) - return buf -} - -func (b BigEndianBuf) Int64(n int64) []byte { - buf := b[0:8] - binary.BigEndian.PutUint64(buf, uint64(n)) - return buf -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go b/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go deleted file mode 100644 index ad6ac48bf..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go +++ /dev/null @@ -1,223 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Bind struct { - DestinationPortal string - PreparedStatement string - ParameterFormatCodes []int16 - Parameters [][]byte - ResultFormatCodes []int16 -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Bind) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Bind) Decode(src []byte) error { - *dst = Bind{} - - idx := bytes.IndexByte(src, 0) - if idx < 0 { - return &invalidMessageFormatErr{messageType: "Bind"} - } - dst.DestinationPortal = string(src[:idx]) - rp := idx + 1 - - idx = bytes.IndexByte(src[rp:], 0) - if idx < 0 { - return &invalidMessageFormatErr{messageType: "Bind"} - } - dst.PreparedStatement = string(src[rp : rp+idx]) - rp += idx + 1 - - if len(src[rp:]) < 2 { - return &invalidMessageFormatErr{messageType: "Bind"} - } - parameterFormatCodeCount := int(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - - if parameterFormatCodeCount > 0 { - dst.ParameterFormatCodes = make([]int16, parameterFormatCodeCount) - - if len(src[rp:]) < len(dst.ParameterFormatCodes)*2 { - return &invalidMessageFormatErr{messageType: "Bind"} - } - for i := 0; i < parameterFormatCodeCount; i++ { - dst.ParameterFormatCodes[i] = int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - } - } - - if len(src[rp:]) < 2 { - return &invalidMessageFormatErr{messageType: "Bind"} - } - parameterCount := int(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - - if parameterCount > 0 { - dst.Parameters = make([][]byte, parameterCount) - - for i := 0; i < parameterCount; i++ { - if len(src[rp:]) < 4 { - return &invalidMessageFormatErr{messageType: "Bind"} - } - - msgSize := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - - // null - if msgSize == -1 { - continue - } - - if len(src[rp:]) < msgSize { - return &invalidMessageFormatErr{messageType: "Bind"} - } - - dst.Parameters[i] = src[rp : rp+msgSize] - rp += msgSize - } - } - - if len(src[rp:]) < 2 { - return &invalidMessageFormatErr{messageType: "Bind"} - } - resultFormatCodeCount := int(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - - dst.ResultFormatCodes = make([]int16, resultFormatCodeCount) - if len(src[rp:]) < len(dst.ResultFormatCodes)*2 { - return &invalidMessageFormatErr{messageType: "Bind"} - } - for i := 0; i < resultFormatCodeCount; i++ { - dst.ResultFormatCodes[i] = int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Bind) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'B') - - dst = append(dst, src.DestinationPortal...) - dst = append(dst, 0) - dst = append(dst, src.PreparedStatement...) - dst = append(dst, 0) - - if len(src.ParameterFormatCodes) > math.MaxUint16 { - return nil, errors.New("too many parameter format codes") - } - dst = pgio.AppendUint16(dst, uint16(len(src.ParameterFormatCodes))) - for _, fc := range src.ParameterFormatCodes { - dst = pgio.AppendInt16(dst, fc) - } - - if len(src.Parameters) > math.MaxUint16 { - return nil, errors.New("too many parameters") - } - dst = pgio.AppendUint16(dst, uint16(len(src.Parameters))) - for _, p := range src.Parameters { - if p == nil { - dst = pgio.AppendInt32(dst, -1) - continue - } - - dst = pgio.AppendInt32(dst, int32(len(p))) - dst = append(dst, p...) - } - - if len(src.ResultFormatCodes) > math.MaxUint16 { - return nil, errors.New("too many result format codes") - } - dst = pgio.AppendUint16(dst, uint16(len(src.ResultFormatCodes))) - for _, fc := range src.ResultFormatCodes { - dst = pgio.AppendInt16(dst, fc) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Bind) MarshalJSON() ([]byte, error) { - formattedParameters := make([]map[string]string, len(src.Parameters)) - for i, p := range src.Parameters { - if p == nil { - continue - } - - textFormat := true - if len(src.ParameterFormatCodes) == 1 { - textFormat = src.ParameterFormatCodes[0] == 0 - } else if len(src.ParameterFormatCodes) > 1 { - textFormat = src.ParameterFormatCodes[i] == 0 - } - - if textFormat { - formattedParameters[i] = map[string]string{"text": string(p)} - } else { - formattedParameters[i] = map[string]string{"binary": hex.EncodeToString(p)} - } - } - - return json.Marshal(struct { - Type string - DestinationPortal string - PreparedStatement string - ParameterFormatCodes []int16 - Parameters []map[string]string - ResultFormatCodes []int16 - }{ - Type: "Bind", - DestinationPortal: src.DestinationPortal, - PreparedStatement: src.PreparedStatement, - ParameterFormatCodes: src.ParameterFormatCodes, - Parameters: formattedParameters, - ResultFormatCodes: src.ResultFormatCodes, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *Bind) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - DestinationPortal string - PreparedStatement string - ParameterFormatCodes []int16 - Parameters []map[string]string - ResultFormatCodes []int16 - } - err := json.Unmarshal(data, &msg) - if err != nil { - return err - } - dst.DestinationPortal = msg.DestinationPortal - dst.PreparedStatement = msg.PreparedStatement - dst.ParameterFormatCodes = msg.ParameterFormatCodes - dst.Parameters = make([][]byte, len(msg.Parameters)) - dst.ResultFormatCodes = msg.ResultFormatCodes - for n, parameter := range msg.Parameters { - dst.Parameters[n], err = getValueFromJSON(parameter) - if err != nil { - return fmt.Errorf("cannot get param %d: %w", n, err) - } - } - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go deleted file mode 100644 index bacf30d88..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type BindComplete struct{} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*BindComplete) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *BindComplete) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "BindComplete", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *BindComplete) Encode(dst []byte) ([]byte, error) { - return append(dst, '2', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src BindComplete) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "BindComplete", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go deleted file mode 100644 index 6b52dd977..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go +++ /dev/null @@ -1,58 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -const cancelRequestCode = 80877102 - -type CancelRequest struct { - ProcessID uint32 - SecretKey uint32 -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*CancelRequest) Frontend() {} - -func (dst *CancelRequest) Decode(src []byte) error { - if len(src) != 12 { - return errors.New("bad cancel request size") - } - - requestCode := binary.BigEndian.Uint32(src) - - if requestCode != cancelRequestCode { - return errors.New("bad cancel request code") - } - - dst.ProcessID = binary.BigEndian.Uint32(src[4:]) - dst.SecretKey = binary.BigEndian.Uint32(src[8:]) - - return nil -} - -// Encode encodes src into dst. dst will include the 4 byte message length. -func (src *CancelRequest) Encode(dst []byte) ([]byte, error) { - dst = pgio.AppendInt32(dst, 16) - dst = pgio.AppendInt32(dst, cancelRequestCode) - dst = pgio.AppendUint32(dst, src.ProcessID) - dst = pgio.AppendUint32(dst, src.SecretKey) - return dst, nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CancelRequest) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ProcessID uint32 - SecretKey uint32 - }{ - Type: "CancelRequest", - ProcessID: src.ProcessID, - SecretKey: src.SecretKey, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/chunkreader.go b/vendor/github.com/jackc/pgx/v5/pgproto3/chunkreader.go deleted file mode 100644 index fc0fa61e9..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/chunkreader.go +++ /dev/null @@ -1,90 +0,0 @@ -package pgproto3 - -import ( - "io" - - "github.com/jackc/pgx/v5/internal/iobufpool" -) - -// chunkReader is a io.Reader wrapper that minimizes IO reads and memory allocations. It allocates memory in chunks and -// will read as much as will fit in the current buffer in a single call regardless of how large a read is actually -// requested. The memory returned via Next is only valid until the next call to Next. -// -// This is roughly equivalent to a bufio.Reader that only uses Peek and Discard to never copy bytes. -type chunkReader struct { - r io.Reader - - buf *[]byte - rp, wp int // buf read position and write position - - minBufSize int -} - -// newChunkReader creates and returns a new chunkReader for r with default configuration. If minBufSize is <= 0 it uses -// a default value. -func newChunkReader(r io.Reader, minBufSize int) *chunkReader { - if minBufSize <= 0 { - // By historical reasons Postgres currently has 8KB send buffer inside, - // so here we want to have at least the same size buffer. - // @see https://github.com/postgres/postgres/blob/249d64999615802752940e017ee5166e726bc7cd/src/backend/libpq/pqcomm.c#L134 - // @see https://www.postgresql.org/message-id/0cdc5485-cb3c-5e16-4a46-e3b2f7a41322%40ya.ru - // - // In addition, testing has found no benefit of any larger buffer. - minBufSize = 8192 - } - - return &chunkReader{ - r: r, - minBufSize: minBufSize, - buf: iobufpool.Get(minBufSize), - } -} - -// Next returns buf filled with the next n bytes. buf is only valid until next call of Next. If an error occurs, buf -// will be nil. -func (r *chunkReader) Next(n int) (buf []byte, err error) { - // Reset the buffer if it is empty - if r.rp == r.wp { - if len(*r.buf) != r.minBufSize { - iobufpool.Put(r.buf) - r.buf = iobufpool.Get(r.minBufSize) - } - r.rp = 0 - r.wp = 0 - } - - // n bytes already in buf - if (r.wp - r.rp) >= n { - buf = (*r.buf)[r.rp : r.rp+n : r.rp+n] - r.rp += n - return buf, err - } - - // buf is smaller than requested number of bytes - if len(*r.buf) < n { - bigBuf := iobufpool.Get(n) - r.wp = copy((*bigBuf), (*r.buf)[r.rp:r.wp]) - r.rp = 0 - iobufpool.Put(r.buf) - r.buf = bigBuf - } - - // buf is large enough, but need to shift filled area to start to make enough contiguous space - minReadCount := n - (r.wp - r.rp) - if (len(*r.buf) - r.wp) < minReadCount { - r.wp = copy((*r.buf), (*r.buf)[r.rp:r.wp]) - r.rp = 0 - } - - // Read at least the required number of bytes from the underlying io.Reader - readBytesCount, err := io.ReadAtLeast(r.r, (*r.buf)[r.wp:], minReadCount) - r.wp += readBytesCount - // fmt.Println("read", n) - if err != nil { - return nil, err - } - - buf = (*r.buf)[r.rp : r.rp+n : r.rp+n] - r.rp += n - return buf, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/close.go b/vendor/github.com/jackc/pgx/v5/pgproto3/close.go deleted file mode 100644 index 0b50f27cb..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/close.go +++ /dev/null @@ -1,81 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/json" - "errors" -) - -type Close struct { - ObjectType byte // 'S' = prepared statement, 'P' = portal - Name string -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Close) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Close) Decode(src []byte) error { - if len(src) < 2 { - return &invalidMessageFormatErr{messageType: "Close"} - } - - dst.ObjectType = src[0] - rp := 1 - - idx := bytes.IndexByte(src[rp:], 0) - if idx != len(src[rp:])-1 { - return &invalidMessageFormatErr{messageType: "Close"} - } - - dst.Name = string(src[rp : len(src)-1]) - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Close) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'C') - dst = append(dst, src.ObjectType) - dst = append(dst, src.Name...) - dst = append(dst, 0) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Close) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ObjectType string - Name string - }{ - Type: "Close", - ObjectType: string(src.ObjectType), - Name: src.Name, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *Close) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - ObjectType string - Name string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - if len(msg.ObjectType) != 1 { - return errors.New("invalid length for Close.ObjectType") - } - - dst.ObjectType = byte(msg.ObjectType[0]) - dst.Name = msg.Name - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go deleted file mode 100644 index 833f7a12c..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type CloseComplete struct{} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*CloseComplete) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *CloseComplete) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "CloseComplete", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CloseComplete) Encode(dst []byte) ([]byte, error) { - return append(dst, '3', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CloseComplete) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "CloseComplete", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go deleted file mode 100644 index eba70947d..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go +++ /dev/null @@ -1,66 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/json" -) - -type CommandComplete struct { - CommandTag []byte -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*CommandComplete) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *CommandComplete) Decode(src []byte) error { - idx := bytes.IndexByte(src, 0) - if idx == -1 { - return &invalidMessageFormatErr{messageType: "CommandComplete", details: "unterminated string"} - } - if idx != len(src)-1 { - return &invalidMessageFormatErr{messageType: "CommandComplete", details: "string terminated too early"} - } - - dst.CommandTag = src[:idx] - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CommandComplete) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'C') - dst = append(dst, src.CommandTag...) - dst = append(dst, 0) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CommandComplete) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - CommandTag string - }{ - Type: "CommandComplete", - CommandTag: string(src.CommandTag), - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *CommandComplete) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - CommandTag string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - dst.CommandTag = []byte(msg.CommandTag) - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go deleted file mode 100644 index 99e1afea4..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go +++ /dev/null @@ -1,95 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type CopyBothResponse struct { - OverallFormat byte - ColumnFormatCodes []uint16 -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*CopyBothResponse) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *CopyBothResponse) Decode(src []byte) error { - buf := bytes.NewBuffer(src) - - if buf.Len() < 3 { - return &invalidMessageFormatErr{messageType: "CopyBothResponse"} - } - - overallFormat := buf.Next(1)[0] - - columnCount := int(binary.BigEndian.Uint16(buf.Next(2))) - if buf.Len() != columnCount*2 { - return &invalidMessageFormatErr{messageType: "CopyBothResponse"} - } - - columnFormatCodes := make([]uint16, columnCount) - for i := 0; i < columnCount; i++ { - columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2)) - } - - *dst = CopyBothResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes} - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyBothResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'W') - dst = append(dst, src.OverallFormat) - if len(src.ColumnFormatCodes) > math.MaxUint16 { - return nil, errors.New("too many column format codes") - } - dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) - for _, fc := range src.ColumnFormatCodes { - dst = pgio.AppendUint16(dst, fc) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CopyBothResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ColumnFormatCodes []uint16 - }{ - Type: "CopyBothResponse", - ColumnFormatCodes: src.ColumnFormatCodes, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *CopyBothResponse) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - OverallFormat string - ColumnFormatCodes []uint16 - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - if len(msg.OverallFormat) != 1 { - return errors.New("invalid length for CopyBothResponse.OverallFormat") - } - - dst.OverallFormat = msg.OverallFormat[0] - dst.ColumnFormatCodes = msg.ColumnFormatCodes - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go deleted file mode 100644 index 89ecdd4dd..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go +++ /dev/null @@ -1,59 +0,0 @@ -package pgproto3 - -import ( - "encoding/hex" - "encoding/json" -) - -type CopyData struct { - Data []byte -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*CopyData) Backend() {} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*CopyData) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *CopyData) Decode(src []byte) error { - dst.Data = src - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyData) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'd') - dst = append(dst, src.Data...) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CopyData) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Data string - }{ - Type: "CopyData", - Data: hex.EncodeToString(src.Data), - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *CopyData) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Data string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - dst.Data = []byte(msg.Data) - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go deleted file mode 100644 index 040814dbd..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go +++ /dev/null @@ -1,38 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type CopyDone struct { -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*CopyDone) Backend() {} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*CopyDone) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *CopyDone) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "CopyDone", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyDone) Encode(dst []byte) ([]byte, error) { - return append(dst, 'c', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CopyDone) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "CopyDone", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go deleted file mode 100644 index 72a85fd09..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go +++ /dev/null @@ -1,45 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/json" -) - -type CopyFail struct { - Message string -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*CopyFail) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *CopyFail) Decode(src []byte) error { - idx := bytes.IndexByte(src, 0) - if idx != len(src)-1 { - return &invalidMessageFormatErr{messageType: "CopyFail"} - } - - dst.Message = string(src[:idx]) - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyFail) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'f') - dst = append(dst, src.Message...) - dst = append(dst, 0) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CopyFail) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Message string - }{ - Type: "CopyFail", - Message: src.Message, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go deleted file mode 100644 index 06cf99ced..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go +++ /dev/null @@ -1,96 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type CopyInResponse struct { - OverallFormat byte - ColumnFormatCodes []uint16 -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*CopyInResponse) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *CopyInResponse) Decode(src []byte) error { - buf := bytes.NewBuffer(src) - - if buf.Len() < 3 { - return &invalidMessageFormatErr{messageType: "CopyInResponse"} - } - - overallFormat := buf.Next(1)[0] - - columnCount := int(binary.BigEndian.Uint16(buf.Next(2))) - if buf.Len() != columnCount*2 { - return &invalidMessageFormatErr{messageType: "CopyInResponse"} - } - - columnFormatCodes := make([]uint16, columnCount) - for i := 0; i < columnCount; i++ { - columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2)) - } - - *dst = CopyInResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes} - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyInResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'G') - - dst = append(dst, src.OverallFormat) - if len(src.ColumnFormatCodes) > math.MaxUint16 { - return nil, errors.New("too many column format codes") - } - dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) - for _, fc := range src.ColumnFormatCodes { - dst = pgio.AppendUint16(dst, fc) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CopyInResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ColumnFormatCodes []uint16 - }{ - Type: "CopyInResponse", - ColumnFormatCodes: src.ColumnFormatCodes, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *CopyInResponse) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - OverallFormat string - ColumnFormatCodes []uint16 - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - if len(msg.OverallFormat) != 1 { - return errors.New("invalid length for CopyInResponse.OverallFormat") - } - - dst.OverallFormat = msg.OverallFormat[0] - dst.ColumnFormatCodes = msg.ColumnFormatCodes - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go deleted file mode 100644 index 549e916c1..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go +++ /dev/null @@ -1,96 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type CopyOutResponse struct { - OverallFormat byte - ColumnFormatCodes []uint16 -} - -func (*CopyOutResponse) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *CopyOutResponse) Decode(src []byte) error { - buf := bytes.NewBuffer(src) - - if buf.Len() < 3 { - return &invalidMessageFormatErr{messageType: "CopyOutResponse"} - } - - overallFormat := buf.Next(1)[0] - - columnCount := int(binary.BigEndian.Uint16(buf.Next(2))) - if buf.Len() != columnCount*2 { - return &invalidMessageFormatErr{messageType: "CopyOutResponse"} - } - - columnFormatCodes := make([]uint16, columnCount) - for i := 0; i < columnCount; i++ { - columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2)) - } - - *dst = CopyOutResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes} - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *CopyOutResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'H') - - dst = append(dst, src.OverallFormat) - - if len(src.ColumnFormatCodes) > math.MaxUint16 { - return nil, errors.New("too many column format codes") - } - dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) - for _, fc := range src.ColumnFormatCodes { - dst = pgio.AppendUint16(dst, fc) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src CopyOutResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ColumnFormatCodes []uint16 - }{ - Type: "CopyOutResponse", - ColumnFormatCodes: src.ColumnFormatCodes, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *CopyOutResponse) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - OverallFormat string - ColumnFormatCodes []uint16 - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - if len(msg.OverallFormat) != 1 { - return errors.New("invalid length for CopyOutResponse.OverallFormat") - } - - dst.OverallFormat = msg.OverallFormat[0] - dst.ColumnFormatCodes = msg.ColumnFormatCodes - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go b/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go deleted file mode 100644 index fdfb0f7f6..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go +++ /dev/null @@ -1,143 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/hex" - "encoding/json" - "errors" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type DataRow struct { - Values [][]byte -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*DataRow) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *DataRow) Decode(src []byte) error { - if len(src) < 2 { - return &invalidMessageFormatErr{messageType: "DataRow"} - } - rp := 0 - fieldCount := int(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - - // If the capacity of the values slice is too small OR substantially too - // large reallocate. This is too avoid one row with many columns from - // permanently allocating memory. - if cap(dst.Values) < fieldCount || cap(dst.Values)-fieldCount > 32 { - newCap := 32 - if newCap < fieldCount { - newCap = fieldCount - } - dst.Values = make([][]byte, fieldCount, newCap) - } else { - dst.Values = dst.Values[:fieldCount] - } - - for i := 0; i < fieldCount; i++ { - if len(src[rp:]) < 4 { - return &invalidMessageFormatErr{messageType: "DataRow"} - } - - valueLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - - // null - if valueLen == -1 { - dst.Values[i] = nil - } else { - if len(src[rp:]) < valueLen || valueLen < 0 { - return &invalidMessageFormatErr{messageType: "DataRow"} - } - - dst.Values[i] = src[rp : rp+valueLen : rp+valueLen] - rp += valueLen - } - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *DataRow) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'D') - - if len(src.Values) > math.MaxUint16 { - return nil, errors.New("too many values") - } - dst = pgio.AppendUint16(dst, uint16(len(src.Values))) - for _, v := range src.Values { - if v == nil { - dst = pgio.AppendInt32(dst, -1) - continue - } - - dst = pgio.AppendInt32(dst, int32(len(v))) - dst = append(dst, v...) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src DataRow) MarshalJSON() ([]byte, error) { - formattedValues := make([]map[string]string, len(src.Values)) - for i, v := range src.Values { - if v == nil { - continue - } - - var hasNonPrintable bool - for _, b := range v { - if b < 32 { - hasNonPrintable = true - break - } - } - - if hasNonPrintable { - formattedValues[i] = map[string]string{"binary": hex.EncodeToString(v)} - } else { - formattedValues[i] = map[string]string{"text": string(v)} - } - } - - return json.Marshal(struct { - Type string - Values []map[string]string - }{ - Type: "DataRow", - Values: formattedValues, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *DataRow) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Values []map[string]string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - dst.Values = make([][]byte, len(msg.Values)) - for n, parameter := range msg.Values { - var err error - dst.Values[n], err = getValueFromJSON(parameter) - if err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go b/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go deleted file mode 100644 index 89feff215..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go +++ /dev/null @@ -1,80 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/json" - "errors" -) - -type Describe struct { - ObjectType byte // 'S' = prepared statement, 'P' = portal - Name string -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Describe) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Describe) Decode(src []byte) error { - if len(src) < 2 { - return &invalidMessageFormatErr{messageType: "Describe"} - } - - dst.ObjectType = src[0] - rp := 1 - - idx := bytes.IndexByte(src[rp:], 0) - if idx != len(src[rp:])-1 { - return &invalidMessageFormatErr{messageType: "Describe"} - } - - dst.Name = string(src[rp : len(src)-1]) - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Describe) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'D') - dst = append(dst, src.ObjectType) - dst = append(dst, src.Name...) - dst = append(dst, 0) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Describe) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ObjectType string - Name string - }{ - Type: "Describe", - ObjectType: string(src.ObjectType), - Name: src.Name, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *Describe) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - ObjectType string - Name string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - if len(msg.ObjectType) != 1 { - return errors.New("invalid length for Describe.ObjectType") - } - - dst.ObjectType = byte(msg.ObjectType[0]) - dst.Name = msg.Name - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/doc.go b/vendor/github.com/jackc/pgx/v5/pgproto3/doc.go deleted file mode 100644 index 0afd18e29..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package pgproto3 is an encoder and decoder of the PostgreSQL wire protocol version 3. -// -// The primary interfaces are Frontend and Backend. They correspond to a client and server respectively. Messages are -// sent with Send (or a specialized Send variant). Messages are automatically buffered to minimize small writes. Call -// Flush to ensure a message has actually been sent. -// -// The Trace method of Frontend and Backend can be used to examine the wire-level message traffic. It outputs in a -// similar format to the PQtrace function in libpq. -// -// See https://www.postgresql.org/docs/current/protocol-message-formats.html for meanings of the different messages. -package pgproto3 diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go deleted file mode 100644 index cb6cca073..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type EmptyQueryResponse struct{} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*EmptyQueryResponse) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *EmptyQueryResponse) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "EmptyQueryResponse", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *EmptyQueryResponse) Encode(dst []byte) ([]byte, error) { - return append(dst, 'I', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src EmptyQueryResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "EmptyQueryResponse", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go deleted file mode 100644 index 6ef9bd061..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go +++ /dev/null @@ -1,326 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/json" - "strconv" -) - -type ErrorResponse struct { - Severity string - SeverityUnlocalized string // only in 9.6 and greater - Code string - Message string - Detail string - Hint string - Position int32 - InternalPosition int32 - InternalQuery string - Where string - SchemaName string - TableName string - ColumnName string - DataTypeName string - ConstraintName string - File string - Line int32 - Routine string - - UnknownFields map[byte]string -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*ErrorResponse) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *ErrorResponse) Decode(src []byte) error { - *dst = ErrorResponse{} - - buf := bytes.NewBuffer(src) - - for { - k, err := buf.ReadByte() - if err != nil { - return err - } - if k == 0 { - break - } - - vb, err := buf.ReadBytes(0) - if err != nil { - return err - } - v := string(vb[:len(vb)-1]) - - switch k { - case 'S': - dst.Severity = v - case 'V': - dst.SeverityUnlocalized = v - case 'C': - dst.Code = v - case 'M': - dst.Message = v - case 'D': - dst.Detail = v - case 'H': - dst.Hint = v - case 'P': - s := v - n, _ := strconv.ParseInt(s, 10, 32) - dst.Position = int32(n) - case 'p': - s := v - n, _ := strconv.ParseInt(s, 10, 32) - dst.InternalPosition = int32(n) - case 'q': - dst.InternalQuery = v - case 'W': - dst.Where = v - case 's': - dst.SchemaName = v - case 't': - dst.TableName = v - case 'c': - dst.ColumnName = v - case 'd': - dst.DataTypeName = v - case 'n': - dst.ConstraintName = v - case 'F': - dst.File = v - case 'L': - s := v - n, _ := strconv.ParseInt(s, 10, 32) - dst.Line = int32(n) - case 'R': - dst.Routine = v - - default: - if dst.UnknownFields == nil { - dst.UnknownFields = make(map[byte]string) - } - dst.UnknownFields[k] = v - } - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ErrorResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'E') - dst = src.appendFields(dst) - return finishMessage(dst, sp) -} - -func (src *ErrorResponse) appendFields(dst []byte) []byte { - if src.Severity != "" { - dst = append(dst, 'S') - dst = append(dst, src.Severity...) - dst = append(dst, 0) - } - if src.SeverityUnlocalized != "" { - dst = append(dst, 'V') - dst = append(dst, src.SeverityUnlocalized...) - dst = append(dst, 0) - } - if src.Code != "" { - dst = append(dst, 'C') - dst = append(dst, src.Code...) - dst = append(dst, 0) - } - if src.Message != "" { - dst = append(dst, 'M') - dst = append(dst, src.Message...) - dst = append(dst, 0) - } - if src.Detail != "" { - dst = append(dst, 'D') - dst = append(dst, src.Detail...) - dst = append(dst, 0) - } - if src.Hint != "" { - dst = append(dst, 'H') - dst = append(dst, src.Hint...) - dst = append(dst, 0) - } - if src.Position != 0 { - dst = append(dst, 'P') - dst = append(dst, strconv.Itoa(int(src.Position))...) - dst = append(dst, 0) - } - if src.InternalPosition != 0 { - dst = append(dst, 'p') - dst = append(dst, strconv.Itoa(int(src.InternalPosition))...) - dst = append(dst, 0) - } - if src.InternalQuery != "" { - dst = append(dst, 'q') - dst = append(dst, src.InternalQuery...) - dst = append(dst, 0) - } - if src.Where != "" { - dst = append(dst, 'W') - dst = append(dst, src.Where...) - dst = append(dst, 0) - } - if src.SchemaName != "" { - dst = append(dst, 's') - dst = append(dst, src.SchemaName...) - dst = append(dst, 0) - } - if src.TableName != "" { - dst = append(dst, 't') - dst = append(dst, src.TableName...) - dst = append(dst, 0) - } - if src.ColumnName != "" { - dst = append(dst, 'c') - dst = append(dst, src.ColumnName...) - dst = append(dst, 0) - } - if src.DataTypeName != "" { - dst = append(dst, 'd') - dst = append(dst, src.DataTypeName...) - dst = append(dst, 0) - } - if src.ConstraintName != "" { - dst = append(dst, 'n') - dst = append(dst, src.ConstraintName...) - dst = append(dst, 0) - } - if src.File != "" { - dst = append(dst, 'F') - dst = append(dst, src.File...) - dst = append(dst, 0) - } - if src.Line != 0 { - dst = append(dst, 'L') - dst = append(dst, strconv.Itoa(int(src.Line))...) - dst = append(dst, 0) - } - if src.Routine != "" { - dst = append(dst, 'R') - dst = append(dst, src.Routine...) - dst = append(dst, 0) - } - - for k, v := range src.UnknownFields { - dst = append(dst, k) - dst = append(dst, v...) - dst = append(dst, 0) - } - - dst = append(dst, 0) - - return dst -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src ErrorResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Severity string - SeverityUnlocalized string // only in 9.6 and greater - Code string - Message string - Detail string - Hint string - Position int32 - InternalPosition int32 - InternalQuery string - Where string - SchemaName string - TableName string - ColumnName string - DataTypeName string - ConstraintName string - File string - Line int32 - Routine string - - UnknownFields map[byte]string - }{ - Type: "ErrorResponse", - Severity: src.Severity, - SeverityUnlocalized: src.SeverityUnlocalized, - Code: src.Code, - Message: src.Message, - Detail: src.Detail, - Hint: src.Hint, - Position: src.Position, - InternalPosition: src.InternalPosition, - InternalQuery: src.InternalQuery, - Where: src.Where, - SchemaName: src.SchemaName, - TableName: src.TableName, - ColumnName: src.ColumnName, - DataTypeName: src.DataTypeName, - ConstraintName: src.ConstraintName, - File: src.File, - Line: src.Line, - Routine: src.Routine, - UnknownFields: src.UnknownFields, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *ErrorResponse) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Type string - Severity string - SeverityUnlocalized string // only in 9.6 and greater - Code string - Message string - Detail string - Hint string - Position int32 - InternalPosition int32 - InternalQuery string - Where string - SchemaName string - TableName string - ColumnName string - DataTypeName string - ConstraintName string - File string - Line int32 - Routine string - - UnknownFields map[byte]string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - - dst.Severity = msg.Severity - dst.SeverityUnlocalized = msg.SeverityUnlocalized - dst.Code = msg.Code - dst.Message = msg.Message - dst.Detail = msg.Detail - dst.Hint = msg.Hint - dst.Position = msg.Position - dst.InternalPosition = msg.InternalPosition - dst.InternalQuery = msg.InternalQuery - dst.Where = msg.Where - dst.SchemaName = msg.SchemaName - dst.TableName = msg.TableName - dst.ColumnName = msg.ColumnName - dst.DataTypeName = msg.DataTypeName - dst.ConstraintName = msg.ConstraintName - dst.File = msg.File - dst.Line = msg.Line - dst.Routine = msg.Routine - - dst.UnknownFields = msg.UnknownFields - - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go b/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go deleted file mode 100644 index 31bc714d1..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go +++ /dev/null @@ -1,58 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Execute struct { - Portal string - MaxRows uint32 -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Execute) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Execute) Decode(src []byte) error { - buf := bytes.NewBuffer(src) - - b, err := buf.ReadBytes(0) - if err != nil { - return err - } - dst.Portal = string(b[:len(b)-1]) - - if buf.Len() < 4 { - return &invalidMessageFormatErr{messageType: "Execute"} - } - dst.MaxRows = binary.BigEndian.Uint32(buf.Next(4)) - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Execute) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'E') - dst = append(dst, src.Portal...) - dst = append(dst, 0) - dst = pgio.AppendUint32(dst, src.MaxRows) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Execute) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Portal string - MaxRows uint32 - }{ - Type: "Execute", - Portal: src.Portal, - MaxRows: src.MaxRows, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go b/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go deleted file mode 100644 index e5dc1fbbd..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type Flush struct{} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Flush) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Flush) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "Flush", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Flush) Encode(dst []byte) ([]byte, error) { - return append(dst, 'H', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Flush) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "Flush", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go b/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go deleted file mode 100644 index 056e547cd..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go +++ /dev/null @@ -1,468 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" -) - -// Frontend acts as a client for the PostgreSQL wire protocol version 3. -type Frontend struct { - cr *chunkReader - w io.Writer - - // tracer is used to trace messages when Send or Receive is called. This means an outbound message is traced - // before it is actually transmitted (i.e. before Flush). It is safe to change this variable when the Frontend is - // idle. Setting and unsetting tracer provides equivalent functionality to PQtrace and PQuntrace in libpq. - tracer *tracer - - wbuf []byte - encodeError error - - // Backend message flyweights - authenticationOk AuthenticationOk - authenticationCleartextPassword AuthenticationCleartextPassword - authenticationMD5Password AuthenticationMD5Password - authenticationGSS AuthenticationGSS - authenticationGSSContinue AuthenticationGSSContinue - authenticationSASL AuthenticationSASL - authenticationSASLContinue AuthenticationSASLContinue - authenticationSASLFinal AuthenticationSASLFinal - backendKeyData BackendKeyData - bindComplete BindComplete - closeComplete CloseComplete - commandComplete CommandComplete - copyBothResponse CopyBothResponse - copyData CopyData - copyInResponse CopyInResponse - copyOutResponse CopyOutResponse - copyDone CopyDone - dataRow DataRow - emptyQueryResponse EmptyQueryResponse - errorResponse ErrorResponse - functionCallResponse FunctionCallResponse - noData NoData - noticeResponse NoticeResponse - notificationResponse NotificationResponse - parameterDescription ParameterDescription - parameterStatus ParameterStatus - parseComplete ParseComplete - readyForQuery ReadyForQuery - rowDescription RowDescription - portalSuspended PortalSuspended - - bodyLen int - maxBodyLen int // maxBodyLen is the maximum length of a message body in octets. If a message body exceeds this length, Receive will return an error. - msgType byte - partialMsg bool - authType uint32 -} - -// NewFrontend creates a new Frontend. -func NewFrontend(r io.Reader, w io.Writer) *Frontend { - cr := newChunkReader(r, 0) - return &Frontend{cr: cr, w: w} -} - -// Send sends a message to the backend (i.e. the server). The message is buffered until Flush is called. Any error -// encountered will be returned from Flush. -// -// Send can work with any FrontendMessage. Some commonly used message types such as Bind have specialized send methods -// such as SendBind. These methods should be preferred when the type of message is known up front (e.g. when building an -// extended query protocol query) as they may be faster due to knowing the type of msg rather than it being hidden -// behind an interface. -func (f *Frontend) Send(msg FrontendMessage) { - if f.encodeError != nil { - return - } - - prevLen := len(f.wbuf) - newBuf, err := msg.Encode(f.wbuf) - if err != nil { - f.encodeError = err - return - } - f.wbuf = newBuf - - if f.tracer != nil { - f.tracer.traceMessage('F', int32(len(f.wbuf)-prevLen), msg) - } -} - -// Flush writes any pending messages to the backend (i.e. the server). -func (f *Frontend) Flush() error { - if err := f.encodeError; err != nil { - f.encodeError = nil - f.wbuf = f.wbuf[:0] - return &writeError{err: err, safeToRetry: true} - } - - if len(f.wbuf) == 0 { - return nil - } - - n, err := f.w.Write(f.wbuf) - - const maxLen = 1024 - if len(f.wbuf) > maxLen { - f.wbuf = make([]byte, 0, maxLen) - } else { - f.wbuf = f.wbuf[:0] - } - - if err != nil { - return &writeError{err: err, safeToRetry: n == 0} - } - - return nil -} - -// Trace starts tracing the message traffic to w. It writes in a similar format to that produced by the libpq function -// PQtrace. -func (f *Frontend) Trace(w io.Writer, options TracerOptions) { - f.tracer = &tracer{ - w: w, - buf: &bytes.Buffer{}, - TracerOptions: options, - } -} - -// Untrace stops tracing. -func (f *Frontend) Untrace() { - f.tracer = nil -} - -// SendBind sends a Bind message to the backend (i.e. the server). The message is buffered until Flush is called. Any -// error encountered will be returned from Flush. -func (f *Frontend) SendBind(msg *Bind) { - if f.encodeError != nil { - return - } - - prevLen := len(f.wbuf) - newBuf, err := msg.Encode(f.wbuf) - if err != nil { - f.encodeError = err - return - } - f.wbuf = newBuf - - if f.tracer != nil { - f.tracer.traceBind('F', int32(len(f.wbuf)-prevLen), msg) - } -} - -// SendParse sends a Parse message to the backend (i.e. the server). The message is buffered until Flush is called. Any -// error encountered will be returned from Flush. -func (f *Frontend) SendParse(msg *Parse) { - if f.encodeError != nil { - return - } - - prevLen := len(f.wbuf) - newBuf, err := msg.Encode(f.wbuf) - if err != nil { - f.encodeError = err - return - } - f.wbuf = newBuf - - if f.tracer != nil { - f.tracer.traceParse('F', int32(len(f.wbuf)-prevLen), msg) - } -} - -// SendClose sends a Close message to the backend (i.e. the server). The message is buffered until Flush is called. Any -// error encountered will be returned from Flush. -func (f *Frontend) SendClose(msg *Close) { - if f.encodeError != nil { - return - } - - prevLen := len(f.wbuf) - newBuf, err := msg.Encode(f.wbuf) - if err != nil { - f.encodeError = err - return - } - f.wbuf = newBuf - - if f.tracer != nil { - f.tracer.traceClose('F', int32(len(f.wbuf)-prevLen), msg) - } -} - -// SendDescribe sends a Describe message to the backend (i.e. the server). The message is buffered until Flush is -// called. Any error encountered will be returned from Flush. -func (f *Frontend) SendDescribe(msg *Describe) { - if f.encodeError != nil { - return - } - - prevLen := len(f.wbuf) - newBuf, err := msg.Encode(f.wbuf) - if err != nil { - f.encodeError = err - return - } - f.wbuf = newBuf - - if f.tracer != nil { - f.tracer.traceDescribe('F', int32(len(f.wbuf)-prevLen), msg) - } -} - -// SendExecute sends an Execute message to the backend (i.e. the server). The message is buffered until Flush is called. -// Any error encountered will be returned from Flush. -func (f *Frontend) SendExecute(msg *Execute) { - if f.encodeError != nil { - return - } - - prevLen := len(f.wbuf) - newBuf, err := msg.Encode(f.wbuf) - if err != nil { - f.encodeError = err - return - } - f.wbuf = newBuf - - if f.tracer != nil { - f.tracer.TraceQueryute('F', int32(len(f.wbuf)-prevLen), msg) - } -} - -// SendSync sends a Sync message to the backend (i.e. the server). The message is buffered until Flush is called. Any -// error encountered will be returned from Flush. -func (f *Frontend) SendSync(msg *Sync) { - if f.encodeError != nil { - return - } - - prevLen := len(f.wbuf) - newBuf, err := msg.Encode(f.wbuf) - if err != nil { - f.encodeError = err - return - } - f.wbuf = newBuf - - if f.tracer != nil { - f.tracer.traceSync('F', int32(len(f.wbuf)-prevLen), msg) - } -} - -// SendQuery sends a Query message to the backend (i.e. the server). The message is buffered until Flush is called. Any -// error encountered will be returned from Flush. -func (f *Frontend) SendQuery(msg *Query) { - if f.encodeError != nil { - return - } - - prevLen := len(f.wbuf) - newBuf, err := msg.Encode(f.wbuf) - if err != nil { - f.encodeError = err - return - } - f.wbuf = newBuf - - if f.tracer != nil { - f.tracer.traceQuery('F', int32(len(f.wbuf)-prevLen), msg) - } -} - -// SendUnbufferedEncodedCopyData immediately sends an encoded CopyData message to the backend (i.e. the server). This method -// is more efficient than sending a CopyData message with Send as the message data is not copied to the internal buffer -// before being written out. The internal buffer is flushed before the message is sent. -func (f *Frontend) SendUnbufferedEncodedCopyData(msg []byte) error { - err := f.Flush() - if err != nil { - return err - } - - n, err := f.w.Write(msg) - if err != nil { - return &writeError{err: err, safeToRetry: n == 0} - } - - if f.tracer != nil { - f.tracer.traceCopyData('F', int32(len(msg)-1), &CopyData{}) - } - - return nil -} - -func translateEOFtoErrUnexpectedEOF(err error) error { - if err == io.EOF { - return io.ErrUnexpectedEOF - } - return err -} - -// Receive receives a message from the backend. The returned message is only valid until the next call to Receive. -func (f *Frontend) Receive() (BackendMessage, error) { - if !f.partialMsg { - header, err := f.cr.Next(5) - if err != nil { - return nil, translateEOFtoErrUnexpectedEOF(err) - } - - f.msgType = header[0] - - msgLength := int(binary.BigEndian.Uint32(header[1:])) - if msgLength < 4 { - return nil, fmt.Errorf("invalid message length: %d", msgLength) - } - - f.bodyLen = msgLength - 4 - if f.maxBodyLen > 0 && f.bodyLen > f.maxBodyLen { - return nil, &ExceededMaxBodyLenErr{f.maxBodyLen, f.bodyLen} - } - f.partialMsg = true - } - - msgBody, err := f.cr.Next(f.bodyLen) - if err != nil { - return nil, translateEOFtoErrUnexpectedEOF(err) - } - - f.partialMsg = false - - var msg BackendMessage - switch f.msgType { - case '1': - msg = &f.parseComplete - case '2': - msg = &f.bindComplete - case '3': - msg = &f.closeComplete - case 'A': - msg = &f.notificationResponse - case 'c': - msg = &f.copyDone - case 'C': - msg = &f.commandComplete - case 'd': - msg = &f.copyData - case 'D': - msg = &f.dataRow - case 'E': - msg = &f.errorResponse - case 'G': - msg = &f.copyInResponse - case 'H': - msg = &f.copyOutResponse - case 'I': - msg = &f.emptyQueryResponse - case 'K': - msg = &f.backendKeyData - case 'n': - msg = &f.noData - case 'N': - msg = &f.noticeResponse - case 'R': - var err error - msg, err = f.findAuthenticationMessageType(msgBody) - if err != nil { - return nil, err - } - case 's': - msg = &f.portalSuspended - case 'S': - msg = &f.parameterStatus - case 't': - msg = &f.parameterDescription - case 'T': - msg = &f.rowDescription - case 'V': - msg = &f.functionCallResponse - case 'W': - msg = &f.copyBothResponse - case 'Z': - msg = &f.readyForQuery - default: - return nil, fmt.Errorf("unknown message type: %c", f.msgType) - } - - err = msg.Decode(msgBody) - if err != nil { - return nil, err - } - - if f.tracer != nil { - f.tracer.traceMessage('B', int32(5+len(msgBody)), msg) - } - - return msg, nil -} - -// Authentication message type constants. -// See src/include/libpq/pqcomm.h for all -// constants. -const ( - AuthTypeOk = 0 - AuthTypeCleartextPassword = 3 - AuthTypeMD5Password = 5 - AuthTypeSCMCreds = 6 - AuthTypeGSS = 7 - AuthTypeGSSCont = 8 - AuthTypeSSPI = 9 - AuthTypeSASL = 10 - AuthTypeSASLContinue = 11 - AuthTypeSASLFinal = 12 -) - -func (f *Frontend) findAuthenticationMessageType(src []byte) (BackendMessage, error) { - if len(src) < 4 { - return nil, errors.New("authentication message too short") - } - f.authType = binary.BigEndian.Uint32(src[:4]) - - switch f.authType { - case AuthTypeOk: - return &f.authenticationOk, nil - case AuthTypeCleartextPassword: - return &f.authenticationCleartextPassword, nil - case AuthTypeMD5Password: - return &f.authenticationMD5Password, nil - case AuthTypeSCMCreds: - return nil, errors.New("AuthTypeSCMCreds is unimplemented") - case AuthTypeGSS: - return &f.authenticationGSS, nil - case AuthTypeGSSCont: - return &f.authenticationGSSContinue, nil - case AuthTypeSSPI: - return nil, errors.New("AuthTypeSSPI is unimplemented") - case AuthTypeSASL: - return &f.authenticationSASL, nil - case AuthTypeSASLContinue: - return &f.authenticationSASLContinue, nil - case AuthTypeSASLFinal: - return &f.authenticationSASLFinal, nil - default: - return nil, fmt.Errorf("unknown authentication type: %d", f.authType) - } -} - -// GetAuthType returns the authType used in the current state of the frontend. -// See SetAuthType for more information. -func (f *Frontend) GetAuthType() uint32 { - return f.authType -} - -func (f *Frontend) ReadBufferLen() int { - return f.cr.wp - f.cr.rp -} - -// SetMaxBodyLen sets the maximum length of a message body in octets. -// If a message body exceeds this length, Receive will return an error. -// This is useful for protecting against a corrupted server that sends -// messages with incorrect length, which can cause memory exhaustion. -// The default value is 0. -// If maxBodyLen is 0, then no maximum is enforced. -func (f *Frontend) SetMaxBodyLen(maxBodyLen int) { - f.maxBodyLen = maxBodyLen -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go deleted file mode 100644 index 7d83579ff..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go +++ /dev/null @@ -1,102 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "errors" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type FunctionCall struct { - Function uint32 - ArgFormatCodes []uint16 - Arguments [][]byte - ResultFormatCode uint16 -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*FunctionCall) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *FunctionCall) Decode(src []byte) error { - *dst = FunctionCall{} - rp := 0 - // Specifies the object ID of the function to call. - dst.Function = binary.BigEndian.Uint32(src[rp:]) - rp += 4 - // The number of argument format codes that follow (denoted C below). - // This can be zero to indicate that there are no arguments or that the arguments all use the default format (text); - // or one, in which case the specified format code is applied to all arguments; - // or it can equal the actual number of arguments. - nArgumentCodes := int(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - argumentCodes := make([]uint16, nArgumentCodes) - for i := 0; i < nArgumentCodes; i++ { - // The argument format codes. Each must presently be zero (text) or one (binary). - ac := binary.BigEndian.Uint16(src[rp:]) - if ac != 0 && ac != 1 { - return &invalidMessageFormatErr{messageType: "FunctionCall"} - } - argumentCodes[i] = ac - rp += 2 - } - dst.ArgFormatCodes = argumentCodes - - // Specifies the number of arguments being supplied to the function. - nArguments := int(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - arguments := make([][]byte, nArguments) - for i := 0; i < nArguments; i++ { - // The length of the argument value, in bytes (this count does not include itself). Can be zero. - // As a special case, -1 indicates a NULL argument value. No value bytes follow in the NULL case. - argumentLength := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - if argumentLength == -1 { - arguments[i] = nil - } else { - // The value of the argument, in the format indicated by the associated format code. n is the above length. - argumentValue := src[rp : rp+argumentLength] - rp += argumentLength - arguments[i] = argumentValue - } - } - dst.Arguments = arguments - // The format code for the function result. Must presently be zero (text) or one (binary). - resultFormatCode := binary.BigEndian.Uint16(src[rp:]) - if resultFormatCode != 0 && resultFormatCode != 1 { - return &invalidMessageFormatErr{messageType: "FunctionCall"} - } - dst.ResultFormatCode = resultFormatCode - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *FunctionCall) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'F') - dst = pgio.AppendUint32(dst, src.Function) - - if len(src.ArgFormatCodes) > math.MaxUint16 { - return nil, errors.New("too many arg format codes") - } - dst = pgio.AppendUint16(dst, uint16(len(src.ArgFormatCodes))) - for _, argFormatCode := range src.ArgFormatCodes { - dst = pgio.AppendUint16(dst, argFormatCode) - } - - if len(src.Arguments) > math.MaxUint16 { - return nil, errors.New("too many arguments") - } - dst = pgio.AppendUint16(dst, uint16(len(src.Arguments))) - for _, argument := range src.Arguments { - if argument == nil { - dst = pgio.AppendInt32(dst, -1) - } else { - dst = pgio.AppendInt32(dst, int32(len(argument))) - dst = append(dst, argument...) - } - } - dst = pgio.AppendUint16(dst, src.ResultFormatCode) - return finishMessage(dst, sp) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go deleted file mode 100644 index 1f2734952..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go +++ /dev/null @@ -1,97 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/hex" - "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type FunctionCallResponse struct { - Result []byte -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*FunctionCallResponse) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *FunctionCallResponse) Decode(src []byte) error { - if len(src) < 4 { - return &invalidMessageFormatErr{messageType: "FunctionCallResponse"} - } - rp := 0 - resultSize := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - if resultSize == -1 { - dst.Result = nil - return nil - } - - if len(src[rp:]) != resultSize { - return &invalidMessageFormatErr{messageType: "FunctionCallResponse"} - } - - dst.Result = src[rp:] - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *FunctionCallResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'V') - - if src.Result == nil { - dst = pgio.AppendInt32(dst, -1) - } else { - dst = pgio.AppendInt32(dst, int32(len(src.Result))) - dst = append(dst, src.Result...) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src FunctionCallResponse) MarshalJSON() ([]byte, error) { - var formattedValue map[string]string - var hasNonPrintable bool - for _, b := range src.Result { - if b < 32 { - hasNonPrintable = true - break - } - } - - if hasNonPrintable { - formattedValue = map[string]string{"binary": hex.EncodeToString(src.Result)} - } else { - formattedValue = map[string]string{"text": string(src.Result)} - } - - return json.Marshal(struct { - Type string - Result map[string]string - }{ - Type: "FunctionCallResponse", - Result: formattedValue, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *FunctionCallResponse) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - Result map[string]string - } - err := json.Unmarshal(data, &msg) - if err != nil { - return err - } - dst.Result, err = getValueFromJSON(msg.Result) - return err -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go deleted file mode 100644 index 70cb20cd5..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go +++ /dev/null @@ -1,49 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -const gssEncReqNumber = 80877104 - -type GSSEncRequest struct { -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*GSSEncRequest) Frontend() {} - -func (dst *GSSEncRequest) Decode(src []byte) error { - if len(src) < 4 { - return errors.New("gss encoding request too short") - } - - requestCode := binary.BigEndian.Uint32(src) - - if requestCode != gssEncReqNumber { - return errors.New("bad gss encoding request code") - } - - return nil -} - -// Encode encodes src into dst. dst will include the 4 byte message length. -func (src *GSSEncRequest) Encode(dst []byte) ([]byte, error) { - dst = pgio.AppendInt32(dst, 8) - dst = pgio.AppendInt32(dst, gssEncReqNumber) - return dst, nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src GSSEncRequest) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ProtocolVersion uint32 - Parameters map[string]string - }{ - Type: "GSSEncRequest", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go deleted file mode 100644 index 10d937759..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go +++ /dev/null @@ -1,46 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type GSSResponse struct { - Data []byte -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (g *GSSResponse) Frontend() {} - -func (g *GSSResponse) Decode(data []byte) error { - g.Data = data - return nil -} - -func (g *GSSResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'p') - dst = append(dst, g.Data...) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (g *GSSResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Data []byte - }{ - Type: "GSSResponse", - Data: g.Data, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (g *GSSResponse) UnmarshalJSON(data []byte) error { - var msg struct { - Data []byte - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - g.Data = msg.Data - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go deleted file mode 100644 index cbcaad40c..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type NoData struct{} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*NoData) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *NoData) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "NoData", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *NoData) Encode(dst []byte) ([]byte, error) { - return append(dst, 'n', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src NoData) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "NoData", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go deleted file mode 100644 index 497aba6dd..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go +++ /dev/null @@ -1,19 +0,0 @@ -package pgproto3 - -type NoticeResponse ErrorResponse - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*NoticeResponse) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *NoticeResponse) Decode(src []byte) error { - return (*ErrorResponse)(dst).Decode(src) -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *NoticeResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'N') - dst = (*ErrorResponse)(src).appendFields(dst) - return finishMessage(dst, sp) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go deleted file mode 100644 index 243b6bf7c..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go +++ /dev/null @@ -1,71 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type NotificationResponse struct { - PID uint32 - Channel string - Payload string -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*NotificationResponse) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *NotificationResponse) Decode(src []byte) error { - buf := bytes.NewBuffer(src) - - if buf.Len() < 4 { - return &invalidMessageFormatErr{messageType: "NotificationResponse", details: "too short"} - } - - pid := binary.BigEndian.Uint32(buf.Next(4)) - - b, err := buf.ReadBytes(0) - if err != nil { - return err - } - channel := string(b[:len(b)-1]) - - b, err = buf.ReadBytes(0) - if err != nil { - return err - } - payload := string(b[:len(b)-1]) - - *dst = NotificationResponse{PID: pid, Channel: channel, Payload: payload} - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *NotificationResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'A') - dst = pgio.AppendUint32(dst, src.PID) - dst = append(dst, src.Channel...) - dst = append(dst, 0) - dst = append(dst, src.Payload...) - dst = append(dst, 0) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src NotificationResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - PID uint32 - Channel string - Payload string - }{ - Type: "NotificationResponse", - PID: src.PID, - Channel: src.Channel, - Payload: src.Payload, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go deleted file mode 100644 index 1ef27b75f..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go +++ /dev/null @@ -1,67 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type ParameterDescription struct { - ParameterOIDs []uint32 -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*ParameterDescription) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *ParameterDescription) Decode(src []byte) error { - buf := bytes.NewBuffer(src) - - if buf.Len() < 2 { - return &invalidMessageFormatErr{messageType: "ParameterDescription"} - } - - // Reported parameter count will be incorrect when number of args is greater than uint16 - buf.Next(2) - // Instead infer parameter count by remaining size of message - parameterCount := buf.Len() / 4 - - *dst = ParameterDescription{ParameterOIDs: make([]uint32, parameterCount)} - - for i := 0; i < parameterCount; i++ { - dst.ParameterOIDs[i] = binary.BigEndian.Uint32(buf.Next(4)) - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ParameterDescription) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 't') - - if len(src.ParameterOIDs) > math.MaxUint16 { - return nil, errors.New("too many parameter oids") - } - dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs))) - for _, oid := range src.ParameterOIDs { - dst = pgio.AppendUint32(dst, oid) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src ParameterDescription) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ParameterOIDs []uint32 - }{ - Type: "ParameterDescription", - ParameterOIDs: src.ParameterOIDs, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go deleted file mode 100644 index 9ee0720b5..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go +++ /dev/null @@ -1,58 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/json" -) - -type ParameterStatus struct { - Name string - Value string -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*ParameterStatus) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *ParameterStatus) Decode(src []byte) error { - buf := bytes.NewBuffer(src) - - b, err := buf.ReadBytes(0) - if err != nil { - return err - } - name := string(b[:len(b)-1]) - - b, err = buf.ReadBytes(0) - if err != nil { - return err - } - value := string(b[:len(b)-1]) - - *dst = ParameterStatus{Name: name, Value: value} - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ParameterStatus) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'S') - dst = append(dst, src.Name...) - dst = append(dst, 0) - dst = append(dst, src.Value...) - dst = append(dst, 0) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (ps ParameterStatus) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Name string - Value string - }{ - Type: "ParameterStatus", - Name: ps.Name, - Value: ps.Value, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go deleted file mode 100644 index 6ba3486cf..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go +++ /dev/null @@ -1,89 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Parse struct { - Name string - Query string - ParameterOIDs []uint32 -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Parse) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Parse) Decode(src []byte) error { - *dst = Parse{} - - buf := bytes.NewBuffer(src) - - b, err := buf.ReadBytes(0) - if err != nil { - return err - } - dst.Name = string(b[:len(b)-1]) - - b, err = buf.ReadBytes(0) - if err != nil { - return err - } - dst.Query = string(b[:len(b)-1]) - - if buf.Len() < 2 { - return &invalidMessageFormatErr{messageType: "Parse"} - } - parameterOIDCount := int(binary.BigEndian.Uint16(buf.Next(2))) - - for i := 0; i < parameterOIDCount; i++ { - if buf.Len() < 4 { - return &invalidMessageFormatErr{messageType: "Parse"} - } - dst.ParameterOIDs = append(dst.ParameterOIDs, binary.BigEndian.Uint32(buf.Next(4))) - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Parse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'P') - - dst = append(dst, src.Name...) - dst = append(dst, 0) - dst = append(dst, src.Query...) - dst = append(dst, 0) - - if len(src.ParameterOIDs) > math.MaxUint16 { - return nil, errors.New("too many parameter oids") - } - dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs))) - for _, oid := range src.ParameterOIDs { - dst = pgio.AppendUint32(dst, oid) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Parse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Name string - Query string - ParameterOIDs []uint32 - }{ - Type: "Parse", - Name: src.Name, - Query: src.Query, - ParameterOIDs: src.ParameterOIDs, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go deleted file mode 100644 index cff9e27d0..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type ParseComplete struct{} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*ParseComplete) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *ParseComplete) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "ParseComplete", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ParseComplete) Encode(dst []byte) ([]byte, error) { - return append(dst, '1', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src ParseComplete) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "ParseComplete", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go b/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go deleted file mode 100644 index d820d3275..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go +++ /dev/null @@ -1,49 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/json" -) - -type PasswordMessage struct { - Password string -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*PasswordMessage) Frontend() {} - -// Frontend identifies this message as an authentication response. -func (*PasswordMessage) InitialResponse() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *PasswordMessage) Decode(src []byte) error { - buf := bytes.NewBuffer(src) - - b, err := buf.ReadBytes(0) - if err != nil { - return err - } - dst.Password = string(b[:len(b)-1]) - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *PasswordMessage) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'p') - dst = append(dst, src.Password...) - dst = append(dst, 0) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src PasswordMessage) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Password string - }{ - Type: "PasswordMessage", - Password: src.Password, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go b/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go deleted file mode 100644 index 128f97f87..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go +++ /dev/null @@ -1,120 +0,0 @@ -package pgproto3 - -import ( - "encoding/hex" - "errors" - "fmt" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// maxMessageBodyLen is the maximum length of a message body in bytes. See PG_LARGE_MESSAGE_LIMIT in the PostgreSQL -// source. It is defined as (MaxAllocSize - 1). MaxAllocSize is defined as 0x3fffffff. -const maxMessageBodyLen = (0x3fffffff - 1) - -// Message is the interface implemented by an object that can decode and encode -// a particular PostgreSQL message. -type Message interface { - // Decode is allowed and expected to retain a reference to data after - // returning (unlike encoding.BinaryUnmarshaler). - Decode(data []byte) error - - // Encode appends itself to dst and returns the new buffer. - Encode(dst []byte) ([]byte, error) -} - -// FrontendMessage is a message sent by the frontend (i.e. the client). -type FrontendMessage interface { - Message - Frontend() // no-op method to distinguish frontend from backend methods -} - -// BackendMessage is a message sent by the backend (i.e. the server). -type BackendMessage interface { - Message - Backend() // no-op method to distinguish frontend from backend methods -} - -type AuthenticationResponseMessage interface { - BackendMessage - AuthenticationResponse() // no-op method to distinguish authentication responses -} - -type invalidMessageLenErr struct { - messageType string - expectedLen int - actualLen int -} - -func (e *invalidMessageLenErr) Error() string { - return fmt.Sprintf("%s body must have length of %d, but it is %d", e.messageType, e.expectedLen, e.actualLen) -} - -type invalidMessageFormatErr struct { - messageType string - details string -} - -func (e *invalidMessageFormatErr) Error() string { - return fmt.Sprintf("%s body is invalid %s", e.messageType, e.details) -} - -type writeError struct { - err error - safeToRetry bool -} - -func (e *writeError) Error() string { - return fmt.Sprintf("write failed: %s", e.err.Error()) -} - -func (e *writeError) SafeToRetry() bool { - return e.safeToRetry -} - -func (e *writeError) Unwrap() error { - return e.err -} - -type ExceededMaxBodyLenErr struct { - MaxExpectedBodyLen int - ActualBodyLen int -} - -func (e *ExceededMaxBodyLenErr) Error() string { - return fmt.Sprintf("invalid body length: expected at most %d, but got %d", e.MaxExpectedBodyLen, e.ActualBodyLen) -} - -// getValueFromJSON gets the value from a protocol message representation in JSON. -func getValueFromJSON(v map[string]string) ([]byte, error) { - if v == nil { - return nil, nil - } - if text, ok := v["text"]; ok { - return []byte(text), nil - } - if binary, ok := v["binary"]; ok { - return hex.DecodeString(binary) - } - return nil, errors.New("unknown protocol representation") -} - -// beginMessage begins a new message of type t. It appends the message type and a placeholder for the message length to -// dst. It returns the new buffer and the position of the message length placeholder. -func beginMessage(dst []byte, t byte) ([]byte, int) { - dst = append(dst, t) - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - return dst, sp -} - -// finishMessage finishes a message that was started with beginMessage. It computes the message length and writes it to -// dst[sp]. If the message length is too large it returns an error. Otherwise it returns the final message buffer. -func finishMessage(dst []byte, sp int) ([]byte, error) { - messageBodyLen := len(dst[sp:]) - if messageBodyLen > maxMessageBodyLen { - return nil, errors.New("message body too large") - } - pgio.SetInt32(dst[sp:], int32(messageBodyLen)) - return dst, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go b/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go deleted file mode 100644 index 9e2f8cbc4..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type PortalSuspended struct{} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*PortalSuspended) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *PortalSuspended) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "PortalSuspended", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *PortalSuspended) Encode(dst []byte) ([]byte, error) { - return append(dst, 's', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src PortalSuspended) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "PortalSuspended", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/query.go b/vendor/github.com/jackc/pgx/v5/pgproto3/query.go deleted file mode 100644 index aebdfde89..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/query.go +++ /dev/null @@ -1,45 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/json" -) - -type Query struct { - String string -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Query) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Query) Decode(src []byte) error { - i := bytes.IndexByte(src, 0) - if i != len(src)-1 { - return &invalidMessageFormatErr{messageType: "Query"} - } - - dst.String = string(src[:i]) - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Query) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'Q') - dst = append(dst, src.String...) - dst = append(dst, 0) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Query) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - String string - }{ - Type: "Query", - String: src.String, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go b/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go deleted file mode 100644 index a56af9fb2..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go +++ /dev/null @@ -1,61 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" - "errors" -) - -type ReadyForQuery struct { - TxStatus byte -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*ReadyForQuery) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *ReadyForQuery) Decode(src []byte) error { - if len(src) != 1 { - return &invalidMessageLenErr{messageType: "ReadyForQuery", expectedLen: 1, actualLen: len(src)} - } - - dst.TxStatus = src[0] - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *ReadyForQuery) Encode(dst []byte) ([]byte, error) { - return append(dst, 'Z', 0, 0, 0, 5, src.TxStatus), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src ReadyForQuery) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - TxStatus string - }{ - Type: "ReadyForQuery", - TxStatus: string(src.TxStatus), - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *ReadyForQuery) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - TxStatus string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - if len(msg.TxStatus) != 1 { - return errors.New("invalid length for ReadyForQuery.TxStatus") - } - dst.TxStatus = msg.TxStatus[0] - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go b/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go deleted file mode 100644 index dc2a4ddf2..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go +++ /dev/null @@ -1,166 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - "math" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -const ( - TextFormat = 0 - BinaryFormat = 1 -) - -type FieldDescription struct { - Name []byte - TableOID uint32 - TableAttributeNumber uint16 - DataTypeOID uint32 - DataTypeSize int16 - TypeModifier int32 - Format int16 -} - -// MarshalJSON implements encoding/json.Marshaler. -func (fd FieldDescription) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Name string - TableOID uint32 - TableAttributeNumber uint16 - DataTypeOID uint32 - DataTypeSize int16 - TypeModifier int32 - Format int16 - }{ - Name: string(fd.Name), - TableOID: fd.TableOID, - TableAttributeNumber: fd.TableAttributeNumber, - DataTypeOID: fd.DataTypeOID, - DataTypeSize: fd.DataTypeSize, - TypeModifier: fd.TypeModifier, - Format: fd.Format, - }) -} - -type RowDescription struct { - Fields []FieldDescription -} - -// Backend identifies this message as sendable by the PostgreSQL backend. -func (*RowDescription) Backend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *RowDescription) Decode(src []byte) error { - - if len(src) < 2 { - return &invalidMessageFormatErr{messageType: "RowDescription"} - } - fieldCount := int(binary.BigEndian.Uint16(src)) - rp := 2 - - dst.Fields = dst.Fields[0:0] - - for i := 0; i < fieldCount; i++ { - var fd FieldDescription - - idx := bytes.IndexByte(src[rp:], 0) - if idx < 0 { - return &invalidMessageFormatErr{messageType: "RowDescription"} - } - fd.Name = src[rp : rp+idx] - rp += idx + 1 - - // Since buf.Next() doesn't return an error if we hit the end of the buffer - // check Len ahead of time - if len(src[rp:]) < 18 { - return &invalidMessageFormatErr{messageType: "RowDescription"} - } - - fd.TableOID = binary.BigEndian.Uint32(src[rp:]) - rp += 4 - fd.TableAttributeNumber = binary.BigEndian.Uint16(src[rp:]) - rp += 2 - fd.DataTypeOID = binary.BigEndian.Uint32(src[rp:]) - rp += 4 - fd.DataTypeSize = int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - fd.TypeModifier = int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - fd.Format = int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - - dst.Fields = append(dst.Fields, fd) - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *RowDescription) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'T') - - if len(src.Fields) > math.MaxUint16 { - return nil, errors.New("too many fields") - } - dst = pgio.AppendUint16(dst, uint16(len(src.Fields))) - for _, fd := range src.Fields { - dst = append(dst, fd.Name...) - dst = append(dst, 0) - - dst = pgio.AppendUint32(dst, fd.TableOID) - dst = pgio.AppendUint16(dst, fd.TableAttributeNumber) - dst = pgio.AppendUint32(dst, fd.DataTypeOID) - dst = pgio.AppendInt16(dst, fd.DataTypeSize) - dst = pgio.AppendInt32(dst, fd.TypeModifier) - dst = pgio.AppendInt16(dst, fd.Format) - } - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src RowDescription) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Fields []FieldDescription - }{ - Type: "RowDescription", - Fields: src.Fields, - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *RowDescription) UnmarshalJSON(data []byte) error { - var msg struct { - Fields []struct { - Name string - TableOID uint32 - TableAttributeNumber uint16 - DataTypeOID uint32 - DataTypeSize int16 - TypeModifier int32 - Format int16 - } - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - dst.Fields = make([]FieldDescription, len(msg.Fields)) - for n, field := range msg.Fields { - dst.Fields[n] = FieldDescription{ - Name: []byte(field.Name), - TableOID: field.TableOID, - TableAttributeNumber: field.TableAttributeNumber, - DataTypeOID: field.DataTypeOID, - DataTypeSize: field.DataTypeSize, - TypeModifier: field.TypeModifier, - Format: field.Format, - } - } - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go deleted file mode 100644 index 9eb1b6a4b..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go +++ /dev/null @@ -1,90 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/hex" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type SASLInitialResponse struct { - AuthMechanism string - Data []byte -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*SASLInitialResponse) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *SASLInitialResponse) Decode(src []byte) error { - *dst = SASLInitialResponse{} - - rp := 0 - - idx := bytes.IndexByte(src, 0) - if idx < 0 { - return errors.New("invalid SASLInitialResponse") - } - - dst.AuthMechanism = string(src[rp:idx]) - rp = idx + 1 - - rp += 4 // The rest of the message is data so we can just skip the size - dst.Data = src[rp:] - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *SASLInitialResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'p') - - dst = append(dst, []byte(src.AuthMechanism)...) - dst = append(dst, 0) - - dst = pgio.AppendInt32(dst, int32(len(src.Data))) - dst = append(dst, src.Data...) - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src SASLInitialResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - AuthMechanism string - Data string - }{ - Type: "SASLInitialResponse", - AuthMechanism: src.AuthMechanism, - Data: string(src.Data), - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *SASLInitialResponse) UnmarshalJSON(data []byte) error { - // Ignore null, like in the main JSON package. - if string(data) == "null" { - return nil - } - - var msg struct { - AuthMechanism string - Data string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - dst.AuthMechanism = msg.AuthMechanism - if msg.Data != "" { - decoded, err := hex.DecodeString(msg.Data) - if err != nil { - return err - } - dst.Data = decoded - } - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go deleted file mode 100644 index 1b604c254..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go +++ /dev/null @@ -1,56 +0,0 @@ -package pgproto3 - -import ( - "encoding/hex" - "encoding/json" -) - -type SASLResponse struct { - Data []byte -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*SASLResponse) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *SASLResponse) Decode(src []byte) error { - *dst = SASLResponse{Data: src} - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *SASLResponse) Encode(dst []byte) ([]byte, error) { - dst, sp := beginMessage(dst, 'p') - dst = append(dst, src.Data...) - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src SASLResponse) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - Data string - }{ - Type: "SASLResponse", - Data: string(src.Data), - }) -} - -// UnmarshalJSON implements encoding/json.Unmarshaler. -func (dst *SASLResponse) UnmarshalJSON(data []byte) error { - var msg struct { - Data string - } - if err := json.Unmarshal(data, &msg); err != nil { - return err - } - if msg.Data != "" { - decoded, err := hex.DecodeString(msg.Data) - if err != nil { - return err - } - dst.Data = decoded - } - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go deleted file mode 100644 index b0fc28476..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go +++ /dev/null @@ -1,49 +0,0 @@ -package pgproto3 - -import ( - "encoding/binary" - "encoding/json" - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -const sslRequestNumber = 80877103 - -type SSLRequest struct { -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*SSLRequest) Frontend() {} - -func (dst *SSLRequest) Decode(src []byte) error { - if len(src) < 4 { - return errors.New("ssl request too short") - } - - requestCode := binary.BigEndian.Uint32(src) - - if requestCode != sslRequestNumber { - return errors.New("bad ssl request code") - } - - return nil -} - -// Encode encodes src into dst. dst will include the 4 byte message length. -func (src *SSLRequest) Encode(dst []byte) ([]byte, error) { - dst = pgio.AppendInt32(dst, 8) - dst = pgio.AppendInt32(dst, sslRequestNumber) - return dst, nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src SSLRequest) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ProtocolVersion uint32 - Parameters map[string]string - }{ - Type: "SSLRequest", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go deleted file mode 100644 index 3af4587d8..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go +++ /dev/null @@ -1,94 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - "fmt" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -const ProtocolVersionNumber = 196608 // 3.0 - -type StartupMessage struct { - ProtocolVersion uint32 - Parameters map[string]string -} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*StartupMessage) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *StartupMessage) Decode(src []byte) error { - if len(src) < 4 { - return errors.New("startup message too short") - } - - dst.ProtocolVersion = binary.BigEndian.Uint32(src) - rp := 4 - - if dst.ProtocolVersion != ProtocolVersionNumber { - return fmt.Errorf("Bad startup message version number. Expected %d, got %d", ProtocolVersionNumber, dst.ProtocolVersion) - } - - dst.Parameters = make(map[string]string) - for { - idx := bytes.IndexByte(src[rp:], 0) - if idx < 0 { - return &invalidMessageFormatErr{messageType: "StartupMessage"} - } - key := string(src[rp : rp+idx]) - rp += idx + 1 - - idx = bytes.IndexByte(src[rp:], 0) - if idx < 0 { - return &invalidMessageFormatErr{messageType: "StartupMessage"} - } - value := string(src[rp : rp+idx]) - rp += idx + 1 - - dst.Parameters[key] = value - - if len(src[rp:]) == 1 { - if src[rp] != 0 { - return fmt.Errorf("Bad startup message last byte. Expected 0, got %d", src[rp]) - } - break - } - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *StartupMessage) Encode(dst []byte) ([]byte, error) { - sp := len(dst) - dst = pgio.AppendInt32(dst, -1) - - dst = pgio.AppendUint32(dst, src.ProtocolVersion) - for k, v := range src.Parameters { - dst = append(dst, k...) - dst = append(dst, 0) - dst = append(dst, v...) - dst = append(dst, 0) - } - dst = append(dst, 0) - - return finishMessage(dst, sp) -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src StartupMessage) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - ProtocolVersion uint32 - Parameters map[string]string - }{ - Type: "StartupMessage", - ProtocolVersion: src.ProtocolVersion, - Parameters: src.Parameters, - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go deleted file mode 100644 index ea4fc9594..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type Sync struct{} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Sync) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Sync) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "Sync", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Sync) Encode(dst []byte) ([]byte, error) { - return append(dst, 'S', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Sync) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "Sync", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go b/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go deleted file mode 100644 index 35a9dc837..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go +++ /dev/null @@ -1,34 +0,0 @@ -package pgproto3 - -import ( - "encoding/json" -) - -type Terminate struct{} - -// Frontend identifies this message as sendable by a PostgreSQL frontend. -func (*Terminate) Frontend() {} - -// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message -// type identifier and 4 byte message length. -func (dst *Terminate) Decode(src []byte) error { - if len(src) != 0 { - return &invalidMessageLenErr{messageType: "Terminate", expectedLen: 0, actualLen: len(src)} - } - - return nil -} - -// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. -func (src *Terminate) Encode(dst []byte) ([]byte, error) { - return append(dst, 'X', 0, 0, 0, 4), nil -} - -// MarshalJSON implements encoding/json.Marshaler. -func (src Terminate) MarshalJSON() ([]byte, error) { - return json.Marshal(struct { - Type string - }{ - Type: "Terminate", - }) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/trace.go b/vendor/github.com/jackc/pgx/v5/pgproto3/trace.go deleted file mode 100644 index 6cc7d3e36..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgproto3/trace.go +++ /dev/null @@ -1,416 +0,0 @@ -package pgproto3 - -import ( - "bytes" - "fmt" - "io" - "strconv" - "strings" - "sync" - "time" -) - -// tracer traces the messages send to and from a Backend or Frontend. The format it produces roughly mimics the -// format produced by the libpq C function PQtrace. -type tracer struct { - TracerOptions - - mux sync.Mutex - w io.Writer - buf *bytes.Buffer -} - -// TracerOptions controls tracing behavior. It is roughly equivalent to the libpq function PQsetTraceFlags. -type TracerOptions struct { - // SuppressTimestamps prevents printing of timestamps. - SuppressTimestamps bool - - // RegressMode redacts fields that may be vary between executions. - RegressMode bool -} - -func (t *tracer) traceMessage(sender byte, encodedLen int32, msg Message) { - switch msg := msg.(type) { - case *AuthenticationCleartextPassword: - t.traceAuthenticationCleartextPassword(sender, encodedLen, msg) - case *AuthenticationGSS: - t.traceAuthenticationGSS(sender, encodedLen, msg) - case *AuthenticationGSSContinue: - t.traceAuthenticationGSSContinue(sender, encodedLen, msg) - case *AuthenticationMD5Password: - t.traceAuthenticationMD5Password(sender, encodedLen, msg) - case *AuthenticationOk: - t.traceAuthenticationOk(sender, encodedLen, msg) - case *AuthenticationSASL: - t.traceAuthenticationSASL(sender, encodedLen, msg) - case *AuthenticationSASLContinue: - t.traceAuthenticationSASLContinue(sender, encodedLen, msg) - case *AuthenticationSASLFinal: - t.traceAuthenticationSASLFinal(sender, encodedLen, msg) - case *BackendKeyData: - t.traceBackendKeyData(sender, encodedLen, msg) - case *Bind: - t.traceBind(sender, encodedLen, msg) - case *BindComplete: - t.traceBindComplete(sender, encodedLen, msg) - case *CancelRequest: - t.traceCancelRequest(sender, encodedLen, msg) - case *Close: - t.traceClose(sender, encodedLen, msg) - case *CloseComplete: - t.traceCloseComplete(sender, encodedLen, msg) - case *CommandComplete: - t.traceCommandComplete(sender, encodedLen, msg) - case *CopyBothResponse: - t.traceCopyBothResponse(sender, encodedLen, msg) - case *CopyData: - t.traceCopyData(sender, encodedLen, msg) - case *CopyDone: - t.traceCopyDone(sender, encodedLen, msg) - case *CopyFail: - t.traceCopyFail(sender, encodedLen, msg) - case *CopyInResponse: - t.traceCopyInResponse(sender, encodedLen, msg) - case *CopyOutResponse: - t.traceCopyOutResponse(sender, encodedLen, msg) - case *DataRow: - t.traceDataRow(sender, encodedLen, msg) - case *Describe: - t.traceDescribe(sender, encodedLen, msg) - case *EmptyQueryResponse: - t.traceEmptyQueryResponse(sender, encodedLen, msg) - case *ErrorResponse: - t.traceErrorResponse(sender, encodedLen, msg) - case *Execute: - t.TraceQueryute(sender, encodedLen, msg) - case *Flush: - t.traceFlush(sender, encodedLen, msg) - case *FunctionCall: - t.traceFunctionCall(sender, encodedLen, msg) - case *FunctionCallResponse: - t.traceFunctionCallResponse(sender, encodedLen, msg) - case *GSSEncRequest: - t.traceGSSEncRequest(sender, encodedLen, msg) - case *NoData: - t.traceNoData(sender, encodedLen, msg) - case *NoticeResponse: - t.traceNoticeResponse(sender, encodedLen, msg) - case *NotificationResponse: - t.traceNotificationResponse(sender, encodedLen, msg) - case *ParameterDescription: - t.traceParameterDescription(sender, encodedLen, msg) - case *ParameterStatus: - t.traceParameterStatus(sender, encodedLen, msg) - case *Parse: - t.traceParse(sender, encodedLen, msg) - case *ParseComplete: - t.traceParseComplete(sender, encodedLen, msg) - case *PortalSuspended: - t.tracePortalSuspended(sender, encodedLen, msg) - case *Query: - t.traceQuery(sender, encodedLen, msg) - case *ReadyForQuery: - t.traceReadyForQuery(sender, encodedLen, msg) - case *RowDescription: - t.traceRowDescription(sender, encodedLen, msg) - case *SSLRequest: - t.traceSSLRequest(sender, encodedLen, msg) - case *StartupMessage: - t.traceStartupMessage(sender, encodedLen, msg) - case *Sync: - t.traceSync(sender, encodedLen, msg) - case *Terminate: - t.traceTerminate(sender, encodedLen, msg) - default: - t.writeTrace(sender, encodedLen, "Unknown", nil) - } -} - -func (t *tracer) traceAuthenticationCleartextPassword(sender byte, encodedLen int32, msg *AuthenticationCleartextPassword) { - t.writeTrace(sender, encodedLen, "AuthenticationCleartextPassword", nil) -} - -func (t *tracer) traceAuthenticationGSS(sender byte, encodedLen int32, msg *AuthenticationGSS) { - t.writeTrace(sender, encodedLen, "AuthenticationGSS", nil) -} - -func (t *tracer) traceAuthenticationGSSContinue(sender byte, encodedLen int32, msg *AuthenticationGSSContinue) { - t.writeTrace(sender, encodedLen, "AuthenticationGSSContinue", nil) -} - -func (t *tracer) traceAuthenticationMD5Password(sender byte, encodedLen int32, msg *AuthenticationMD5Password) { - t.writeTrace(sender, encodedLen, "AuthenticationMD5Password", nil) -} - -func (t *tracer) traceAuthenticationOk(sender byte, encodedLen int32, msg *AuthenticationOk) { - t.writeTrace(sender, encodedLen, "AuthenticationOk", nil) -} - -func (t *tracer) traceAuthenticationSASL(sender byte, encodedLen int32, msg *AuthenticationSASL) { - t.writeTrace(sender, encodedLen, "AuthenticationSASL", nil) -} - -func (t *tracer) traceAuthenticationSASLContinue(sender byte, encodedLen int32, msg *AuthenticationSASLContinue) { - t.writeTrace(sender, encodedLen, "AuthenticationSASLContinue", nil) -} - -func (t *tracer) traceAuthenticationSASLFinal(sender byte, encodedLen int32, msg *AuthenticationSASLFinal) { - t.writeTrace(sender, encodedLen, "AuthenticationSASLFinal", nil) -} - -func (t *tracer) traceBackendKeyData(sender byte, encodedLen int32, msg *BackendKeyData) { - t.writeTrace(sender, encodedLen, "BackendKeyData", func() { - if t.RegressMode { - t.buf.WriteString("\t NNNN NNNN") - } else { - fmt.Fprintf(t.buf, "\t %d %d", msg.ProcessID, msg.SecretKey) - } - }) -} - -func (t *tracer) traceBind(sender byte, encodedLen int32, msg *Bind) { - t.writeTrace(sender, encodedLen, "Bind", func() { - fmt.Fprintf(t.buf, "\t %s %s %d", traceDoubleQuotedString([]byte(msg.DestinationPortal)), traceDoubleQuotedString([]byte(msg.PreparedStatement)), len(msg.ParameterFormatCodes)) - for _, fc := range msg.ParameterFormatCodes { - fmt.Fprintf(t.buf, " %d", fc) - } - fmt.Fprintf(t.buf, " %d", len(msg.Parameters)) - for _, p := range msg.Parameters { - fmt.Fprintf(t.buf, " %s", traceSingleQuotedString(p)) - } - fmt.Fprintf(t.buf, " %d", len(msg.ResultFormatCodes)) - for _, fc := range msg.ResultFormatCodes { - fmt.Fprintf(t.buf, " %d", fc) - } - }) -} - -func (t *tracer) traceBindComplete(sender byte, encodedLen int32, msg *BindComplete) { - t.writeTrace(sender, encodedLen, "BindComplete", nil) -} - -func (t *tracer) traceCancelRequest(sender byte, encodedLen int32, msg *CancelRequest) { - t.writeTrace(sender, encodedLen, "CancelRequest", nil) -} - -func (t *tracer) traceClose(sender byte, encodedLen int32, msg *Close) { - t.writeTrace(sender, encodedLen, "Close", nil) -} - -func (t *tracer) traceCloseComplete(sender byte, encodedLen int32, msg *CloseComplete) { - t.writeTrace(sender, encodedLen, "CloseComplete", nil) -} - -func (t *tracer) traceCommandComplete(sender byte, encodedLen int32, msg *CommandComplete) { - t.writeTrace(sender, encodedLen, "CommandComplete", func() { - fmt.Fprintf(t.buf, "\t %s", traceDoubleQuotedString(msg.CommandTag)) - }) -} - -func (t *tracer) traceCopyBothResponse(sender byte, encodedLen int32, msg *CopyBothResponse) { - t.writeTrace(sender, encodedLen, "CopyBothResponse", nil) -} - -func (t *tracer) traceCopyData(sender byte, encodedLen int32, msg *CopyData) { - t.writeTrace(sender, encodedLen, "CopyData", nil) -} - -func (t *tracer) traceCopyDone(sender byte, encodedLen int32, msg *CopyDone) { - t.writeTrace(sender, encodedLen, "CopyDone", nil) -} - -func (t *tracer) traceCopyFail(sender byte, encodedLen int32, msg *CopyFail) { - t.writeTrace(sender, encodedLen, "CopyFail", func() { - fmt.Fprintf(t.buf, "\t %s", traceDoubleQuotedString([]byte(msg.Message))) - }) -} - -func (t *tracer) traceCopyInResponse(sender byte, encodedLen int32, msg *CopyInResponse) { - t.writeTrace(sender, encodedLen, "CopyInResponse", nil) -} - -func (t *tracer) traceCopyOutResponse(sender byte, encodedLen int32, msg *CopyOutResponse) { - t.writeTrace(sender, encodedLen, "CopyOutResponse", nil) -} - -func (t *tracer) traceDataRow(sender byte, encodedLen int32, msg *DataRow) { - t.writeTrace(sender, encodedLen, "DataRow", func() { - fmt.Fprintf(t.buf, "\t %d", len(msg.Values)) - for _, v := range msg.Values { - if v == nil { - t.buf.WriteString(" -1") - } else { - fmt.Fprintf(t.buf, " %d %s", len(v), traceSingleQuotedString(v)) - } - } - }) -} - -func (t *tracer) traceDescribe(sender byte, encodedLen int32, msg *Describe) { - t.writeTrace(sender, encodedLen, "Describe", func() { - fmt.Fprintf(t.buf, "\t %c %s", msg.ObjectType, traceDoubleQuotedString([]byte(msg.Name))) - }) -} - -func (t *tracer) traceEmptyQueryResponse(sender byte, encodedLen int32, msg *EmptyQueryResponse) { - t.writeTrace(sender, encodedLen, "EmptyQueryResponse", nil) -} - -func (t *tracer) traceErrorResponse(sender byte, encodedLen int32, msg *ErrorResponse) { - t.writeTrace(sender, encodedLen, "ErrorResponse", nil) -} - -func (t *tracer) TraceQueryute(sender byte, encodedLen int32, msg *Execute) { - t.writeTrace(sender, encodedLen, "Execute", func() { - fmt.Fprintf(t.buf, "\t %s %d", traceDoubleQuotedString([]byte(msg.Portal)), msg.MaxRows) - }) -} - -func (t *tracer) traceFlush(sender byte, encodedLen int32, msg *Flush) { - t.writeTrace(sender, encodedLen, "Flush", nil) -} - -func (t *tracer) traceFunctionCall(sender byte, encodedLen int32, msg *FunctionCall) { - t.writeTrace(sender, encodedLen, "FunctionCall", nil) -} - -func (t *tracer) traceFunctionCallResponse(sender byte, encodedLen int32, msg *FunctionCallResponse) { - t.writeTrace(sender, encodedLen, "FunctionCallResponse", nil) -} - -func (t *tracer) traceGSSEncRequest(sender byte, encodedLen int32, msg *GSSEncRequest) { - t.writeTrace(sender, encodedLen, "GSSEncRequest", nil) -} - -func (t *tracer) traceNoData(sender byte, encodedLen int32, msg *NoData) { - t.writeTrace(sender, encodedLen, "NoData", nil) -} - -func (t *tracer) traceNoticeResponse(sender byte, encodedLen int32, msg *NoticeResponse) { - t.writeTrace(sender, encodedLen, "NoticeResponse", nil) -} - -func (t *tracer) traceNotificationResponse(sender byte, encodedLen int32, msg *NotificationResponse) { - t.writeTrace(sender, encodedLen, "NotificationResponse", func() { - fmt.Fprintf(t.buf, "\t %d %s %s", msg.PID, traceDoubleQuotedString([]byte(msg.Channel)), traceDoubleQuotedString([]byte(msg.Payload))) - }) -} - -func (t *tracer) traceParameterDescription(sender byte, encodedLen int32, msg *ParameterDescription) { - t.writeTrace(sender, encodedLen, "ParameterDescription", nil) -} - -func (t *tracer) traceParameterStatus(sender byte, encodedLen int32, msg *ParameterStatus) { - t.writeTrace(sender, encodedLen, "ParameterStatus", func() { - fmt.Fprintf(t.buf, "\t %s %s", traceDoubleQuotedString([]byte(msg.Name)), traceDoubleQuotedString([]byte(msg.Value))) - }) -} - -func (t *tracer) traceParse(sender byte, encodedLen int32, msg *Parse) { - t.writeTrace(sender, encodedLen, "Parse", func() { - fmt.Fprintf(t.buf, "\t %s %s %d", traceDoubleQuotedString([]byte(msg.Name)), traceDoubleQuotedString([]byte(msg.Query)), len(msg.ParameterOIDs)) - for _, oid := range msg.ParameterOIDs { - fmt.Fprintf(t.buf, " %d", oid) - } - }) -} - -func (t *tracer) traceParseComplete(sender byte, encodedLen int32, msg *ParseComplete) { - t.writeTrace(sender, encodedLen, "ParseComplete", nil) -} - -func (t *tracer) tracePortalSuspended(sender byte, encodedLen int32, msg *PortalSuspended) { - t.writeTrace(sender, encodedLen, "PortalSuspended", nil) -} - -func (t *tracer) traceQuery(sender byte, encodedLen int32, msg *Query) { - t.writeTrace(sender, encodedLen, "Query", func() { - fmt.Fprintf(t.buf, "\t %s", traceDoubleQuotedString([]byte(msg.String))) - }) -} - -func (t *tracer) traceReadyForQuery(sender byte, encodedLen int32, msg *ReadyForQuery) { - t.writeTrace(sender, encodedLen, "ReadyForQuery", func() { - fmt.Fprintf(t.buf, "\t %c", msg.TxStatus) - }) -} - -func (t *tracer) traceRowDescription(sender byte, encodedLen int32, msg *RowDescription) { - t.writeTrace(sender, encodedLen, "RowDescription", func() { - fmt.Fprintf(t.buf, "\t %d", len(msg.Fields)) - for _, fd := range msg.Fields { - fmt.Fprintf(t.buf, ` %s %d %d %d %d %d %d`, traceDoubleQuotedString(fd.Name), fd.TableOID, fd.TableAttributeNumber, fd.DataTypeOID, fd.DataTypeSize, fd.TypeModifier, fd.Format) - } - }) -} - -func (t *tracer) traceSSLRequest(sender byte, encodedLen int32, msg *SSLRequest) { - t.writeTrace(sender, encodedLen, "SSLRequest", nil) -} - -func (t *tracer) traceStartupMessage(sender byte, encodedLen int32, msg *StartupMessage) { - t.writeTrace(sender, encodedLen, "StartupMessage", nil) -} - -func (t *tracer) traceSync(sender byte, encodedLen int32, msg *Sync) { - t.writeTrace(sender, encodedLen, "Sync", nil) -} - -func (t *tracer) traceTerminate(sender byte, encodedLen int32, msg *Terminate) { - t.writeTrace(sender, encodedLen, "Terminate", nil) -} - -func (t *tracer) writeTrace(sender byte, encodedLen int32, msgType string, writeDetails func()) { - t.mux.Lock() - defer t.mux.Unlock() - defer func() { - if t.buf.Cap() > 1024 { - t.buf = &bytes.Buffer{} - } else { - t.buf.Reset() - } - }() - - if !t.SuppressTimestamps { - now := time.Now() - t.buf.WriteString(now.Format("2006-01-02 15:04:05.000000")) - t.buf.WriteByte('\t') - } - - t.buf.WriteByte(sender) - t.buf.WriteByte('\t') - t.buf.WriteString(msgType) - t.buf.WriteByte('\t') - t.buf.WriteString(strconv.FormatInt(int64(encodedLen), 10)) - - if writeDetails != nil { - writeDetails() - } - - t.buf.WriteByte('\n') - t.buf.WriteTo(t.w) -} - -// traceDoubleQuotedString returns t.buf as a double-quoted string without any escaping. It is roughly equivalent to -// pqTraceOutputString in libpq. -func traceDoubleQuotedString(buf []byte) string { - return `"` + string(buf) + `"` -} - -// traceSingleQuotedString returns buf as a single-quoted string with non-printable characters hex-escaped. It is -// roughly equivalent to pqTraceOutputNchar in libpq. -func traceSingleQuotedString(buf []byte) string { - sb := &strings.Builder{} - - sb.WriteByte('\'') - for _, b := range buf { - if b < 32 || b > 126 { - fmt.Fprintf(sb, `\x%x`, b) - } else { - sb.WriteByte(b) - } - } - sb.WriteByte('\'') - - return sb.String() -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array.go b/vendor/github.com/jackc/pgx/v5/pgtype/array.go deleted file mode 100644 index 06b824ad0..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/array.go +++ /dev/null @@ -1,460 +0,0 @@ -package pgtype - -import ( - "bytes" - "encoding/binary" - "fmt" - "io" - "strconv" - "strings" - "unicode" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// Information on the internals of PostgreSQL arrays can be found in -// src/include/utils/array.h and src/backend/utils/adt/arrayfuncs.c. Of -// particular interest is the array_send function. - -type arrayHeader struct { - ContainsNull bool - ElementOID uint32 - Dimensions []ArrayDimension -} - -type ArrayDimension struct { - Length int32 - LowerBound int32 -} - -// cardinality returns the number of elements in an array of dimensions size. -func cardinality(dimensions []ArrayDimension) int { - if len(dimensions) == 0 { - return 0 - } - - elementCount := int(dimensions[0].Length) - for _, d := range dimensions[1:] { - elementCount *= int(d.Length) - } - - return elementCount -} - -func (dst *arrayHeader) DecodeBinary(m *Map, src []byte) (int, error) { - if len(src) < 12 { - return 0, fmt.Errorf("array header too short: %d", len(src)) - } - - rp := 0 - - numDims := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - dst.ContainsNull = binary.BigEndian.Uint32(src[rp:]) == 1 - rp += 4 - - dst.ElementOID = binary.BigEndian.Uint32(src[rp:]) - rp += 4 - - dst.Dimensions = make([]ArrayDimension, numDims) - if len(src) < 12+numDims*8 { - return 0, fmt.Errorf("array header too short for %d dimensions: %d", numDims, len(src)) - } - for i := range dst.Dimensions { - dst.Dimensions[i].Length = int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - dst.Dimensions[i].LowerBound = int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - } - - return rp, nil -} - -func (src arrayHeader) EncodeBinary(buf []byte) []byte { - buf = pgio.AppendInt32(buf, int32(len(src.Dimensions))) - - var containsNull int32 - if src.ContainsNull { - containsNull = 1 - } - buf = pgio.AppendInt32(buf, containsNull) - - buf = pgio.AppendUint32(buf, src.ElementOID) - - for i := range src.Dimensions { - buf = pgio.AppendInt32(buf, src.Dimensions[i].Length) - buf = pgio.AppendInt32(buf, src.Dimensions[i].LowerBound) - } - - return buf -} - -type untypedTextArray struct { - Elements []string - Quoted []bool - Dimensions []ArrayDimension -} - -func parseUntypedTextArray(src string) (*untypedTextArray, error) { - dst := &untypedTextArray{ - Elements: []string{}, - Quoted: []bool{}, - Dimensions: []ArrayDimension{}, - } - - buf := bytes.NewBufferString(src) - - skipWhitespace(buf) - - r, _, err := buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - var explicitDimensions []ArrayDimension - - // Array has explicit dimensions - if r == '[' { - buf.UnreadRune() - - for { - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - if r == '=' { - break - } else if r != '[' { - return nil, fmt.Errorf("invalid array, expected '[' or '=' got %v", r) - } - - lower, err := arrayParseInteger(buf) - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - if r != ':' { - return nil, fmt.Errorf("invalid array, expected ':' got %v", r) - } - - upper, err := arrayParseInteger(buf) - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - if r != ']' { - return nil, fmt.Errorf("invalid array, expected ']' got %v", r) - } - - explicitDimensions = append(explicitDimensions, ArrayDimension{LowerBound: lower, Length: upper - lower + 1}) - } - - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - } - - if r != '{' { - return nil, fmt.Errorf("invalid array, expected '{' got %v", r) - } - - implicitDimensions := []ArrayDimension{{LowerBound: 1, Length: 0}} - - // Consume all initial opening brackets. This provides number of dimensions. - for { - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - if r == '{' { - implicitDimensions[len(implicitDimensions)-1].Length = 1 - implicitDimensions = append(implicitDimensions, ArrayDimension{LowerBound: 1}) - } else { - buf.UnreadRune() - break - } - } - currentDim := len(implicitDimensions) - 1 - counterDim := currentDim - - for { - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - switch r { - case '{': - if currentDim == counterDim { - implicitDimensions[currentDim].Length++ - } - currentDim++ - case ',': - case '}': - currentDim-- - if currentDim < counterDim { - counterDim = currentDim - } - default: - buf.UnreadRune() - value, quoted, err := arrayParseValue(buf) - if err != nil { - return nil, fmt.Errorf("invalid array value: %w", err) - } - if currentDim == counterDim { - implicitDimensions[currentDim].Length++ - } - dst.Quoted = append(dst.Quoted, quoted) - dst.Elements = append(dst.Elements, value) - } - - if currentDim < 0 { - break - } - } - - skipWhitespace(buf) - - if buf.Len() > 0 { - return nil, fmt.Errorf("unexpected trailing data: %v", buf.String()) - } - - if len(dst.Elements) == 0 { - } else if len(explicitDimensions) > 0 { - dst.Dimensions = explicitDimensions - } else { - dst.Dimensions = implicitDimensions - } - - return dst, nil -} - -func skipWhitespace(buf *bytes.Buffer) { - var r rune - var err error - for r, _, _ = buf.ReadRune(); unicode.IsSpace(r); r, _, _ = buf.ReadRune() { - } - - if err != io.EOF { - buf.UnreadRune() - } -} - -func arrayParseValue(buf *bytes.Buffer) (string, bool, error) { - r, _, err := buf.ReadRune() - if err != nil { - return "", false, err - } - if r == '"' { - return arrayParseQuotedValue(buf) - } - buf.UnreadRune() - - s := &bytes.Buffer{} - - for { - r, _, err := buf.ReadRune() - if err != nil { - return "", false, err - } - - switch r { - case ',', '}': - buf.UnreadRune() - return s.String(), false, nil - } - - s.WriteRune(r) - } -} - -func arrayParseQuotedValue(buf *bytes.Buffer) (string, bool, error) { - s := &bytes.Buffer{} - - for { - r, _, err := buf.ReadRune() - if err != nil { - return "", false, err - } - - switch r { - case '\\': - r, _, err = buf.ReadRune() - if err != nil { - return "", false, err - } - case '"': - r, _, err = buf.ReadRune() - if err != nil { - return "", false, err - } - buf.UnreadRune() - return s.String(), true, nil - } - s.WriteRune(r) - } -} - -func arrayParseInteger(buf *bytes.Buffer) (int32, error) { - s := &bytes.Buffer{} - - for { - r, _, err := buf.ReadRune() - if err != nil { - return 0, err - } - - if ('0' <= r && r <= '9') || r == '-' { - s.WriteRune(r) - } else { - buf.UnreadRune() - n, err := strconv.ParseInt(s.String(), 10, 32) - if err != nil { - return 0, err - } - return int32(n), nil - } - } -} - -func encodeTextArrayDimensions(buf []byte, dimensions []ArrayDimension) []byte { - var customDimensions bool - for _, dim := range dimensions { - if dim.LowerBound != 1 { - customDimensions = true - } - } - - if !customDimensions { - return buf - } - - for _, dim := range dimensions { - buf = append(buf, '[') - buf = append(buf, strconv.FormatInt(int64(dim.LowerBound), 10)...) - buf = append(buf, ':') - buf = append(buf, strconv.FormatInt(int64(dim.LowerBound+dim.Length-1), 10)...) - buf = append(buf, ']') - } - - return append(buf, '=') -} - -var quoteArrayReplacer = strings.NewReplacer(`\`, `\\`, `"`, `\"`) - -func quoteArrayElement(src string) string { - return `"` + quoteArrayReplacer.Replace(src) + `"` -} - -func isSpace(ch byte) bool { - // see array_isspace: - // https://github.com/postgres/postgres/blob/master/src/backend/utils/adt/arrayfuncs.c - return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\v' || ch == '\f' -} - -func quoteArrayElementIfNeeded(src string) string { - if src == "" || (len(src) == 4 && strings.EqualFold(src, "null")) || isSpace(src[0]) || isSpace(src[len(src)-1]) || strings.ContainsAny(src, `{},"\`) { - return quoteArrayElement(src) - } - return src -} - -// Array represents a PostgreSQL array for T. It implements the ArrayGetter and ArraySetter interfaces. It preserves -// PostgreSQL dimensions and custom lower bounds. Use FlatArray if these are not needed. -type Array[T any] struct { - Elements []T - Dims []ArrayDimension - Valid bool -} - -func (a Array[T]) Dimensions() []ArrayDimension { - return a.Dims -} - -func (a Array[T]) Index(i int) any { - return a.Elements[i] -} - -func (a Array[T]) IndexType() any { - var el T - return el -} - -func (a *Array[T]) SetDimensions(dimensions []ArrayDimension) error { - if dimensions == nil { - *a = Array[T]{} - return nil - } - - elementCount := cardinality(dimensions) - *a = Array[T]{ - Elements: make([]T, elementCount), - Dims: dimensions, - Valid: true, - } - - return nil -} - -func (a Array[T]) ScanIndex(i int) any { - return &a.Elements[i] -} - -func (a Array[T]) ScanIndexType() any { - return new(T) -} - -// FlatArray implements the ArrayGetter and ArraySetter interfaces for any slice of T. It ignores PostgreSQL dimensions -// and custom lower bounds. Use Array to preserve these. -type FlatArray[T any] []T - -func (a FlatArray[T]) Dimensions() []ArrayDimension { - if a == nil { - return nil - } - - return []ArrayDimension{{Length: int32(len(a)), LowerBound: 1}} -} - -func (a FlatArray[T]) Index(i int) any { - return a[i] -} - -func (a FlatArray[T]) IndexType() any { - var el T - return el -} - -func (a *FlatArray[T]) SetDimensions(dimensions []ArrayDimension) error { - if dimensions == nil { - *a = nil - return nil - } - - elementCount := cardinality(dimensions) - *a = make(FlatArray[T], elementCount) - return nil -} - -func (a FlatArray[T]) ScanIndex(i int) any { - return &a[i] -} - -func (a FlatArray[T]) ScanIndexType() any { - return new(T) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go deleted file mode 100644 index bf5f6989a..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go +++ /dev/null @@ -1,405 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "reflect" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// ArrayGetter is a type that can be converted into a PostgreSQL array. -type ArrayGetter interface { - // Dimensions returns the array dimensions. If array is nil then nil is returned. - Dimensions() []ArrayDimension - - // Index returns the element at i. - Index(i int) any - - // IndexType returns a non-nil scan target of the type Index will return. This is used by ArrayCodec.PlanEncode. - IndexType() any -} - -// ArraySetter is a type can be set from a PostgreSQL array. -type ArraySetter interface { - // SetDimensions prepares the value such that ScanIndex can be called for each element. This will remove any existing - // elements. dimensions may be nil to indicate a NULL array. If unable to exactly preserve dimensions SetDimensions - // may return an error or silently flatten the array dimensions. - SetDimensions(dimensions []ArrayDimension) error - - // ScanIndex returns a value usable as a scan target for i. SetDimensions must be called before ScanIndex. - ScanIndex(i int) any - - // ScanIndexType returns a non-nil scan target of the type ScanIndex will return. This is used by - // ArrayCodec.PlanScan. - ScanIndexType() any -} - -// ArrayCodec is a codec for any array type. -type ArrayCodec struct { - ElementType *Type -} - -func (c *ArrayCodec) FormatSupported(format int16) bool { - return c.ElementType.Codec.FormatSupported(format) -} - -func (c *ArrayCodec) PreferredFormat() int16 { - // The binary format should always be preferred for arrays if it is supported. Usually, this will happen automatically - // because most types that support binary prefer it. However, text, json, and jsonb support binary but prefer the text - // format. This is because it is simpler for jsonb and PostgreSQL can be significantly faster using the text format - // for text-like data types than binary. However, arrays appear to always be faster in binary. - // - // https://www.postgresql.org/message-id/CAMovtNoHFod2jMAKQjjxv209PCTJx5Kc66anwWvX0mEiaXwgmA%40mail.gmail.com - if c.ElementType.Codec.FormatSupported(BinaryFormatCode) { - return BinaryFormatCode - } - return TextFormatCode -} - -func (c *ArrayCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - arrayValuer, ok := value.(ArrayGetter) - if !ok { - return nil - } - - elementType := arrayValuer.IndexType() - - elementEncodePlan := m.PlanEncode(c.ElementType.OID, format, elementType) - if elementEncodePlan == nil { - if reflect.TypeOf(elementType) != nil { - return nil - } - } - - switch format { - case BinaryFormatCode: - return &encodePlanArrayCodecBinary{ac: c, m: m, oid: oid} - case TextFormatCode: - return &encodePlanArrayCodecText{ac: c, m: m, oid: oid} - } - - return nil -} - -type encodePlanArrayCodecText struct { - ac *ArrayCodec - m *Map - oid uint32 -} - -func (p *encodePlanArrayCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - array := value.(ArrayGetter) - - dimensions := array.Dimensions() - if dimensions == nil { - return nil, nil - } - - elementCount := cardinality(dimensions) - if elementCount == 0 { - return append(buf, '{', '}'), nil - } - - buf = encodeTextArrayDimensions(buf, dimensions) - - // dimElemCounts is the multiples of elements that each array lies on. For - // example, a single dimension array of length 4 would have a dimElemCounts of - // [4]. A multi-dimensional array of lengths [3,5,2] would have a - // dimElemCounts of [30,10,2]. This is used to simplify when to render a '{' - // or '}'. - dimElemCounts := make([]int, len(dimensions)) - dimElemCounts[len(dimensions)-1] = int(dimensions[len(dimensions)-1].Length) - for i := len(dimensions) - 2; i > -1; i-- { - dimElemCounts[i] = int(dimensions[i].Length) * dimElemCounts[i+1] - } - - var encodePlan EncodePlan - var lastElemType reflect.Type - inElemBuf := make([]byte, 0, 32) - for i := 0; i < elementCount; i++ { - if i > 0 { - buf = append(buf, ',') - } - - for _, dec := range dimElemCounts { - if i%dec == 0 { - buf = append(buf, '{') - } - } - - elem := array.Index(i) - var elemBuf []byte - if elem != nil { - elemType := reflect.TypeOf(elem) - if lastElemType != elemType { - lastElemType = elemType - encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, TextFormatCode, elem) - if encodePlan == nil { - return nil, fmt.Errorf("unable to encode %v", array.Index(i)) - } - } - elemBuf, err = encodePlan.Encode(elem, inElemBuf) - if err != nil { - return nil, err - } - } - - if elemBuf == nil { - buf = append(buf, `NULL`...) - } else { - buf = append(buf, quoteArrayElementIfNeeded(string(elemBuf))...) - } - - for _, dec := range dimElemCounts { - if (i+1)%dec == 0 { - buf = append(buf, '}') - } - } - } - - return buf, nil -} - -type encodePlanArrayCodecBinary struct { - ac *ArrayCodec - m *Map - oid uint32 -} - -func (p *encodePlanArrayCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - array := value.(ArrayGetter) - - dimensions := array.Dimensions() - if dimensions == nil { - return nil, nil - } - - arrayHeader := arrayHeader{ - Dimensions: dimensions, - ElementOID: p.ac.ElementType.OID, - } - - containsNullIndex := len(buf) + 4 - - buf = arrayHeader.EncodeBinary(buf) - - elementCount := cardinality(dimensions) - - var encodePlan EncodePlan - var lastElemType reflect.Type - for i := 0; i < elementCount; i++ { - sp := len(buf) - buf = pgio.AppendInt32(buf, -1) - - elem := array.Index(i) - var elemBuf []byte - if elem != nil { - elemType := reflect.TypeOf(elem) - if lastElemType != elemType { - lastElemType = elemType - encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, BinaryFormatCode, elem) - if encodePlan == nil { - return nil, fmt.Errorf("unable to encode %v", array.Index(i)) - } - } - elemBuf, err = encodePlan.Encode(elem, buf) - if err != nil { - return nil, err - } - } - - if elemBuf == nil { - pgio.SetInt32(buf[containsNullIndex:], 1) - } else { - buf = elemBuf - pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) - } - } - - return buf, nil -} - -func (c *ArrayCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - arrayScanner, ok := target.(ArraySetter) - if !ok { - return nil - } - - // target / arrayScanner might be a pointer to a nil. If it is create one so we can call ScanIndexType to plan the - // scan of the elements. - if isNil, _ := isNilDriverValuer(target); isNil { - arrayScanner = reflect.New(reflect.TypeOf(target).Elem()).Interface().(ArraySetter) - } - - elementType := arrayScanner.ScanIndexType() - - elementScanPlan := m.PlanScan(c.ElementType.OID, format, elementType) - if _, ok := elementScanPlan.(*scanPlanFail); ok { - return nil - } - - return &scanPlanArrayCodec{ - arrayCodec: c, - m: m, - oid: oid, - formatCode: format, - } -} - -func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array ArraySetter) error { - var arrayHeader arrayHeader - rp, err := arrayHeader.DecodeBinary(m, src) - if err != nil { - return err - } - - err = array.SetDimensions(arrayHeader.Dimensions) - if err != nil { - return err - } - - elementCount := cardinality(arrayHeader.Dimensions) - if elementCount == 0 { - return nil - } - - elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, array.ScanIndex(0)) - if elementScanPlan == nil { - elementScanPlan = m.PlanScan(c.ElementType.OID, BinaryFormatCode, array.ScanIndex(0)) - } - - for i := 0; i < elementCount; i++ { - elem := array.ScanIndex(i) - elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - var elemSrc []byte - if elemLen >= 0 { - elemSrc = src[rp : rp+elemLen] - rp += elemLen - } - err = elementScanPlan.Scan(elemSrc, elem) - if err != nil { - return fmt.Errorf("failed to scan array element %d: %w", i, err) - } - } - - return nil -} - -func (c *ArrayCodec) decodeText(m *Map, arrayOID uint32, src []byte, array ArraySetter) error { - uta, err := parseUntypedTextArray(string(src)) - if err != nil { - return err - } - - err = array.SetDimensions(uta.Dimensions) - if err != nil { - return err - } - - if len(uta.Elements) == 0 { - return nil - } - - elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, TextFormatCode, array.ScanIndex(0)) - if elementScanPlan == nil { - elementScanPlan = m.PlanScan(c.ElementType.OID, TextFormatCode, array.ScanIndex(0)) - } - - for i, s := range uta.Elements { - elem := array.ScanIndex(i) - var elemSrc []byte - if s != "NULL" || uta.Quoted[i] { - elemSrc = []byte(s) - } - - err = elementScanPlan.Scan(elemSrc, elem) - if err != nil { - return err - } - } - - return nil -} - -type scanPlanArrayCodec struct { - arrayCodec *ArrayCodec - m *Map - oid uint32 - formatCode int16 - elementScanPlan ScanPlan -} - -func (spac *scanPlanArrayCodec) Scan(src []byte, dst any) error { - c := spac.arrayCodec - m := spac.m - oid := spac.oid - formatCode := spac.formatCode - - array := dst.(ArraySetter) - - if src == nil { - return array.SetDimensions(nil) - } - - switch formatCode { - case BinaryFormatCode: - return c.decodeBinary(m, oid, src, array) - case TextFormatCode: - return c.decodeText(m, oid, src, array) - default: - return fmt.Errorf("unknown format code %d", formatCode) - } -} - -func (c *ArrayCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - switch format { - case TextFormatCode: - return string(src), nil - case BinaryFormatCode: - buf := make([]byte, len(src)) - copy(buf, src) - return buf, nil - default: - return nil, fmt.Errorf("unknown format code %d", format) - } -} - -func (c *ArrayCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var slice []any - err := m.PlanScan(oid, format, &slice).Scan(src, &slice) - return slice, err -} - -func isRagged(slice reflect.Value) bool { - if slice.Type().Elem().Kind() != reflect.Slice { - return false - } - - sliceLen := slice.Len() - innerLen := 0 - for i := 0; i < sliceLen; i++ { - if i == 0 { - innerLen = slice.Index(i).Len() - } else { - if slice.Index(i).Len() != innerLen { - return true - } - } - if isRagged(slice.Index(i)) { - return true - } - } - - return false -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go deleted file mode 100644 index e7a1d016d..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go +++ /dev/null @@ -1,210 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type BitsScanner interface { - ScanBits(v Bits) error -} - -type BitsValuer interface { - BitsValue() (Bits, error) -} - -// Bits represents the PostgreSQL bit and varbit types. -type Bits struct { - Bytes []byte - Len int32 // Number of bits - Valid bool -} - -func (b *Bits) ScanBits(v Bits) error { - *b = v - return nil -} - -func (b Bits) BitsValue() (Bits, error) { - return b, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Bits) Scan(src any) error { - if src == nil { - *dst = Bits{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToBitsScanner{}.Scan([]byte(src), dst) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src Bits) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - buf, err := BitsCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type BitsCodec struct{} - -func (BitsCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (BitsCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (BitsCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(BitsValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanBitsCodecBinary{} - case TextFormatCode: - return encodePlanBitsCodecText{} - } - - return nil -} - -type encodePlanBitsCodecBinary struct{} - -func (encodePlanBitsCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - bits, err := value.(BitsValuer).BitsValue() - if err != nil { - return nil, err - } - - if !bits.Valid { - return nil, nil - } - - buf = pgio.AppendInt32(buf, bits.Len) - return append(buf, bits.Bytes...), nil -} - -type encodePlanBitsCodecText struct{} - -func (encodePlanBitsCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - bits, err := value.(BitsValuer).BitsValue() - if err != nil { - return nil, err - } - - if !bits.Valid { - return nil, nil - } - - for i := int32(0); i < bits.Len; i++ { - byteIdx := i / 8 - bitMask := byte(128 >> byte(i%8)) - char := byte('0') - if bits.Bytes[byteIdx]&bitMask > 0 { - char = '1' - } - buf = append(buf, char) - } - - return buf, nil -} - -func (BitsCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case BitsScanner: - return scanPlanBinaryBitsToBitsScanner{} - } - case TextFormatCode: - switch target.(type) { - case BitsScanner: - return scanPlanTextAnyToBitsScanner{} - } - } - - return nil -} - -func (c BitsCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c BitsCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var box Bits - err := codecScan(c, m, oid, format, src, &box) - if err != nil { - return nil, err - } - return box, nil -} - -type scanPlanBinaryBitsToBitsScanner struct{} - -func (scanPlanBinaryBitsToBitsScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BitsScanner) - - if src == nil { - return scanner.ScanBits(Bits{}) - } - - if len(src) < 4 { - return fmt.Errorf("invalid length for bit/varbit: %v", len(src)) - } - - bitLen := int32(binary.BigEndian.Uint32(src)) - rp := 4 - buf := make([]byte, len(src[rp:])) - copy(buf, src[rp:]) - - return scanner.ScanBits(Bits{Bytes: buf, Len: bitLen, Valid: true}) -} - -type scanPlanTextAnyToBitsScanner struct{} - -func (scanPlanTextAnyToBitsScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BitsScanner) - - if src == nil { - return scanner.ScanBits(Bits{}) - } - - bitLen := len(src) - byteLen := bitLen / 8 - if bitLen%8 > 0 { - byteLen++ - } - buf := make([]byte, byteLen) - - for i, b := range src { - if b == '1' { - byteIdx := i / 8 - bitIdx := uint(i % 8) - buf[byteIdx] = buf[byteIdx] | (128 >> bitIdx) - } - } - - return scanner.ScanBits(Bits{Bytes: buf, Len: int32(bitLen), Valid: true}) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bool.go b/vendor/github.com/jackc/pgx/v5/pgtype/bool.go deleted file mode 100644 index 71caffa74..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bool.go +++ /dev/null @@ -1,343 +0,0 @@ -package pgtype - -import ( - "bytes" - "database/sql/driver" - "encoding/json" - "fmt" - "strconv" - "strings" -) - -type BoolScanner interface { - ScanBool(v Bool) error -} - -type BoolValuer interface { - BoolValue() (Bool, error) -} - -type Bool struct { - Bool bool - Valid bool -} - -func (b *Bool) ScanBool(v Bool) error { - *b = v - return nil -} - -func (b Bool) BoolValue() (Bool, error) { - return b, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Bool) Scan(src any) error { - if src == nil { - *dst = Bool{} - return nil - } - - switch src := src.(type) { - case bool: - *dst = Bool{Bool: src, Valid: true} - return nil - case string: - b, err := strconv.ParseBool(src) - if err != nil { - return err - } - *dst = Bool{Bool: b, Valid: true} - return nil - case []byte: - b, err := strconv.ParseBool(string(src)) - if err != nil { - return err - } - *dst = Bool{Bool: b, Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src Bool) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - return src.Bool, nil -} - -func (src Bool) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - - if src.Bool { - return []byte("true"), nil - } else { - return []byte("false"), nil - } -} - -func (dst *Bool) UnmarshalJSON(b []byte) error { - var v *bool - err := json.Unmarshal(b, &v) - if err != nil { - return err - } - - if v == nil { - *dst = Bool{} - } else { - *dst = Bool{Bool: *v, Valid: true} - } - - return nil -} - -type BoolCodec struct{} - -func (BoolCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (BoolCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (BoolCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case bool: - return encodePlanBoolCodecBinaryBool{} - case BoolValuer: - return encodePlanBoolCodecBinaryBoolValuer{} - } - case TextFormatCode: - switch value.(type) { - case bool: - return encodePlanBoolCodecTextBool{} - case BoolValuer: - return encodePlanBoolCodecTextBoolValuer{} - } - } - - return nil -} - -type encodePlanBoolCodecBinaryBool struct{} - -func (encodePlanBoolCodecBinaryBool) Encode(value any, buf []byte) (newBuf []byte, err error) { - v := value.(bool) - - if v { - buf = append(buf, 1) - } else { - buf = append(buf, 0) - } - - return buf, nil -} - -type encodePlanBoolCodecTextBoolValuer struct{} - -func (encodePlanBoolCodecTextBoolValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - b, err := value.(BoolValuer).BoolValue() - if err != nil { - return nil, err - } - - if !b.Valid { - return nil, nil - } - - if b.Bool { - buf = append(buf, 't') - } else { - buf = append(buf, 'f') - } - - return buf, nil -} - -type encodePlanBoolCodecBinaryBoolValuer struct{} - -func (encodePlanBoolCodecBinaryBoolValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - b, err := value.(BoolValuer).BoolValue() - if err != nil { - return nil, err - } - - if !b.Valid { - return nil, nil - } - - if b.Bool { - buf = append(buf, 1) - } else { - buf = append(buf, 0) - } - - return buf, nil -} - -type encodePlanBoolCodecTextBool struct{} - -func (encodePlanBoolCodecTextBool) Encode(value any, buf []byte) (newBuf []byte, err error) { - v := value.(bool) - - if v { - buf = append(buf, 't') - } else { - buf = append(buf, 'f') - } - - return buf, nil -} - -func (BoolCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *bool: - return scanPlanBinaryBoolToBool{} - case BoolScanner: - return scanPlanBinaryBoolToBoolScanner{} - } - case TextFormatCode: - switch target.(type) { - case *bool: - return scanPlanTextAnyToBool{} - case BoolScanner: - return scanPlanTextAnyToBoolScanner{} - } - } - - return nil -} - -func (c BoolCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return c.DecodeValue(m, oid, format, src) -} - -func (c BoolCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var b bool - err := codecScan(c, m, oid, format, src, &b) - if err != nil { - return nil, err - } - return b, nil -} - -type scanPlanBinaryBoolToBool struct{} - -func (scanPlanBinaryBoolToBool) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 1 { - return fmt.Errorf("invalid length for bool: %v", len(src)) - } - - p, ok := (dst).(*bool) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = src[0] == 1 - - return nil -} - -type scanPlanTextAnyToBool struct{} - -func (scanPlanTextAnyToBool) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) == 0 { - return fmt.Errorf("cannot scan empty string into %T", dst) - } - - p, ok := (dst).(*bool) - if !ok { - return ErrScanTargetTypeChanged - } - - v, err := planTextToBool(src) - if err != nil { - return err - } - - *p = v - - return nil -} - -type scanPlanBinaryBoolToBoolScanner struct{} - -func (scanPlanBinaryBoolToBoolScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(BoolScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanBool(Bool{}) - } - - if len(src) != 1 { - return fmt.Errorf("invalid length for bool: %v", len(src)) - } - - return s.ScanBool(Bool{Bool: src[0] == 1, Valid: true}) -} - -type scanPlanTextAnyToBoolScanner struct{} - -func (scanPlanTextAnyToBoolScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(BoolScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanBool(Bool{}) - } - - if len(src) == 0 { - return fmt.Errorf("cannot scan empty string into %T", dst) - } - - v, err := planTextToBool(src) - if err != nil { - return err - } - - return s.ScanBool(Bool{Bool: v, Valid: true}) -} - -// https://www.postgresql.org/docs/11/datatype-boolean.html -func planTextToBool(src []byte) (bool, error) { - s := string(bytes.ToLower(bytes.TrimSpace(src))) - - switch { - case strings.HasPrefix("true", s), strings.HasPrefix("yes", s), s == "on", s == "1": - return true, nil - case strings.HasPrefix("false", s), strings.HasPrefix("no", s), strings.HasPrefix("off", s), s == "0": - return false, nil - default: - return false, fmt.Errorf("unknown boolean string representation %q", src) - } -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/box.go b/vendor/github.com/jackc/pgx/v5/pgtype/box.go deleted file mode 100644 index 887d268bc..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/box.go +++ /dev/null @@ -1,238 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type BoxScanner interface { - ScanBox(v Box) error -} - -type BoxValuer interface { - BoxValue() (Box, error) -} - -type Box struct { - P [2]Vec2 - Valid bool -} - -func (b *Box) ScanBox(v Box) error { - *b = v - return nil -} - -func (b Box) BoxValue() (Box, error) { - return b, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Box) Scan(src any) error { - if src == nil { - *dst = Box{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToBoxScanner{}.Scan([]byte(src), dst) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src Box) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - buf, err := BoxCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type BoxCodec struct{} - -func (BoxCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (BoxCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (BoxCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(BoxValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanBoxCodecBinary{} - case TextFormatCode: - return encodePlanBoxCodecText{} - } - - return nil -} - -type encodePlanBoxCodecBinary struct{} - -func (encodePlanBoxCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - box, err := value.(BoxValuer).BoxValue() - if err != nil { - return nil, err - } - - if !box.Valid { - return nil, nil - } - - buf = pgio.AppendUint64(buf, math.Float64bits(box.P[0].X)) - buf = pgio.AppendUint64(buf, math.Float64bits(box.P[0].Y)) - buf = pgio.AppendUint64(buf, math.Float64bits(box.P[1].X)) - buf = pgio.AppendUint64(buf, math.Float64bits(box.P[1].Y)) - return buf, nil -} - -type encodePlanBoxCodecText struct{} - -func (encodePlanBoxCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - box, err := value.(BoxValuer).BoxValue() - if err != nil { - return nil, err - } - - if !box.Valid { - return nil, nil - } - - buf = append(buf, fmt.Sprintf(`(%s,%s),(%s,%s)`, - strconv.FormatFloat(box.P[0].X, 'f', -1, 64), - strconv.FormatFloat(box.P[0].Y, 'f', -1, 64), - strconv.FormatFloat(box.P[1].X, 'f', -1, 64), - strconv.FormatFloat(box.P[1].Y, 'f', -1, 64), - )...) - return buf, nil -} - -func (BoxCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case BoxScanner: - return scanPlanBinaryBoxToBoxScanner{} - } - case TextFormatCode: - switch target.(type) { - case BoxScanner: - return scanPlanTextAnyToBoxScanner{} - } - } - - return nil -} - -type scanPlanBinaryBoxToBoxScanner struct{} - -func (scanPlanBinaryBoxToBoxScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BoxScanner) - - if src == nil { - return scanner.ScanBox(Box{}) - } - - if len(src) != 32 { - return fmt.Errorf("invalid length for Box: %v", len(src)) - } - - x1 := binary.BigEndian.Uint64(src) - y1 := binary.BigEndian.Uint64(src[8:]) - x2 := binary.BigEndian.Uint64(src[16:]) - y2 := binary.BigEndian.Uint64(src[24:]) - - return scanner.ScanBox(Box{ - P: [2]Vec2{ - {math.Float64frombits(x1), math.Float64frombits(y1)}, - {math.Float64frombits(x2), math.Float64frombits(y2)}, - }, - Valid: true, - }) -} - -type scanPlanTextAnyToBoxScanner struct{} - -func (scanPlanTextAnyToBoxScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BoxScanner) - - if src == nil { - return scanner.ScanBox(Box{}) - } - - if len(src) < 11 { - return fmt.Errorf("invalid length for Box: %v", len(src)) - } - - str := string(src[1:]) - - var end int - end = strings.IndexByte(str, ',') - - x1, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+1:] - end = strings.IndexByte(str, ')') - - y1, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+3:] - end = strings.IndexByte(str, ',') - - x2, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+1 : len(str)-1] - - y2, err := strconv.ParseFloat(str, 64) - if err != nil { - return err - } - - return scanner.ScanBox(Box{P: [2]Vec2{{x1, y1}, {x2, y2}}, Valid: true}) -} - -func (c BoxCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c BoxCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var box Box - err := codecScan(c, m, oid, format, src, &box) - if err != nil { - return nil, err - } - return box, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go deleted file mode 100644 index b39d3fa10..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go +++ /dev/null @@ -1,952 +0,0 @@ -package pgtype - -import ( - "errors" - "fmt" - "math" - "math/big" - "net" - "net/netip" - "reflect" - "time" -) - -type int8Wrapper int8 - -func (w int8Wrapper) SkipUnderlyingTypePlan() {} - -func (w *int8Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *int8") - } - - if v.Int64 < math.MinInt8 { - return fmt.Errorf("%d is less than minimum value for int8", v.Int64) - } - if v.Int64 > math.MaxInt8 { - return fmt.Errorf("%d is greater than maximum value for int8", v.Int64) - } - *w = int8Wrapper(v.Int64) - - return nil -} - -func (w int8Wrapper) Int64Value() (Int8, error) { - return Int8{Int64: int64(w), Valid: true}, nil -} - -type int16Wrapper int16 - -func (w int16Wrapper) SkipUnderlyingTypePlan() {} - -func (w *int16Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *int16") - } - - if v.Int64 < math.MinInt16 { - return fmt.Errorf("%d is less than minimum value for int16", v.Int64) - } - if v.Int64 > math.MaxInt16 { - return fmt.Errorf("%d is greater than maximum value for int16", v.Int64) - } - *w = int16Wrapper(v.Int64) - - return nil -} - -func (w int16Wrapper) Int64Value() (Int8, error) { - return Int8{Int64: int64(w), Valid: true}, nil -} - -type int32Wrapper int32 - -func (w int32Wrapper) SkipUnderlyingTypePlan() {} - -func (w *int32Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *int32") - } - - if v.Int64 < math.MinInt32 { - return fmt.Errorf("%d is less than minimum value for int32", v.Int64) - } - if v.Int64 > math.MaxInt32 { - return fmt.Errorf("%d is greater than maximum value for int32", v.Int64) - } - *w = int32Wrapper(v.Int64) - - return nil -} - -func (w int32Wrapper) Int64Value() (Int8, error) { - return Int8{Int64: int64(w), Valid: true}, nil -} - -type int64Wrapper int64 - -func (w int64Wrapper) SkipUnderlyingTypePlan() {} - -func (w *int64Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *int64") - } - - *w = int64Wrapper(v.Int64) - - return nil -} - -func (w int64Wrapper) Int64Value() (Int8, error) { - return Int8{Int64: int64(w), Valid: true}, nil -} - -type intWrapper int - -func (w intWrapper) SkipUnderlyingTypePlan() {} - -func (w *intWrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *int") - } - - if v.Int64 < math.MinInt { - return fmt.Errorf("%d is less than minimum value for int", v.Int64) - } - if v.Int64 > math.MaxInt { - return fmt.Errorf("%d is greater than maximum value for int", v.Int64) - } - - *w = intWrapper(v.Int64) - - return nil -} - -func (w intWrapper) Int64Value() (Int8, error) { - return Int8{Int64: int64(w), Valid: true}, nil -} - -type uint8Wrapper uint8 - -func (w uint8Wrapper) SkipUnderlyingTypePlan() {} - -func (w *uint8Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *uint8") - } - - if v.Int64 < 0 { - return fmt.Errorf("%d is less than minimum value for uint8", v.Int64) - } - if v.Int64 > math.MaxUint8 { - return fmt.Errorf("%d is greater than maximum value for uint8", v.Int64) - } - *w = uint8Wrapper(v.Int64) - - return nil -} - -func (w uint8Wrapper) Int64Value() (Int8, error) { - return Int8{Int64: int64(w), Valid: true}, nil -} - -type uint16Wrapper uint16 - -func (w uint16Wrapper) SkipUnderlyingTypePlan() {} - -func (w *uint16Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *uint16") - } - - if v.Int64 < 0 { - return fmt.Errorf("%d is less than minimum value for uint16", v.Int64) - } - if v.Int64 > math.MaxUint16 { - return fmt.Errorf("%d is greater than maximum value for uint16", v.Int64) - } - *w = uint16Wrapper(v.Int64) - - return nil -} - -func (w uint16Wrapper) Int64Value() (Int8, error) { - return Int8{Int64: int64(w), Valid: true}, nil -} - -type uint32Wrapper uint32 - -func (w uint32Wrapper) SkipUnderlyingTypePlan() {} - -func (w *uint32Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *uint32") - } - - if v.Int64 < 0 { - return fmt.Errorf("%d is less than minimum value for uint32", v.Int64) - } - if v.Int64 > math.MaxUint32 { - return fmt.Errorf("%d is greater than maximum value for uint32", v.Int64) - } - *w = uint32Wrapper(v.Int64) - - return nil -} - -func (w uint32Wrapper) Int64Value() (Int8, error) { - return Int8{Int64: int64(w), Valid: true}, nil -} - -type uint64Wrapper uint64 - -func (w uint64Wrapper) SkipUnderlyingTypePlan() {} - -func (w *uint64Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *uint64") - } - - if v.Int64 < 0 { - return fmt.Errorf("%d is less than minimum value for uint64", v.Int64) - } - - *w = uint64Wrapper(v.Int64) - - return nil -} - -func (w uint64Wrapper) Int64Value() (Int8, error) { - if uint64(w) > uint64(math.MaxInt64) { - return Int8{}, fmt.Errorf("%d is greater than maximum value for int64", w) - } - - return Int8{Int64: int64(w), Valid: true}, nil -} - -func (w *uint64Wrapper) ScanNumeric(v Numeric) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *uint64") - } - - bi, err := v.toBigInt() - if err != nil { - return fmt.Errorf("cannot scan into *uint64: %w", err) - } - - if !bi.IsUint64() { - return fmt.Errorf("cannot scan %v into *uint64", bi.String()) - } - - *w = uint64Wrapper(bi.Uint64()) - - return nil -} - -func (w uint64Wrapper) NumericValue() (Numeric, error) { - return Numeric{Int: new(big.Int).SetUint64(uint64(w)), Valid: true}, nil -} - -type uintWrapper uint - -func (w uintWrapper) SkipUnderlyingTypePlan() {} - -func (w *uintWrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *uint64") - } - - if v.Int64 < 0 { - return fmt.Errorf("%d is less than minimum value for uint64", v.Int64) - } - - if uint64(v.Int64) > math.MaxUint { - return fmt.Errorf("%d is greater than maximum value for uint", v.Int64) - } - - *w = uintWrapper(v.Int64) - - return nil -} - -func (w uintWrapper) Int64Value() (Int8, error) { - if uint64(w) > uint64(math.MaxInt64) { - return Int8{}, fmt.Errorf("%d is greater than maximum value for int64", w) - } - - return Int8{Int64: int64(w), Valid: true}, nil -} - -func (w *uintWrapper) ScanNumeric(v Numeric) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *uint") - } - - bi, err := v.toBigInt() - if err != nil { - return fmt.Errorf("cannot scan into *uint: %w", err) - } - - if !bi.IsUint64() { - return fmt.Errorf("cannot scan %v into *uint", bi.String()) - } - - ui := bi.Uint64() - - if math.MaxUint < ui { - return fmt.Errorf("cannot scan %v into *uint", ui) - } - - *w = uintWrapper(ui) - - return nil -} - -func (w uintWrapper) NumericValue() (Numeric, error) { - return Numeric{Int: new(big.Int).SetUint64(uint64(w)), Valid: true}, nil -} - -type float32Wrapper float32 - -func (w float32Wrapper) SkipUnderlyingTypePlan() {} - -func (w *float32Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *float32") - } - - *w = float32Wrapper(v.Int64) - - return nil -} - -func (w float32Wrapper) Int64Value() (Int8, error) { - if w > math.MaxInt64 { - return Int8{}, fmt.Errorf("%f is greater than maximum value for int64", w) - } - - return Int8{Int64: int64(w), Valid: true}, nil -} - -func (w *float32Wrapper) ScanFloat64(v Float8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *float32") - } - - *w = float32Wrapper(v.Float64) - - return nil -} - -func (w float32Wrapper) Float64Value() (Float8, error) { - return Float8{Float64: float64(w), Valid: true}, nil -} - -type float64Wrapper float64 - -func (w float64Wrapper) SkipUnderlyingTypePlan() {} - -func (w *float64Wrapper) ScanInt64(v Int8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *float64") - } - - *w = float64Wrapper(v.Int64) - - return nil -} - -func (w float64Wrapper) Int64Value() (Int8, error) { - if w > math.MaxInt64 { - return Int8{}, fmt.Errorf("%f is greater than maximum value for int64", w) - } - - return Int8{Int64: int64(w), Valid: true}, nil -} - -func (w *float64Wrapper) ScanFloat64(v Float8) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *float64") - } - - *w = float64Wrapper(v.Float64) - - return nil -} - -func (w float64Wrapper) Float64Value() (Float8, error) { - return Float8{Float64: float64(w), Valid: true}, nil -} - -type stringWrapper string - -func (w stringWrapper) SkipUnderlyingTypePlan() {} - -func (w *stringWrapper) ScanText(v Text) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *string") - } - - *w = stringWrapper(v.String) - return nil -} - -func (w stringWrapper) TextValue() (Text, error) { - return Text{String: string(w), Valid: true}, nil -} - -type timeWrapper time.Time - -func (w *timeWrapper) ScanDate(v Date) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *time.Time") - } - - switch v.InfinityModifier { - case Finite: - *w = timeWrapper(v.Time) - return nil - case Infinity: - return fmt.Errorf("cannot scan Infinity into *time.Time") - case NegativeInfinity: - return fmt.Errorf("cannot scan -Infinity into *time.Time") - default: - return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) - } -} - -func (w timeWrapper) DateValue() (Date, error) { - return Date{Time: time.Time(w), Valid: true}, nil -} - -func (w *timeWrapper) ScanTimestamp(v Timestamp) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *time.Time") - } - - switch v.InfinityModifier { - case Finite: - *w = timeWrapper(v.Time) - return nil - case Infinity: - return fmt.Errorf("cannot scan Infinity into *time.Time") - case NegativeInfinity: - return fmt.Errorf("cannot scan -Infinity into *time.Time") - default: - return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) - } -} - -func (w timeWrapper) TimestampValue() (Timestamp, error) { - return Timestamp{Time: time.Time(w), Valid: true}, nil -} - -func (w *timeWrapper) ScanTimestamptz(v Timestamptz) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *time.Time") - } - - switch v.InfinityModifier { - case Finite: - *w = timeWrapper(v.Time) - return nil - case Infinity: - return fmt.Errorf("cannot scan Infinity into *time.Time") - case NegativeInfinity: - return fmt.Errorf("cannot scan -Infinity into *time.Time") - default: - return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) - } -} - -func (w timeWrapper) TimestamptzValue() (Timestamptz, error) { - return Timestamptz{Time: time.Time(w), Valid: true}, nil -} - -func (w *timeWrapper) ScanTime(v Time) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *time.Time") - } - - // 24:00:00 is max allowed time in PostgreSQL, but time.Time will normalize that to 00:00:00 the next day. - var maxRepresentableByTime int64 = 24*60*60*1000000 - 1 - if v.Microseconds > maxRepresentableByTime { - return fmt.Errorf("%d microseconds cannot be represented as time.Time", v.Microseconds) - } - - usec := v.Microseconds - hours := usec / microsecondsPerHour - usec -= hours * microsecondsPerHour - minutes := usec / microsecondsPerMinute - usec -= minutes * microsecondsPerMinute - seconds := usec / microsecondsPerSecond - usec -= seconds * microsecondsPerSecond - ns := usec * 1000 - *w = timeWrapper(time.Date(2000, 1, 1, int(hours), int(minutes), int(seconds), int(ns), time.UTC)) - return nil -} - -func (w timeWrapper) TimeValue() (Time, error) { - t := time.Time(w) - usec := int64(t.Hour())*microsecondsPerHour + - int64(t.Minute())*microsecondsPerMinute + - int64(t.Second())*microsecondsPerSecond + - int64(t.Nanosecond())/1000 - return Time{Microseconds: usec, Valid: true}, nil -} - -type durationWrapper time.Duration - -func (w durationWrapper) SkipUnderlyingTypePlan() {} - -func (w *durationWrapper) ScanInterval(v Interval) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *time.Interval") - } - - us := int64(v.Months)*microsecondsPerMonth + int64(v.Days)*microsecondsPerDay + v.Microseconds - *w = durationWrapper(time.Duration(us) * time.Microsecond) - return nil -} - -func (w durationWrapper) IntervalValue() (Interval, error) { - return Interval{Microseconds: int64(w) / 1000, Valid: true}, nil -} - -type netIPNetWrapper net.IPNet - -func (w *netIPNetWrapper) ScanNetipPrefix(v netip.Prefix) error { - if !v.IsValid() { - return fmt.Errorf("cannot scan NULL into *net.IPNet") - } - - *w = netIPNetWrapper{ - IP: v.Addr().AsSlice(), - Mask: net.CIDRMask(v.Bits(), v.Addr().BitLen()), - } - - return nil -} -func (w netIPNetWrapper) NetipPrefixValue() (netip.Prefix, error) { - ip, ok := netip.AddrFromSlice(w.IP) - if !ok { - return netip.Prefix{}, errors.New("invalid net.IPNet") - } - - ones, _ := w.Mask.Size() - - return netip.PrefixFrom(ip, ones), nil -} - -type netIPWrapper net.IP - -func (w netIPWrapper) SkipUnderlyingTypePlan() {} - -func (w *netIPWrapper) ScanNetipPrefix(v netip.Prefix) error { - if !v.IsValid() { - *w = nil - return nil - } - - if v.Addr().BitLen() != v.Bits() { - return fmt.Errorf("cannot scan %v to *net.IP", v) - } - - *w = netIPWrapper(v.Addr().AsSlice()) - return nil -} - -func (w netIPWrapper) NetipPrefixValue() (netip.Prefix, error) { - if w == nil { - return netip.Prefix{}, nil - } - - addr, ok := netip.AddrFromSlice([]byte(w)) - if !ok { - return netip.Prefix{}, errors.New("invalid net.IP") - } - - return netip.PrefixFrom(addr, addr.BitLen()), nil -} - -type netipPrefixWrapper netip.Prefix - -func (w *netipPrefixWrapper) ScanNetipPrefix(v netip.Prefix) error { - *w = netipPrefixWrapper(v) - return nil -} - -func (w netipPrefixWrapper) NetipPrefixValue() (netip.Prefix, error) { - return netip.Prefix(w), nil -} - -type netipAddrWrapper netip.Addr - -func (w *netipAddrWrapper) ScanNetipPrefix(v netip.Prefix) error { - if !v.IsValid() { - *w = netipAddrWrapper(netip.Addr{}) - return nil - } - - if v.Addr().BitLen() != v.Bits() { - return fmt.Errorf("cannot scan %v to netip.Addr", v) - } - - *w = netipAddrWrapper(v.Addr()) - - return nil -} - -func (w netipAddrWrapper) NetipPrefixValue() (netip.Prefix, error) { - addr := (netip.Addr)(w) - if !addr.IsValid() { - return netip.Prefix{}, nil - } - - return netip.PrefixFrom(addr, addr.BitLen()), nil -} - -type mapStringToPointerStringWrapper map[string]*string - -func (w *mapStringToPointerStringWrapper) ScanHstore(v Hstore) error { - *w = mapStringToPointerStringWrapper(v) - return nil -} - -func (w mapStringToPointerStringWrapper) HstoreValue() (Hstore, error) { - return Hstore(w), nil -} - -type mapStringToStringWrapper map[string]string - -func (w *mapStringToStringWrapper) ScanHstore(v Hstore) error { - *w = make(mapStringToStringWrapper, len(v)) - for k, v := range v { - if v == nil { - return fmt.Errorf("cannot scan NULL to string") - } - (*w)[k] = *v - } - return nil -} - -func (w mapStringToStringWrapper) HstoreValue() (Hstore, error) { - if w == nil { - return nil, nil - } - - hstore := make(Hstore, len(w)) - for k, v := range w { - s := v - hstore[k] = &s - } - return hstore, nil -} - -type fmtStringerWrapper struct { - s fmt.Stringer -} - -func (w fmtStringerWrapper) TextValue() (Text, error) { - return Text{String: w.s.String(), Valid: true}, nil -} - -type byte16Wrapper [16]byte - -func (w *byte16Wrapper) ScanUUID(v UUID) error { - if !v.Valid { - return fmt.Errorf("cannot scan NULL into *[16]byte") - } - *w = byte16Wrapper(v.Bytes) - return nil -} - -func (w byte16Wrapper) UUIDValue() (UUID, error) { - return UUID{Bytes: [16]byte(w), Valid: true}, nil -} - -type byteSliceWrapper []byte - -func (w byteSliceWrapper) SkipUnderlyingTypePlan() {} - -func (w *byteSliceWrapper) ScanText(v Text) error { - if !v.Valid { - *w = nil - return nil - } - - *w = byteSliceWrapper(v.String) - return nil -} - -func (w byteSliceWrapper) TextValue() (Text, error) { - if w == nil { - return Text{}, nil - } - - return Text{String: string(w), Valid: true}, nil -} - -func (w *byteSliceWrapper) ScanUUID(v UUID) error { - if !v.Valid { - *w = nil - return nil - } - *w = make(byteSliceWrapper, 16) - copy(*w, v.Bytes[:]) - return nil -} - -func (w byteSliceWrapper) UUIDValue() (UUID, error) { - if w == nil { - return UUID{}, nil - } - - uuid := UUID{Valid: true} - copy(uuid.Bytes[:], w) - return uuid, nil -} - -// structWrapper implements CompositeIndexGetter for a struct. -type structWrapper struct { - s any - exportedFields []reflect.Value -} - -func (w structWrapper) IsNull() bool { - return w.s == nil -} - -func (w structWrapper) Index(i int) any { - if i >= len(w.exportedFields) { - return fmt.Errorf("%#v only has %d public fields - %d is out of bounds", w.s, len(w.exportedFields), i) - } - - return w.exportedFields[i].Interface() -} - -// ptrStructWrapper implements CompositeIndexScanner for a pointer to a struct. -type ptrStructWrapper struct { - s any - exportedFields []reflect.Value -} - -func (w *ptrStructWrapper) ScanNull() error { - return fmt.Errorf("cannot scan NULL into %#v", w.s) -} - -func (w *ptrStructWrapper) ScanIndex(i int) any { - if i >= len(w.exportedFields) { - return fmt.Errorf("%#v only has %d public fields - %d is out of bounds", w.s, len(w.exportedFields), i) - } - - return w.exportedFields[i].Addr().Interface() -} - -type anySliceArrayReflect struct { - slice reflect.Value -} - -func (a anySliceArrayReflect) Dimensions() []ArrayDimension { - if a.slice.IsNil() { - return nil - } - - return []ArrayDimension{{Length: int32(a.slice.Len()), LowerBound: 1}} -} - -func (a anySliceArrayReflect) Index(i int) any { - return a.slice.Index(i).Interface() -} - -func (a anySliceArrayReflect) IndexType() any { - return reflect.New(a.slice.Type().Elem()).Elem().Interface() -} - -func (a *anySliceArrayReflect) SetDimensions(dimensions []ArrayDimension) error { - sliceType := a.slice.Type() - - if dimensions == nil { - a.slice.Set(reflect.Zero(sliceType)) - return nil - } - - elementCount := cardinality(dimensions) - slice := reflect.MakeSlice(sliceType, elementCount, elementCount) - a.slice.Set(slice) - return nil -} - -func (a *anySliceArrayReflect) ScanIndex(i int) any { - return a.slice.Index(i).Addr().Interface() -} - -func (a *anySliceArrayReflect) ScanIndexType() any { - return reflect.New(a.slice.Type().Elem()).Interface() -} - -type anyMultiDimSliceArray struct { - slice reflect.Value - dims []ArrayDimension -} - -func (a *anyMultiDimSliceArray) Dimensions() []ArrayDimension { - if a.slice.IsNil() { - return nil - } - - s := a.slice - for { - a.dims = append(a.dims, ArrayDimension{Length: int32(s.Len()), LowerBound: 1}) - if s.Len() > 0 { - s = s.Index(0) - } else { - break - } - if s.Type().Kind() == reflect.Slice { - } else { - break - } - } - - return a.dims -} - -func (a *anyMultiDimSliceArray) Index(i int) any { - if len(a.dims) == 1 { - return a.slice.Index(i).Interface() - } - - indexes := make([]int, len(a.dims)) - for j := len(a.dims) - 1; j >= 0; j-- { - dimLen := int(a.dims[j].Length) - indexes[j] = i % dimLen - i = i / dimLen - } - - v := a.slice - for _, si := range indexes { - v = v.Index(si) - } - - return v.Interface() -} - -func (a *anyMultiDimSliceArray) IndexType() any { - lowestSliceType := a.slice.Type() - for ; lowestSliceType.Elem().Kind() == reflect.Slice; lowestSliceType = lowestSliceType.Elem() { - } - return reflect.New(lowestSliceType.Elem()).Elem().Interface() -} - -func (a *anyMultiDimSliceArray) SetDimensions(dimensions []ArrayDimension) error { - sliceType := a.slice.Type() - - if dimensions == nil { - a.slice.Set(reflect.Zero(sliceType)) - return nil - } - - switch len(dimensions) { - case 0: - // Empty, but non-nil array - slice := reflect.MakeSlice(sliceType, 0, 0) - a.slice.Set(slice) - return nil - case 1: - elementCount := cardinality(dimensions) - slice := reflect.MakeSlice(sliceType, elementCount, elementCount) - a.slice.Set(slice) - return nil - default: - sliceDimensionCount := 1 - lowestSliceType := sliceType - for ; lowestSliceType.Elem().Kind() == reflect.Slice; lowestSliceType = lowestSliceType.Elem() { - sliceDimensionCount++ - } - - if sliceDimensionCount != len(dimensions) { - return fmt.Errorf("PostgreSQL array has %d dimensions but slice has %d dimensions", len(dimensions), sliceDimensionCount) - } - - elementCount := cardinality(dimensions) - flatSlice := reflect.MakeSlice(lowestSliceType, elementCount, elementCount) - - multiDimSlice := a.makeMultidimensionalSlice(sliceType, dimensions, flatSlice, 0) - a.slice.Set(multiDimSlice) - - // Now that a.slice is a multi-dimensional slice with the underlying data pointed at flatSlice change a.slice to - // flatSlice so ScanIndex only has to handle simple one dimensional slices. - a.slice = flatSlice - - return nil - } - -} - -func (a *anyMultiDimSliceArray) makeMultidimensionalSlice(sliceType reflect.Type, dimensions []ArrayDimension, flatSlice reflect.Value, flatSliceIdx int) reflect.Value { - if len(dimensions) == 1 { - endIdx := flatSliceIdx + int(dimensions[0].Length) - return flatSlice.Slice3(flatSliceIdx, endIdx, endIdx) - } - - sliceLen := int(dimensions[0].Length) - slice := reflect.MakeSlice(sliceType, sliceLen, sliceLen) - for i := 0; i < sliceLen; i++ { - subSlice := a.makeMultidimensionalSlice(sliceType.Elem(), dimensions[1:], flatSlice, flatSliceIdx+(i*int(dimensions[1].Length))) - slice.Index(i).Set(subSlice) - } - - return slice -} - -func (a *anyMultiDimSliceArray) ScanIndex(i int) any { - return a.slice.Index(i).Addr().Interface() -} - -func (a *anyMultiDimSliceArray) ScanIndexType() any { - lowestSliceType := a.slice.Type() - for ; lowestSliceType.Elem().Kind() == reflect.Slice; lowestSliceType = lowestSliceType.Elem() { - } - return reflect.New(lowestSliceType.Elem()).Interface() -} - -type anyArrayArrayReflect struct { - array reflect.Value -} - -func (a anyArrayArrayReflect) Dimensions() []ArrayDimension { - return []ArrayDimension{{Length: int32(a.array.Len()), LowerBound: 1}} -} - -func (a anyArrayArrayReflect) Index(i int) any { - return a.array.Index(i).Interface() -} - -func (a anyArrayArrayReflect) IndexType() any { - return reflect.New(a.array.Type().Elem()).Elem().Interface() -} - -func (a *anyArrayArrayReflect) SetDimensions(dimensions []ArrayDimension) error { - if dimensions == nil { - return fmt.Errorf("anyArrayArrayReflect: cannot scan NULL into %v", a.array.Type().String()) - } - - if len(dimensions) != 1 { - return fmt.Errorf("anyArrayArrayReflect: cannot scan multi-dimensional array into %v", a.array.Type().String()) - } - - if int(dimensions[0].Length) != a.array.Len() { - return fmt.Errorf("anyArrayArrayReflect: cannot scan array with length %v into %v", dimensions[0].Length, a.array.Type().String()) - } - - return nil -} - -func (a *anyArrayArrayReflect) ScanIndex(i int) any { - return a.array.Index(i).Addr().Interface() -} - -func (a *anyArrayArrayReflect) ScanIndexType() any { - return reflect.New(a.array.Type().Elem()).Interface() -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go b/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go deleted file mode 100644 index a247705e9..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go +++ /dev/null @@ -1,255 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/hex" - "fmt" -) - -type BytesScanner interface { - // ScanBytes receives a byte slice of driver memory that is only valid until the next database method call. - ScanBytes(v []byte) error -} - -type BytesValuer interface { - // BytesValue returns a byte slice of the byte data. The caller must not change the returned slice. - BytesValue() ([]byte, error) -} - -// DriverBytes is a byte slice that holds a reference to memory owned by the driver. It is only valid from the time it -// is scanned until Rows.Next or Rows.Close is called. It is never safe to use DriverBytes with QueryRow as Row.Scan -// internally calls Rows.Close before returning. -type DriverBytes []byte - -func (b *DriverBytes) ScanBytes(v []byte) error { - *b = v - return nil -} - -// PreallocBytes is a byte slice of preallocated memory that scanned bytes will be copied to. If it is too small a new -// slice will be allocated. -type PreallocBytes []byte - -func (b *PreallocBytes) ScanBytes(v []byte) error { - if v == nil { - *b = nil - return nil - } - - if len(v) <= len(*b) { - *b = (*b)[:len(v)] - } else { - *b = make(PreallocBytes, len(v)) - } - copy(*b, v) - return nil -} - -// UndecodedBytes can be used as a scan target to get the raw bytes from PostgreSQL without any decoding. -type UndecodedBytes []byte - -type scanPlanAnyToUndecodedBytes struct{} - -func (scanPlanAnyToUndecodedBytes) Scan(src []byte, dst any) error { - dstBuf := dst.(*UndecodedBytes) - if src == nil { - *dstBuf = nil - return nil - } - - *dstBuf = make([]byte, len(src)) - copy(*dstBuf, src) - return nil -} - -type ByteaCodec struct{} - -func (ByteaCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (ByteaCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (ByteaCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case []byte: - return encodePlanBytesCodecBinaryBytes{} - case BytesValuer: - return encodePlanBytesCodecBinaryBytesValuer{} - } - case TextFormatCode: - switch value.(type) { - case []byte: - return encodePlanBytesCodecTextBytes{} - case BytesValuer: - return encodePlanBytesCodecTextBytesValuer{} - } - } - - return nil -} - -type encodePlanBytesCodecBinaryBytes struct{} - -func (encodePlanBytesCodecBinaryBytes) Encode(value any, buf []byte) (newBuf []byte, err error) { - b := value.([]byte) - if b == nil { - return nil, nil - } - - return append(buf, b...), nil -} - -type encodePlanBytesCodecBinaryBytesValuer struct{} - -func (encodePlanBytesCodecBinaryBytesValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - b, err := value.(BytesValuer).BytesValue() - if err != nil { - return nil, err - } - if b == nil { - return nil, nil - } - - return append(buf, b...), nil -} - -type encodePlanBytesCodecTextBytes struct{} - -func (encodePlanBytesCodecTextBytes) Encode(value any, buf []byte) (newBuf []byte, err error) { - b := value.([]byte) - if b == nil { - return nil, nil - } - - buf = append(buf, `\x`...) - buf = append(buf, hex.EncodeToString(b)...) - return buf, nil -} - -type encodePlanBytesCodecTextBytesValuer struct{} - -func (encodePlanBytesCodecTextBytesValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - b, err := value.(BytesValuer).BytesValue() - if err != nil { - return nil, err - } - if b == nil { - return nil, nil - } - - buf = append(buf, `\x`...) - buf = append(buf, hex.EncodeToString(b)...) - return buf, nil -} - -func (ByteaCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *[]byte: - return scanPlanBinaryBytesToBytes{} - case BytesScanner: - return scanPlanBinaryBytesToBytesScanner{} - } - case TextFormatCode: - switch target.(type) { - case *[]byte: - return scanPlanTextByteaToBytes{} - case BytesScanner: - return scanPlanTextByteaToBytesScanner{} - } - } - - return nil -} - -type scanPlanBinaryBytesToBytes struct{} - -func (scanPlanBinaryBytesToBytes) Scan(src []byte, dst any) error { - dstBuf := dst.(*[]byte) - if src == nil { - *dstBuf = nil - return nil - } - - *dstBuf = make([]byte, len(src)) - copy(*dstBuf, src) - return nil -} - -type scanPlanBinaryBytesToBytesScanner struct{} - -func (scanPlanBinaryBytesToBytesScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BytesScanner) - return scanner.ScanBytes(src) -} - -type scanPlanTextByteaToBytes struct{} - -func (scanPlanTextByteaToBytes) Scan(src []byte, dst any) error { - dstBuf := dst.(*[]byte) - if src == nil { - *dstBuf = nil - return nil - } - - buf, err := decodeHexBytea(src) - if err != nil { - return err - } - *dstBuf = buf - - return nil -} - -type scanPlanTextByteaToBytesScanner struct{} - -func (scanPlanTextByteaToBytesScanner) Scan(src []byte, dst any) error { - scanner := (dst).(BytesScanner) - buf, err := decodeHexBytea(src) - if err != nil { - return err - } - return scanner.ScanBytes(buf) -} - -func decodeHexBytea(src []byte) ([]byte, error) { - if src == nil { - return nil, nil - } - - if len(src) < 2 || src[0] != '\\' || src[1] != 'x' { - return nil, fmt.Errorf("invalid hex format") - } - - buf := make([]byte, (len(src)-2)/2) - _, err := hex.Decode(buf, src[2:]) - if err != nil { - return nil, err - } - - return buf, nil -} - -func (c ByteaCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return c.DecodeValue(m, oid, format, src) -} - -func (c ByteaCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var buf []byte - err := codecScan(c, m, oid, format, src, &buf) - if err != nil { - return nil, err - } - return buf, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/circle.go b/vendor/github.com/jackc/pgx/v5/pgtype/circle.go deleted file mode 100644 index e8f118cc9..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/circle.go +++ /dev/null @@ -1,222 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type CircleScanner interface { - ScanCircle(v Circle) error -} - -type CircleValuer interface { - CircleValue() (Circle, error) -} - -type Circle struct { - P Vec2 - R float64 - Valid bool -} - -func (c *Circle) ScanCircle(v Circle) error { - *c = v - return nil -} - -func (c Circle) CircleValue() (Circle, error) { - return c, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Circle) Scan(src any) error { - if src == nil { - *dst = Circle{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToCircleScanner{}.Scan([]byte(src), dst) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src Circle) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - buf, err := CircleCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type CircleCodec struct{} - -func (CircleCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (CircleCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (CircleCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(CircleValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanCircleCodecBinary{} - case TextFormatCode: - return encodePlanCircleCodecText{} - } - - return nil -} - -type encodePlanCircleCodecBinary struct{} - -func (encodePlanCircleCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - circle, err := value.(CircleValuer).CircleValue() - if err != nil { - return nil, err - } - - if !circle.Valid { - return nil, nil - } - - buf = pgio.AppendUint64(buf, math.Float64bits(circle.P.X)) - buf = pgio.AppendUint64(buf, math.Float64bits(circle.P.Y)) - buf = pgio.AppendUint64(buf, math.Float64bits(circle.R)) - return buf, nil -} - -type encodePlanCircleCodecText struct{} - -func (encodePlanCircleCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - circle, err := value.(CircleValuer).CircleValue() - if err != nil { - return nil, err - } - - if !circle.Valid { - return nil, nil - } - - buf = append(buf, fmt.Sprintf(`<(%s,%s),%s>`, - strconv.FormatFloat(circle.P.X, 'f', -1, 64), - strconv.FormatFloat(circle.P.Y, 'f', -1, 64), - strconv.FormatFloat(circle.R, 'f', -1, 64), - )...) - return buf, nil -} - -func (CircleCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case BinaryFormatCode: - switch target.(type) { - case CircleScanner: - return scanPlanBinaryCircleToCircleScanner{} - } - case TextFormatCode: - switch target.(type) { - case CircleScanner: - return scanPlanTextAnyToCircleScanner{} - } - } - - return nil -} - -func (c CircleCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c CircleCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var circle Circle - err := codecScan(c, m, oid, format, src, &circle) - if err != nil { - return nil, err - } - return circle, nil -} - -type scanPlanBinaryCircleToCircleScanner struct{} - -func (scanPlanBinaryCircleToCircleScanner) Scan(src []byte, dst any) error { - scanner := (dst).(CircleScanner) - - if src == nil { - return scanner.ScanCircle(Circle{}) - } - - if len(src) != 24 { - return fmt.Errorf("invalid length for Circle: %v", len(src)) - } - - x := binary.BigEndian.Uint64(src) - y := binary.BigEndian.Uint64(src[8:]) - r := binary.BigEndian.Uint64(src[16:]) - - return scanner.ScanCircle(Circle{ - P: Vec2{math.Float64frombits(x), math.Float64frombits(y)}, - R: math.Float64frombits(r), - Valid: true, - }) -} - -type scanPlanTextAnyToCircleScanner struct{} - -func (scanPlanTextAnyToCircleScanner) Scan(src []byte, dst any) error { - scanner := (dst).(CircleScanner) - - if src == nil { - return scanner.ScanCircle(Circle{}) - } - - if len(src) < 9 { - return fmt.Errorf("invalid length for Circle: %v", len(src)) - } - - str := string(src[2:]) - end := strings.IndexByte(str, ',') - x, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+1:] - end = strings.IndexByte(str, ')') - - y, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+2 : len(str)-1] - - r, err := strconv.ParseFloat(str, 64) - if err != nil { - return err - } - - return scanner.ScanCircle(Circle{P: Vec2{x, y}, R: r, Valid: true}) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/composite.go b/vendor/github.com/jackc/pgx/v5/pgtype/composite.go deleted file mode 100644 index fb372325b..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/composite.go +++ /dev/null @@ -1,602 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// CompositeIndexGetter is a type accessed by index that can be converted into a PostgreSQL composite. -type CompositeIndexGetter interface { - // IsNull returns true if the value is SQL NULL. - IsNull() bool - - // Index returns the element at i. - Index(i int) any -} - -// CompositeIndexScanner is a type accessed by index that can be scanned from a PostgreSQL composite. -type CompositeIndexScanner interface { - // ScanNull sets the value to SQL NULL. - ScanNull() error - - // ScanIndex returns a value usable as a scan target for i. - ScanIndex(i int) any -} - -type CompositeCodecField struct { - Name string - Type *Type -} - -type CompositeCodec struct { - Fields []CompositeCodecField -} - -func (c *CompositeCodec) FormatSupported(format int16) bool { - for _, f := range c.Fields { - if !f.Type.Codec.FormatSupported(format) { - return false - } - } - - return true -} - -func (c *CompositeCodec) PreferredFormat() int16 { - if c.FormatSupported(BinaryFormatCode) { - return BinaryFormatCode - } - return TextFormatCode -} - -func (c *CompositeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(CompositeIndexGetter); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return &encodePlanCompositeCodecCompositeIndexGetterToBinary{cc: c, m: m} - case TextFormatCode: - return &encodePlanCompositeCodecCompositeIndexGetterToText{cc: c, m: m} - } - - return nil -} - -type encodePlanCompositeCodecCompositeIndexGetterToBinary struct { - cc *CompositeCodec - m *Map -} - -func (plan *encodePlanCompositeCodecCompositeIndexGetterToBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - getter := value.(CompositeIndexGetter) - - if getter.IsNull() { - return nil, nil - } - - builder := NewCompositeBinaryBuilder(plan.m, buf) - for i, field := range plan.cc.Fields { - builder.AppendValue(field.Type.OID, getter.Index(i)) - } - - return builder.Finish() -} - -type encodePlanCompositeCodecCompositeIndexGetterToText struct { - cc *CompositeCodec - m *Map -} - -func (plan *encodePlanCompositeCodecCompositeIndexGetterToText) Encode(value any, buf []byte) (newBuf []byte, err error) { - getter := value.(CompositeIndexGetter) - - if getter.IsNull() { - return nil, nil - } - - b := NewCompositeTextBuilder(plan.m, buf) - for i, field := range plan.cc.Fields { - b.AppendValue(field.Type.OID, getter.Index(i)) - } - - return b.Finish() -} - -func (c *CompositeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case BinaryFormatCode: - switch target.(type) { - case CompositeIndexScanner: - return &scanPlanBinaryCompositeToCompositeIndexScanner{cc: c, m: m} - } - case TextFormatCode: - switch target.(type) { - case CompositeIndexScanner: - return &scanPlanTextCompositeToCompositeIndexScanner{cc: c, m: m} - } - } - - return nil -} - -type scanPlanBinaryCompositeToCompositeIndexScanner struct { - cc *CompositeCodec - m *Map -} - -func (plan *scanPlanBinaryCompositeToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) - - if src == nil { - return targetScanner.ScanNull() - } - - scanner := NewCompositeBinaryScanner(plan.m, src) - for i, field := range plan.cc.Fields { - if scanner.Next() { - fieldTarget := targetScanner.ScanIndex(i) - if fieldTarget != nil { - fieldPlan := plan.m.PlanScan(field.Type.OID, BinaryFormatCode, fieldTarget) - if fieldPlan == nil { - return fmt.Errorf("unable to encode %v into OID %d in binary format", field, field.Type.OID) - } - - err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) - if err != nil { - return err - } - } - } else { - return errors.New("read past end of composite") - } - } - - if err := scanner.Err(); err != nil { - return err - } - - return nil -} - -type scanPlanTextCompositeToCompositeIndexScanner struct { - cc *CompositeCodec - m *Map -} - -func (plan *scanPlanTextCompositeToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) - - if src == nil { - return targetScanner.ScanNull() - } - - scanner := NewCompositeTextScanner(plan.m, src) - for i, field := range plan.cc.Fields { - if scanner.Next() { - fieldTarget := targetScanner.ScanIndex(i) - if fieldTarget != nil { - fieldPlan := plan.m.PlanScan(field.Type.OID, TextFormatCode, fieldTarget) - if fieldPlan == nil { - return fmt.Errorf("unable to encode %v into OID %d in text format", field, field.Type.OID) - } - - err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) - if err != nil { - return err - } - } - } else { - return errors.New("read past end of composite") - } - } - - if err := scanner.Err(); err != nil { - return err - } - - return nil -} - -func (c *CompositeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - switch format { - case TextFormatCode: - return string(src), nil - case BinaryFormatCode: - buf := make([]byte, len(src)) - copy(buf, src) - return buf, nil - default: - return nil, fmt.Errorf("unknown format code %d", format) - } -} - -func (c *CompositeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - switch format { - case TextFormatCode: - scanner := NewCompositeTextScanner(m, src) - values := make(map[string]any, len(c.Fields)) - for i := 0; scanner.Next() && i < len(c.Fields); i++ { - var v any - fieldPlan := m.PlanScan(c.Fields[i].Type.OID, TextFormatCode, &v) - if fieldPlan == nil { - return nil, fmt.Errorf("unable to scan OID %d in text format into %v", c.Fields[i].Type.OID, v) - } - - err := fieldPlan.Scan(scanner.Bytes(), &v) - if err != nil { - return nil, err - } - - values[c.Fields[i].Name] = v - } - - if err := scanner.Err(); err != nil { - return nil, err - } - - return values, nil - case BinaryFormatCode: - scanner := NewCompositeBinaryScanner(m, src) - values := make(map[string]any, len(c.Fields)) - for i := 0; scanner.Next() && i < len(c.Fields); i++ { - var v any - fieldPlan := m.PlanScan(scanner.OID(), BinaryFormatCode, &v) - if fieldPlan == nil { - return nil, fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), v) - } - - err := fieldPlan.Scan(scanner.Bytes(), &v) - if err != nil { - return nil, err - } - - values[c.Fields[i].Name] = v - } - - if err := scanner.Err(); err != nil { - return nil, err - } - - return values, nil - default: - return nil, fmt.Errorf("unknown format code %d", format) - } - -} - -type CompositeBinaryScanner struct { - m *Map - rp int - src []byte - - fieldCount int32 - fieldBytes []byte - fieldOID uint32 - err error -} - -// NewCompositeBinaryScanner a scanner over a binary encoded composite balue. -func NewCompositeBinaryScanner(m *Map, src []byte) *CompositeBinaryScanner { - rp := 0 - if len(src[rp:]) < 4 { - return &CompositeBinaryScanner{err: fmt.Errorf("Record incomplete %v", src)} - } - - fieldCount := int32(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - return &CompositeBinaryScanner{ - m: m, - rp: rp, - src: src, - fieldCount: fieldCount, - } -} - -// Next advances the scanner to the next field. It returns false after the last field is read or an error occurs. After -// Next returns false, the Err method can be called to check if any errors occurred. -func (cfs *CompositeBinaryScanner) Next() bool { - if cfs.err != nil { - return false - } - - if cfs.rp == len(cfs.src) { - return false - } - - if len(cfs.src[cfs.rp:]) < 8 { - cfs.err = fmt.Errorf("Record incomplete %v", cfs.src) - return false - } - cfs.fieldOID = binary.BigEndian.Uint32(cfs.src[cfs.rp:]) - cfs.rp += 4 - - fieldLen := int(int32(binary.BigEndian.Uint32(cfs.src[cfs.rp:]))) - cfs.rp += 4 - - if fieldLen >= 0 { - if len(cfs.src[cfs.rp:]) < fieldLen { - cfs.err = fmt.Errorf("Record incomplete rp=%d src=%v", cfs.rp, cfs.src) - return false - } - cfs.fieldBytes = cfs.src[cfs.rp : cfs.rp+fieldLen] - cfs.rp += fieldLen - } else { - cfs.fieldBytes = nil - } - - return true -} - -func (cfs *CompositeBinaryScanner) FieldCount() int { - return int(cfs.fieldCount) -} - -// Bytes returns the bytes of the field most recently read by Scan(). -func (cfs *CompositeBinaryScanner) Bytes() []byte { - return cfs.fieldBytes -} - -// OID returns the OID of the field most recently read by Scan(). -func (cfs *CompositeBinaryScanner) OID() uint32 { - return cfs.fieldOID -} - -// Err returns any error encountered by the scanner. -func (cfs *CompositeBinaryScanner) Err() error { - return cfs.err -} - -type CompositeTextScanner struct { - m *Map - rp int - src []byte - - fieldBytes []byte - err error -} - -// NewCompositeTextScanner a scanner over a text encoded composite value. -func NewCompositeTextScanner(m *Map, src []byte) *CompositeTextScanner { - if len(src) < 2 { - return &CompositeTextScanner{err: fmt.Errorf("Record incomplete %v", src)} - } - - if src[0] != '(' { - return &CompositeTextScanner{err: fmt.Errorf("composite text format must start with '('")} - } - - if src[len(src)-1] != ')' { - return &CompositeTextScanner{err: fmt.Errorf("composite text format must end with ')'")} - } - - return &CompositeTextScanner{ - m: m, - rp: 1, - src: src, - } -} - -// Next advances the scanner to the next field. It returns false after the last field is read or an error occurs. After -// Next returns false, the Err method can be called to check if any errors occurred. -func (cfs *CompositeTextScanner) Next() bool { - if cfs.err != nil { - return false - } - - if cfs.rp == len(cfs.src) { - return false - } - - switch cfs.src[cfs.rp] { - case ',', ')': // null - cfs.rp++ - cfs.fieldBytes = nil - return true - case '"': // quoted value - cfs.rp++ - cfs.fieldBytes = make([]byte, 0, 16) - for { - ch := cfs.src[cfs.rp] - - if ch == '"' { - cfs.rp++ - if cfs.src[cfs.rp] == '"' { - cfs.fieldBytes = append(cfs.fieldBytes, '"') - cfs.rp++ - } else { - break - } - } else if ch == '\\' { - cfs.rp++ - cfs.fieldBytes = append(cfs.fieldBytes, cfs.src[cfs.rp]) - cfs.rp++ - } else { - cfs.fieldBytes = append(cfs.fieldBytes, ch) - cfs.rp++ - } - } - cfs.rp++ - return true - default: // unquoted value - start := cfs.rp - for { - ch := cfs.src[cfs.rp] - if ch == ',' || ch == ')' { - break - } - cfs.rp++ - } - cfs.fieldBytes = cfs.src[start:cfs.rp] - cfs.rp++ - return true - } -} - -// Bytes returns the bytes of the field most recently read by Scan(). -func (cfs *CompositeTextScanner) Bytes() []byte { - return cfs.fieldBytes -} - -// Err returns any error encountered by the scanner. -func (cfs *CompositeTextScanner) Err() error { - return cfs.err -} - -type CompositeBinaryBuilder struct { - m *Map - buf []byte - startIdx int - fieldCount uint32 - err error -} - -func NewCompositeBinaryBuilder(m *Map, buf []byte) *CompositeBinaryBuilder { - startIdx := len(buf) - buf = append(buf, 0, 0, 0, 0) // allocate room for number of fields - return &CompositeBinaryBuilder{m: m, buf: buf, startIdx: startIdx} -} - -func (b *CompositeBinaryBuilder) AppendValue(oid uint32, field any) { - if b.err != nil { - return - } - - if field == nil { - b.buf = pgio.AppendUint32(b.buf, oid) - b.buf = pgio.AppendInt32(b.buf, -1) - b.fieldCount++ - return - } - - plan := b.m.PlanEncode(oid, BinaryFormatCode, field) - if plan == nil { - b.err = fmt.Errorf("unable to encode %v into OID %d in binary format", field, oid) - return - } - - b.buf = pgio.AppendUint32(b.buf, oid) - lengthPos := len(b.buf) - b.buf = pgio.AppendInt32(b.buf, -1) - fieldBuf, err := plan.Encode(field, b.buf) - if err != nil { - b.err = err - return - } - if fieldBuf != nil { - binary.BigEndian.PutUint32(fieldBuf[lengthPos:], uint32(len(fieldBuf)-len(b.buf))) - b.buf = fieldBuf - } - - b.fieldCount++ -} - -func (b *CompositeBinaryBuilder) Finish() ([]byte, error) { - if b.err != nil { - return nil, b.err - } - - binary.BigEndian.PutUint32(b.buf[b.startIdx:], b.fieldCount) - return b.buf, nil -} - -type CompositeTextBuilder struct { - m *Map - buf []byte - startIdx int - fieldCount uint32 - err error - fieldBuf [32]byte -} - -func NewCompositeTextBuilder(m *Map, buf []byte) *CompositeTextBuilder { - buf = append(buf, '(') // allocate room for number of fields - return &CompositeTextBuilder{m: m, buf: buf} -} - -func (b *CompositeTextBuilder) AppendValue(oid uint32, field any) { - if b.err != nil { - return - } - - if field == nil { - b.buf = append(b.buf, ',') - return - } - - plan := b.m.PlanEncode(oid, TextFormatCode, field) - if plan == nil { - b.err = fmt.Errorf("unable to encode %v into OID %d in text format", field, oid) - return - } - - fieldBuf, err := plan.Encode(field, b.fieldBuf[0:0]) - if err != nil { - b.err = err - return - } - if fieldBuf != nil { - b.buf = append(b.buf, quoteCompositeFieldIfNeeded(string(fieldBuf))...) - } - - b.buf = append(b.buf, ',') -} - -func (b *CompositeTextBuilder) Finish() ([]byte, error) { - if b.err != nil { - return nil, b.err - } - - b.buf[len(b.buf)-1] = ')' - return b.buf, nil -} - -var quoteCompositeReplacer = strings.NewReplacer(`\`, `\\`, `"`, `\"`) - -func quoteCompositeField(src string) string { - return `"` + quoteCompositeReplacer.Replace(src) + `"` -} - -func quoteCompositeFieldIfNeeded(src string) string { - if src == "" || src[0] == ' ' || src[len(src)-1] == ' ' || strings.ContainsAny(src, `(),"\`) { - return quoteCompositeField(src) - } - return src -} - -// CompositeFields represents the values of a composite value. It can be used as an encoding source or as a scan target. -// It cannot scan a NULL, but the composite fields can be NULL. -type CompositeFields []any - -func (cf CompositeFields) SkipUnderlyingTypePlan() {} - -func (cf CompositeFields) IsNull() bool { - return cf == nil -} - -func (cf CompositeFields) Index(i int) any { - return cf[i] -} - -func (cf CompositeFields) ScanNull() error { - return fmt.Errorf("cannot scan NULL into CompositeFields") -} - -func (cf CompositeFields) ScanIndex(i int) any { - return cf[i] -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/convert.go b/vendor/github.com/jackc/pgx/v5/pgtype/convert.go deleted file mode 100644 index 8a9cee9c3..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/convert.go +++ /dev/null @@ -1,108 +0,0 @@ -package pgtype - -import ( - "reflect" -) - -func NullAssignTo(dst any) error { - dstPtr := reflect.ValueOf(dst) - - // AssignTo dst must always be a pointer - if dstPtr.Kind() != reflect.Ptr { - return &nullAssignmentError{dst: dst} - } - - dstVal := dstPtr.Elem() - - switch dstVal.Kind() { - case reflect.Ptr, reflect.Slice, reflect.Map: - dstVal.Set(reflect.Zero(dstVal.Type())) - return nil - } - - return &nullAssignmentError{dst: dst} -} - -var kindTypes map[reflect.Kind]reflect.Type - -func toInterface(dst reflect.Value, t reflect.Type) (any, bool) { - nextDst := dst.Convert(t) - return nextDst.Interface(), dst.Type() != nextDst.Type() -} - -// GetAssignToDstType attempts to convert dst to something AssignTo can assign -// to. If dst is a pointer to pointer it allocates a value and returns the -// dereferences pointer. If dst is a named type such as *Foo where Foo is type -// Foo int16, it converts dst to *int16. -// -// GetAssignToDstType returns the converted dst and a bool representing if any -// change was made. -func GetAssignToDstType(dst any) (any, bool) { - dstPtr := reflect.ValueOf(dst) - - // AssignTo dst must always be a pointer - if dstPtr.Kind() != reflect.Ptr { - return nil, false - } - - dstVal := dstPtr.Elem() - - // if dst is a pointer to pointer, allocate space try again with the dereferenced pointer - if dstVal.Kind() == reflect.Ptr { - dstVal.Set(reflect.New(dstVal.Type().Elem())) - return dstVal.Interface(), true - } - - // if dst is pointer to a base type that has been renamed - if baseValType, ok := kindTypes[dstVal.Kind()]; ok { - return toInterface(dstPtr, reflect.PtrTo(baseValType)) - } - - if dstVal.Kind() == reflect.Slice { - if baseElemType, ok := kindTypes[dstVal.Type().Elem().Kind()]; ok { - return toInterface(dstPtr, reflect.PtrTo(reflect.SliceOf(baseElemType))) - } - } - - if dstVal.Kind() == reflect.Array { - if baseElemType, ok := kindTypes[dstVal.Type().Elem().Kind()]; ok { - return toInterface(dstPtr, reflect.PtrTo(reflect.ArrayOf(dstVal.Len(), baseElemType))) - } - } - - if dstVal.Kind() == reflect.Struct { - if dstVal.Type().NumField() == 1 && dstVal.Type().Field(0).Anonymous { - dstPtr = dstVal.Field(0).Addr() - nested := dstVal.Type().Field(0).Type - if nested.Kind() == reflect.Array { - if baseElemType, ok := kindTypes[nested.Elem().Kind()]; ok { - return toInterface(dstPtr, reflect.PtrTo(reflect.ArrayOf(nested.Len(), baseElemType))) - } - } - if _, ok := kindTypes[nested.Kind()]; ok && dstPtr.CanInterface() { - return dstPtr.Interface(), true - } - } - } - - return nil, false -} - -func init() { - kindTypes = map[reflect.Kind]reflect.Type{ - reflect.Bool: reflect.TypeOf(false), - reflect.Float32: reflect.TypeOf(float32(0)), - reflect.Float64: reflect.TypeOf(float64(0)), - reflect.Int: reflect.TypeOf(int(0)), - reflect.Int8: reflect.TypeOf(int8(0)), - reflect.Int16: reflect.TypeOf(int16(0)), - reflect.Int32: reflect.TypeOf(int32(0)), - reflect.Int64: reflect.TypeOf(int64(0)), - reflect.Uint: reflect.TypeOf(uint(0)), - reflect.Uint8: reflect.TypeOf(uint8(0)), - reflect.Uint16: reflect.TypeOf(uint16(0)), - reflect.Uint32: reflect.TypeOf(uint32(0)), - reflect.Uint64: reflect.TypeOf(uint64(0)), - reflect.String: reflect.TypeOf(""), - } -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/date.go b/vendor/github.com/jackc/pgx/v5/pgtype/date.go deleted file mode 100644 index 784b16deb..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/date.go +++ /dev/null @@ -1,351 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "encoding/json" - "fmt" - "regexp" - "strconv" - "time" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type DateScanner interface { - ScanDate(v Date) error -} - -type DateValuer interface { - DateValue() (Date, error) -} - -type Date struct { - Time time.Time - InfinityModifier InfinityModifier - Valid bool -} - -func (d *Date) ScanDate(v Date) error { - *d = v - return nil -} - -func (d Date) DateValue() (Date, error) { - return d, nil -} - -const ( - negativeInfinityDayOffset = -2147483648 - infinityDayOffset = 2147483647 -) - -// Scan implements the database/sql Scanner interface. -func (dst *Date) Scan(src any) error { - if src == nil { - *dst = Date{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToDateScanner{}.Scan([]byte(src), dst) - case time.Time: - *dst = Date{Time: src, Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src Date) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - if src.InfinityModifier != Finite { - return src.InfinityModifier.String(), nil - } - return src.Time, nil -} - -func (src Date) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - - var s string - - switch src.InfinityModifier { - case Finite: - s = src.Time.Format("2006-01-02") - case Infinity: - s = "infinity" - case NegativeInfinity: - s = "-infinity" - } - - return json.Marshal(s) -} - -func (dst *Date) UnmarshalJSON(b []byte) error { - var s *string - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - - if s == nil { - *dst = Date{} - return nil - } - - switch *s { - case "infinity": - *dst = Date{Valid: true, InfinityModifier: Infinity} - case "-infinity": - *dst = Date{Valid: true, InfinityModifier: -Infinity} - default: - t, err := time.ParseInLocation("2006-01-02", *s, time.UTC) - if err != nil { - return err - } - - *dst = Date{Time: t, Valid: true} - } - - return nil -} - -type DateCodec struct{} - -func (DateCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (DateCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (DateCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(DateValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanDateCodecBinary{} - case TextFormatCode: - return encodePlanDateCodecText{} - } - - return nil -} - -type encodePlanDateCodecBinary struct{} - -func (encodePlanDateCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - date, err := value.(DateValuer).DateValue() - if err != nil { - return nil, err - } - - if !date.Valid { - return nil, nil - } - - var daysSinceDateEpoch int32 - switch date.InfinityModifier { - case Finite: - tUnix := time.Date(date.Time.Year(), date.Time.Month(), date.Time.Day(), 0, 0, 0, 0, time.UTC).Unix() - dateEpoch := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).Unix() - - secSinceDateEpoch := tUnix - dateEpoch - daysSinceDateEpoch = int32(secSinceDateEpoch / 86400) - case Infinity: - daysSinceDateEpoch = infinityDayOffset - case NegativeInfinity: - daysSinceDateEpoch = negativeInfinityDayOffset - } - - return pgio.AppendInt32(buf, daysSinceDateEpoch), nil -} - -type encodePlanDateCodecText struct{} - -func (encodePlanDateCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - date, err := value.(DateValuer).DateValue() - if err != nil { - return nil, err - } - - if !date.Valid { - return nil, nil - } - - switch date.InfinityModifier { - case Finite: - // Year 0000 is 1 BC - bc := false - year := date.Time.Year() - if year <= 0 { - year = -year + 1 - bc = true - } - - yearBytes := strconv.AppendInt(make([]byte, 0, 6), int64(year), 10) - for i := len(yearBytes); i < 4; i++ { - buf = append(buf, '0') - } - buf = append(buf, yearBytes...) - buf = append(buf, '-') - if date.Time.Month() < 10 { - buf = append(buf, '0') - } - buf = strconv.AppendInt(buf, int64(date.Time.Month()), 10) - buf = append(buf, '-') - if date.Time.Day() < 10 { - buf = append(buf, '0') - } - buf = strconv.AppendInt(buf, int64(date.Time.Day()), 10) - - if bc { - buf = append(buf, " BC"...) - } - case Infinity: - buf = append(buf, "infinity"...) - case NegativeInfinity: - buf = append(buf, "-infinity"...) - } - - return buf, nil -} - -func (DateCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case DateScanner: - return scanPlanBinaryDateToDateScanner{} - } - case TextFormatCode: - switch target.(type) { - case DateScanner: - return scanPlanTextAnyToDateScanner{} - } - } - - return nil -} - -type scanPlanBinaryDateToDateScanner struct{} - -func (scanPlanBinaryDateToDateScanner) Scan(src []byte, dst any) error { - scanner := (dst).(DateScanner) - - if src == nil { - return scanner.ScanDate(Date{}) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for date: %v", len(src)) - } - - dayOffset := int32(binary.BigEndian.Uint32(src)) - - switch dayOffset { - case infinityDayOffset: - return scanner.ScanDate(Date{InfinityModifier: Infinity, Valid: true}) - case negativeInfinityDayOffset: - return scanner.ScanDate(Date{InfinityModifier: -Infinity, Valid: true}) - default: - t := time.Date(2000, 1, int(1+dayOffset), 0, 0, 0, 0, time.UTC) - return scanner.ScanDate(Date{Time: t, Valid: true}) - } -} - -type scanPlanTextAnyToDateScanner struct{} - -var dateRegexp = regexp.MustCompile(`^(\d{4,})-(\d\d)-(\d\d)( BC)?$`) - -func (scanPlanTextAnyToDateScanner) Scan(src []byte, dst any) error { - scanner := (dst).(DateScanner) - - if src == nil { - return scanner.ScanDate(Date{}) - } - - sbuf := string(src) - match := dateRegexp.FindStringSubmatch(sbuf) - if match != nil { - year, err := strconv.ParseInt(match[1], 10, 32) - if err != nil { - return fmt.Errorf("BUG: cannot parse date that regexp matched (year): %w", err) - } - - month, err := strconv.ParseInt(match[2], 10, 32) - if err != nil { - return fmt.Errorf("BUG: cannot parse date that regexp matched (month): %w", err) - } - - day, err := strconv.ParseInt(match[3], 10, 32) - if err != nil { - return fmt.Errorf("BUG: cannot parse date that regexp matched (month): %w", err) - } - - // BC matched - if len(match[4]) > 0 { - year = -year + 1 - } - - t := time.Date(int(year), time.Month(month), int(day), 0, 0, 0, 0, time.UTC) - return scanner.ScanDate(Date{Time: t, Valid: true}) - } - - switch sbuf { - case "infinity": - return scanner.ScanDate(Date{InfinityModifier: Infinity, Valid: true}) - case "-infinity": - return scanner.ScanDate(Date{InfinityModifier: -Infinity, Valid: true}) - default: - return fmt.Errorf("invalid date format") - } -} - -func (c DateCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var date Date - err := codecScan(c, m, oid, format, src, &date) - if err != nil { - return nil, err - } - - if date.InfinityModifier != Finite { - return date.InfinityModifier.String(), nil - } - - return date.Time, nil -} - -func (c DateCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var date Date - err := codecScan(c, m, oid, format, src, &date) - if err != nil { - return nil, err - } - - if date.InfinityModifier != Finite { - return date.InfinityModifier, nil - } - - return date.Time, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/doc.go b/vendor/github.com/jackc/pgx/v5/pgtype/doc.go deleted file mode 100644 index 7687ea8fe..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/doc.go +++ /dev/null @@ -1,191 +0,0 @@ -// Package pgtype converts between Go and PostgreSQL values. -/* -The primary type is the Map type. It is a map of PostgreSQL types identified by OID (object ID) to a Codec. A Codec is -responsible for converting between Go and PostgreSQL values. NewMap creates a Map with all supported standard PostgreSQL -types already registered. Additional types can be registered with Map.RegisterType. - -Use Map.Scan and Map.Encode to decode PostgreSQL values to Go and encode Go values to PostgreSQL respectively. - -Base Type Mapping - -pgtype maps between all common base types directly between Go and PostgreSQL. In particular: - - Go PostgreSQL - ----------------------- - string varchar - text - - // Integers are automatically be converted to any other integer type if - // it can be done without overflow or underflow. - int8 - int16 smallint - int32 int - int64 bigint - int - uint8 - uint16 - uint32 - uint64 - uint - - // Floats are strict and do not automatically convert like integers. - float32 float4 - float64 float8 - - time.Time date - timestamp - timestamptz - - netip.Addr inet - netip.Prefix cidr - - []byte bytea - -Null Values - -pgtype can map NULLs in two ways. The first is types that can directly represent NULL such as Int4. They work in a -similar fashion to database/sql. The second is to use a pointer to a pointer. - - var foo pgtype.Text - var bar *string - err := conn.QueryRow("select foo, bar from widgets where id=$1", 42).Scan(&foo, &bar) - if err != nil { - return err - } - -When using nullable pgtype types as parameters for queries, one has to remember -to explicitly set their Valid field to true, otherwise the parameter's value will be NULL. - -JSON Support - -pgtype automatically marshals and unmarshals data from json and jsonb PostgreSQL types. - -Extending Existing PostgreSQL Type Support - -Generally, all Codecs will support interfaces that can be implemented to enable scanning and encoding. For example, -PointCodec can use any Go type that implements the PointScanner and PointValuer interfaces. So rather than use -pgtype.Point and application can directly use its own point type with pgtype as long as it implements those interfaces. - -See example_custom_type_test.go for an example of a custom type for the PostgreSQL point type. - -Sometimes pgx supports a PostgreSQL type such as numeric but the Go type is in an external package that does not have -pgx support such as github.com/shopspring/decimal. These types can be registered with pgtype with custom conversion -logic. See https://github.com/jackc/pgx-shopspring-decimal and https://github.com/jackc/pgx-gofrs-uuid for example -integrations. - -New PostgreSQL Type Support - -pgtype uses the PostgreSQL OID to determine how to encode or decode a value. pgtype supports array, composite, domain, -and enum types. However, any type created in PostgreSQL with CREATE TYPE will receive a new OID. This means that the OID -of each new PostgreSQL type must be registered for pgtype to handle values of that type with the correct Codec. - -The pgx.Conn LoadType method can return a *Type for array, composite, domain, and enum types by inspecting the database -metadata. This *Type can then be registered with Map.RegisterType. - -For example, the following function could be called after a connection is established: - - func RegisterDataTypes(ctx context.Context, conn *pgx.Conn) error { - dataTypeNames := []string{ - "foo", - "_foo", - "bar", - "_bar", - } - - for _, typeName := range dataTypeNames { - dataType, err := conn.LoadType(ctx, typeName) - if err != nil { - return err - } - conn.TypeMap().RegisterType(dataType) - } - - return nil - } - -A type cannot be registered unless all types it depends on are already registered. e.g. An array type cannot be -registered until its element type is registered. - -ArrayCodec implements support for arrays. If pgtype supports type T then it can easily support []T by registering an -ArrayCodec for the appropriate PostgreSQL OID. In addition, Array[T] type can support multi-dimensional arrays. - -CompositeCodec implements support for PostgreSQL composite types. Go structs can be scanned into if the public fields of -the struct are in the exact order and type of the PostgreSQL type or by implementing CompositeIndexScanner and -CompositeIndexGetter. - -Domain types are treated as their underlying type if the underlying type and the domain type are registered. - -PostgreSQL enums can usually be treated as text. However, EnumCodec implements support for interning strings which can -reduce memory usage. - -While pgtype will often still work with unregistered types it is highly recommended that all types be registered due to -an improvement in performance and the elimination of certain edge cases. - -If an entirely new PostgreSQL type (e.g. PostGIS types) is used then the application or a library can create a new -Codec. Then the OID / Codec mapping can be registered with Map.RegisterType. There is no difference between a Codec -defined and registered by the application and a Codec built in to pgtype. See any of the Codecs in pgtype for Codec -examples and for examples of type registration. - -Encoding Unknown Types - -pgtype works best when the OID of the PostgreSQL type is known. But in some cases such as using the simple protocol the -OID is unknown. In this case Map.RegisterDefaultPgType can be used to register an assumed OID for a particular Go type. - -Renamed Types - -If pgtype does not recognize a type and that type is a renamed simple type simple (e.g. type MyInt32 int32) pgtype acts -as if it is the underlying type. It currently cannot automatically detect the underlying type of renamed structs (eg.g. -type MyTime time.Time). - -Compatibility with database/sql - -pgtype also includes support for custom types implementing the database/sql.Scanner and database/sql/driver.Valuer -interfaces. - -Encoding Typed Nils - -pgtype encodes untyped and typed nils (e.g. nil and []byte(nil)) to the SQL NULL value without going through the Codec -system. This means that Codecs and other encoding logic do not have to handle nil or *T(nil). - -However, database/sql compatibility requires Value to be called on T(nil) when T implements driver.Valuer. Therefore, -driver.Valuer values are only considered NULL when *T(nil) where driver.Valuer is implemented on T not on *T. See -https://github.com/golang/go/issues/8415 and -https://github.com/golang/go/commit/0ce1d79a6a771f7449ec493b993ed2a720917870. - -Child Records - -pgtype's support for arrays and composite records can be used to load records and their children in a single query. See -example_child_records_test.go for an example. - -Overview of Scanning Implementation - -The first step is to use the OID to lookup the correct Codec. If the OID is unavailable, Map will try to find the OID -from previous calls of Map.RegisterDefaultPgType. The Map will call the Codec's PlanScan method to get a plan for -scanning into the Go value. A Codec will support scanning into one or more Go types. Oftentime these Go types are -interfaces rather than explicit types. For example, PointCodec can use any Go type that implements the PointScanner and -PointValuer interfaces. - -If a Go value is not supported directly by a Codec then Map will try wrapping it with additional logic and try again. -For example, Int8Codec does not support scanning into a renamed type (e.g. type myInt64 int64). But Map will detect that -myInt64 is a renamed type and create a plan that converts the value to the underlying int64 type and then passes that to -the Codec (see TryFindUnderlyingTypeScanPlan). - -These plan wrappers are contained in Map.TryWrapScanPlanFuncs. By default these contain shared logic to handle renamed -types, pointers to pointers, slices, composite types, etc. Additional plan wrappers can be added to seamlessly integrate -types that do not support pgx directly. For example, the before mentioned -https://github.com/jackc/pgx-shopspring-decimal package detects decimal.Decimal values, wraps them in something -implementing NumericScanner and passes that to the Codec. - -Map.Scan and Map.Encode are convenience methods that wrap Map.PlanScan and Map.PlanEncode. Determining how to scan or -encode a particular type may be a time consuming operation. Hence the planning and execution steps of a conversion are -internally separated. - -Reducing Compiled Binary Size - -pgx.QueryExecModeExec and pgx.QueryExecModeSimpleProtocol require the default PostgreSQL type to be registered for each -Go type used as a query parameter. By default pgx does this for all supported types and their array variants. If an -application does not use those query execution modes or manually registers the default PostgreSQL type for the types it -uses as query parameters it can use the build tag nopgxregisterdefaulttypes. This omits the default type registration -and reduces the compiled binary size by ~2MB. -*/ -package pgtype diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go deleted file mode 100644 index 5e787c1e2..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go +++ /dev/null @@ -1,109 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "fmt" -) - -// EnumCodec is a codec that caches the strings it decodes. If the same string is read multiple times only one copy is -// allocated. These strings are only garbage collected when the EnumCodec is garbage collected. EnumCodec can be used -// for any text type not only enums, but it should only be used when there are a small number of possible values. -type EnumCodec struct { - membersMap map[string]string // map to quickly lookup member and reuse string instead of allocating -} - -func (EnumCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (EnumCodec) PreferredFormat() int16 { - return TextFormatCode -} - -func (EnumCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case TextFormatCode, BinaryFormatCode: - switch value.(type) { - case string: - return encodePlanTextCodecString{} - case []byte: - return encodePlanTextCodecByteSlice{} - case TextValuer: - return encodePlanTextCodecTextValuer{} - } - } - - return nil -} - -func (c *EnumCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case TextFormatCode, BinaryFormatCode: - switch target.(type) { - case *string: - return &scanPlanTextAnyToEnumString{codec: c} - case *[]byte: - return scanPlanAnyToNewByteSlice{} - case TextScanner: - return &scanPlanTextAnyToEnumTextScanner{codec: c} - } - } - - return nil -} - -func (c *EnumCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return c.DecodeValue(m, oid, format, src) -} - -func (c *EnumCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - return c.lookupAndCacheString(src), nil -} - -// lookupAndCacheString looks for src in the members map. If it is not found it is added to the map. -func (c *EnumCodec) lookupAndCacheString(src []byte) string { - if c.membersMap == nil { - c.membersMap = make(map[string]string) - } - - if s, found := c.membersMap[string(src)]; found { - return s - } - - s := string(src) - c.membersMap[s] = s - return s -} - -type scanPlanTextAnyToEnumString struct { - codec *EnumCodec -} - -func (plan *scanPlanTextAnyToEnumString) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p := (dst).(*string) - *p = plan.codec.lookupAndCacheString(src) - - return nil -} - -type scanPlanTextAnyToEnumTextScanner struct { - codec *EnumCodec -} - -func (plan *scanPlanTextAnyToEnumTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) - - if src == nil { - return scanner.ScanText(Text{}) - } - - return scanner.ScanText(Text{String: plan.codec.lookupAndCacheString(src), Valid: true}) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go deleted file mode 100644 index 8646d9d22..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go +++ /dev/null @@ -1,319 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "encoding/json" - "fmt" - "math" - "strconv" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Float4 struct { - Float32 float32 - Valid bool -} - -// ScanFloat64 implements the Float64Scanner interface. -func (f *Float4) ScanFloat64(n Float8) error { - *f = Float4{Float32: float32(n.Float64), Valid: n.Valid} - return nil -} - -func (f Float4) Float64Value() (Float8, error) { - return Float8{Float64: float64(f.Float32), Valid: f.Valid}, nil -} - -func (f *Float4) ScanInt64(n Int8) error { - *f = Float4{Float32: float32(n.Int64), Valid: n.Valid} - return nil -} - -func (f Float4) Int64Value() (Int8, error) { - return Int8{Int64: int64(f.Float32), Valid: f.Valid}, nil -} - -// Scan implements the database/sql Scanner interface. -func (f *Float4) Scan(src any) error { - if src == nil { - *f = Float4{} - return nil - } - - switch src := src.(type) { - case float64: - *f = Float4{Float32: float32(src), Valid: true} - return nil - case string: - n, err := strconv.ParseFloat(string(src), 32) - if err != nil { - return err - } - *f = Float4{Float32: float32(n), Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (f Float4) Value() (driver.Value, error) { - if !f.Valid { - return nil, nil - } - return float64(f.Float32), nil -} - -func (f Float4) MarshalJSON() ([]byte, error) { - if !f.Valid { - return []byte("null"), nil - } - return json.Marshal(f.Float32) -} - -func (f *Float4) UnmarshalJSON(b []byte) error { - var n *float32 - err := json.Unmarshal(b, &n) - if err != nil { - return err - } - - if n == nil { - *f = Float4{} - } else { - *f = Float4{Float32: *n, Valid: true} - } - - return nil -} - -type Float4Codec struct{} - -func (Float4Codec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (Float4Codec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (Float4Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case float32: - return encodePlanFloat4CodecBinaryFloat32{} - case Float64Valuer: - return encodePlanFloat4CodecBinaryFloat64Valuer{} - case Int64Valuer: - return encodePlanFloat4CodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case float32: - return encodePlanTextFloat32{} - case Float64Valuer: - return encodePlanTextFloat64Valuer{} - case Int64Valuer: - return encodePlanTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanFloat4CodecBinaryFloat32 struct{} - -func (encodePlanFloat4CodecBinaryFloat32) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(float32) - return pgio.AppendUint32(buf, math.Float32bits(n)), nil -} - -type encodePlanTextFloat32 struct{} - -func (encodePlanTextFloat32) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(float32) - return append(buf, strconv.FormatFloat(float64(n), 'f', -1, 32)...), nil -} - -type encodePlanFloat4CodecBinaryFloat64Valuer struct{} - -func (encodePlanFloat4CodecBinaryFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Float64Valuer).Float64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - return pgio.AppendUint32(buf, math.Float32bits(float32(n.Float64))), nil -} - -type encodePlanFloat4CodecBinaryInt64Valuer struct{} - -func (encodePlanFloat4CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - f := float32(n.Int64) - return pgio.AppendUint32(buf, math.Float32bits(f)), nil -} - -func (Float4Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *float32: - return scanPlanBinaryFloat4ToFloat32{} - case Float64Scanner: - return scanPlanBinaryFloat4ToFloat64Scanner{} - case Int64Scanner: - return scanPlanBinaryFloat4ToInt64Scanner{} - case TextScanner: - return scanPlanBinaryFloat4ToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *float32: - return scanPlanTextAnyToFloat32{} - case Float64Scanner: - return scanPlanTextAnyToFloat64Scanner{} - case Int64Scanner: - return scanPlanTextAnyToInt64Scanner{} - } - } - - return nil -} - -type scanPlanBinaryFloat4ToFloat32 struct{} - -func (scanPlanBinaryFloat4ToFloat32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) - } - - n := int32(binary.BigEndian.Uint32(src)) - f := (dst).(*float32) - *f = math.Float32frombits(uint32(n)) - - return nil -} - -type scanPlanBinaryFloat4ToFloat64Scanner struct{} - -func (scanPlanBinaryFloat4ToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) - - if src == nil { - return s.ScanFloat64(Float8{}) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) - } - - n := int32(binary.BigEndian.Uint32(src)) - return s.ScanFloat64(Float8{Float64: float64(math.Float32frombits(uint32(n))), Valid: true}) -} - -type scanPlanBinaryFloat4ToInt64Scanner struct{} - -func (scanPlanBinaryFloat4ToInt64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Int64Scanner) - - if src == nil { - return s.ScanInt64(Int8{}) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) - } - - ui32 := int32(binary.BigEndian.Uint32(src)) - f32 := math.Float32frombits(uint32(ui32)) - i64 := int64(f32) - if f32 != float32(i64) { - return fmt.Errorf("cannot losslessly convert %v to int64", f32) - } - - return s.ScanInt64(Int8{Int64: i64, Valid: true}) -} - -type scanPlanBinaryFloat4ToTextScanner struct{} - -func (scanPlanBinaryFloat4ToTextScanner) Scan(src []byte, dst any) error { - s := (dst).(TextScanner) - - if src == nil { - return s.ScanText(Text{}) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for float4: %v", len(src)) - } - - ui32 := int32(binary.BigEndian.Uint32(src)) - f32 := math.Float32frombits(uint32(ui32)) - - return s.ScanText(Text{String: strconv.FormatFloat(float64(f32), 'f', -1, 32), Valid: true}) -} - -type scanPlanTextAnyToFloat32 struct{} - -func (scanPlanTextAnyToFloat32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - n, err := strconv.ParseFloat(string(src), 32) - if err != nil { - return err - } - - f := (dst).(*float32) - *f = float32(n) - - return nil -} - -func (c Float4Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var n float32 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return float64(n), nil -} - -func (c Float4Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n float32 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float8.go b/vendor/github.com/jackc/pgx/v5/pgtype/float8.go deleted file mode 100644 index 9c923c9a3..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/float8.go +++ /dev/null @@ -1,365 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "encoding/json" - "fmt" - "math" - "strconv" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Float64Scanner interface { - ScanFloat64(Float8) error -} - -type Float64Valuer interface { - Float64Value() (Float8, error) -} - -type Float8 struct { - Float64 float64 - Valid bool -} - -// ScanFloat64 implements the Float64Scanner interface. -func (f *Float8) ScanFloat64(n Float8) error { - *f = n - return nil -} - -func (f Float8) Float64Value() (Float8, error) { - return f, nil -} - -func (f *Float8) ScanInt64(n Int8) error { - *f = Float8{Float64: float64(n.Int64), Valid: n.Valid} - return nil -} - -func (f Float8) Int64Value() (Int8, error) { - return Int8{Int64: int64(f.Float64), Valid: f.Valid}, nil -} - -// Scan implements the database/sql Scanner interface. -func (f *Float8) Scan(src any) error { - if src == nil { - *f = Float8{} - return nil - } - - switch src := src.(type) { - case float64: - *f = Float8{Float64: src, Valid: true} - return nil - case string: - n, err := strconv.ParseFloat(string(src), 64) - if err != nil { - return err - } - *f = Float8{Float64: n, Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (f Float8) Value() (driver.Value, error) { - if !f.Valid { - return nil, nil - } - return f.Float64, nil -} - -func (f Float8) MarshalJSON() ([]byte, error) { - if !f.Valid { - return []byte("null"), nil - } - return json.Marshal(f.Float64) -} - -func (f *Float8) UnmarshalJSON(b []byte) error { - var n *float64 - err := json.Unmarshal(b, &n) - if err != nil { - return err - } - - if n == nil { - *f = Float8{} - } else { - *f = Float8{Float64: *n, Valid: true} - } - - return nil -} - -type Float8Codec struct{} - -func (Float8Codec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (Float8Codec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (Float8Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case float64: - return encodePlanFloat8CodecBinaryFloat64{} - case Float64Valuer: - return encodePlanFloat8CodecBinaryFloat64Valuer{} - case Int64Valuer: - return encodePlanFloat8CodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case float64: - return encodePlanTextFloat64{} - case Float64Valuer: - return encodePlanTextFloat64Valuer{} - case Int64Valuer: - return encodePlanTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanFloat8CodecBinaryFloat64 struct{} - -func (encodePlanFloat8CodecBinaryFloat64) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(float64) - return pgio.AppendUint64(buf, math.Float64bits(n)), nil -} - -type encodePlanTextFloat64 struct{} - -func (encodePlanTextFloat64) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(float64) - return append(buf, strconv.FormatFloat(n, 'f', -1, 64)...), nil -} - -type encodePlanFloat8CodecBinaryFloat64Valuer struct{} - -func (encodePlanFloat8CodecBinaryFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Float64Valuer).Float64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - return pgio.AppendUint64(buf, math.Float64bits(n.Float64)), nil -} - -type encodePlanTextFloat64Valuer struct{} - -func (encodePlanTextFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Float64Valuer).Float64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - return append(buf, strconv.FormatFloat(n.Float64, 'f', -1, 64)...), nil -} - -type encodePlanFloat8CodecBinaryInt64Valuer struct{} - -func (encodePlanFloat8CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - f := float64(n.Int64) - return pgio.AppendUint64(buf, math.Float64bits(f)), nil -} - -type encodePlanTextInt64Valuer struct{} - -func (encodePlanTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil -} - -func (Float8Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *float64: - return scanPlanBinaryFloat8ToFloat64{} - case Float64Scanner: - return scanPlanBinaryFloat8ToFloat64Scanner{} - case Int64Scanner: - return scanPlanBinaryFloat8ToInt64Scanner{} - case TextScanner: - return scanPlanBinaryFloat8ToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *float64: - return scanPlanTextAnyToFloat64{} - case Float64Scanner: - return scanPlanTextAnyToFloat64Scanner{} - case Int64Scanner: - return scanPlanTextAnyToInt64Scanner{} - } - } - - return nil -} - -type scanPlanBinaryFloat8ToFloat64 struct{} - -func (scanPlanBinaryFloat8ToFloat64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) - } - - n := int64(binary.BigEndian.Uint64(src)) - f := (dst).(*float64) - *f = math.Float64frombits(uint64(n)) - - return nil -} - -type scanPlanBinaryFloat8ToFloat64Scanner struct{} - -func (scanPlanBinaryFloat8ToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) - - if src == nil { - return s.ScanFloat64(Float8{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) - } - - n := int64(binary.BigEndian.Uint64(src)) - return s.ScanFloat64(Float8{Float64: math.Float64frombits(uint64(n)), Valid: true}) -} - -type scanPlanBinaryFloat8ToInt64Scanner struct{} - -func (scanPlanBinaryFloat8ToInt64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Int64Scanner) - - if src == nil { - return s.ScanInt64(Int8{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) - } - - ui64 := int64(binary.BigEndian.Uint64(src)) - f64 := math.Float64frombits(uint64(ui64)) - i64 := int64(f64) - if f64 != float64(i64) { - return fmt.Errorf("cannot losslessly convert %v to int64", f64) - } - - return s.ScanInt64(Int8{Int64: i64, Valid: true}) -} - -type scanPlanBinaryFloat8ToTextScanner struct{} - -func (scanPlanBinaryFloat8ToTextScanner) Scan(src []byte, dst any) error { - s := (dst).(TextScanner) - - if src == nil { - return s.ScanText(Text{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for float8: %v", len(src)) - } - - ui64 := int64(binary.BigEndian.Uint64(src)) - f64 := math.Float64frombits(uint64(ui64)) - - return s.ScanText(Text{String: strconv.FormatFloat(f64, 'f', -1, 64), Valid: true}) -} - -type scanPlanTextAnyToFloat64 struct{} - -func (scanPlanTextAnyToFloat64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - n, err := strconv.ParseFloat(string(src), 64) - if err != nil { - return err - } - - f := (dst).(*float64) - *f = n - - return nil -} - -type scanPlanTextAnyToFloat64Scanner struct{} - -func (scanPlanTextAnyToFloat64Scanner) Scan(src []byte, dst any) error { - s := (dst).(Float64Scanner) - - if src == nil { - return s.ScanFloat64(Float8{}) - } - - n, err := strconv.ParseFloat(string(src), 64) - if err != nil { - return err - } - - return s.ScanFloat64(Float8{Float64: n, Valid: true}) -} - -func (c Float8Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return c.DecodeValue(m, oid, format, src) -} - -func (c Float8Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n float64 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go b/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go deleted file mode 100644 index 2f34f4c9e..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go +++ /dev/null @@ -1,486 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "errors" - "fmt" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type HstoreScanner interface { - ScanHstore(v Hstore) error -} - -type HstoreValuer interface { - HstoreValue() (Hstore, error) -} - -// Hstore represents an hstore column that can be null or have null values -// associated with its keys. -type Hstore map[string]*string - -func (h *Hstore) ScanHstore(v Hstore) error { - *h = v - return nil -} - -func (h Hstore) HstoreValue() (Hstore, error) { - return h, nil -} - -// Scan implements the database/sql Scanner interface. -func (h *Hstore) Scan(src any) error { - if src == nil { - *h = nil - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToHstoreScanner{}.scanString(src, h) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (h Hstore) Value() (driver.Value, error) { - if h == nil { - return nil, nil - } - - buf, err := HstoreCodec{}.PlanEncode(nil, 0, TextFormatCode, h).Encode(h, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type HstoreCodec struct{} - -func (HstoreCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (HstoreCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (HstoreCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(HstoreValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanHstoreCodecBinary{} - case TextFormatCode: - return encodePlanHstoreCodecText{} - } - - return nil -} - -type encodePlanHstoreCodecBinary struct{} - -func (encodePlanHstoreCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - hstore, err := value.(HstoreValuer).HstoreValue() - if err != nil { - return nil, err - } - - if hstore == nil { - return nil, nil - } - - buf = pgio.AppendInt32(buf, int32(len(hstore))) - - for k, v := range hstore { - buf = pgio.AppendInt32(buf, int32(len(k))) - buf = append(buf, k...) - - if v == nil { - buf = pgio.AppendInt32(buf, -1) - } else { - buf = pgio.AppendInt32(buf, int32(len(*v))) - buf = append(buf, (*v)...) - } - } - - return buf, nil -} - -type encodePlanHstoreCodecText struct{} - -func (encodePlanHstoreCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - hstore, err := value.(HstoreValuer).HstoreValue() - if err != nil { - return nil, err - } - - if len(hstore) == 0 { - // distinguish between empty and nil: Not strictly required by Postgres, since its protocol - // explicitly marks NULL column values separately. However, the Binary codec does this, and - // this means we can "round trip" Encode and Scan without data loss. - // nil: []byte(nil); empty: []byte{} - if hstore == nil { - return nil, nil - } - return []byte{}, nil - } - - firstPair := true - - for k, v := range hstore { - if firstPair { - firstPair = false - } else { - buf = append(buf, ',', ' ') - } - - // unconditionally quote hstore keys/values like Postgres does - // this avoids a Mac OS X Postgres hstore parsing bug: - // https://www.postgresql.org/message-id/CA%2BHWA9awUW0%2BRV_gO9r1ABZwGoZxPztcJxPy8vMFSTbTfi4jig%40mail.gmail.com - buf = append(buf, '"') - buf = append(buf, quoteArrayReplacer.Replace(k)...) - buf = append(buf, '"') - buf = append(buf, "=>"...) - - if v == nil { - buf = append(buf, "NULL"...) - } else { - buf = append(buf, '"') - buf = append(buf, quoteArrayReplacer.Replace(*v)...) - buf = append(buf, '"') - } - } - - return buf, nil -} - -func (HstoreCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case HstoreScanner: - return scanPlanBinaryHstoreToHstoreScanner{} - } - case TextFormatCode: - switch target.(type) { - case HstoreScanner: - return scanPlanTextAnyToHstoreScanner{} - } - } - - return nil -} - -type scanPlanBinaryHstoreToHstoreScanner struct{} - -func (scanPlanBinaryHstoreToHstoreScanner) Scan(src []byte, dst any) error { - scanner := (dst).(HstoreScanner) - - if src == nil { - return scanner.ScanHstore(Hstore(nil)) - } - - rp := 0 - - const uint32Len = 4 - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) - } - pairCount := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += uint32Len - - hstore := make(Hstore, pairCount) - // one allocation for all *string, rather than one per string, just like text parsing - valueStrings := make([]string, pairCount) - - for i := 0; i < pairCount; i++ { - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) - } - keyLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += uint32Len - - if len(src[rp:]) < keyLen { - return fmt.Errorf("hstore incomplete %v", src) - } - key := string(src[rp : rp+keyLen]) - rp += keyLen - - if len(src[rp:]) < uint32Len { - return fmt.Errorf("hstore incomplete %v", src) - } - valueLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - - if valueLen >= 0 { - valueStrings[i] = string(src[rp : rp+valueLen]) - rp += valueLen - - hstore[key] = &valueStrings[i] - } else { - hstore[key] = nil - } - } - - return scanner.ScanHstore(hstore) -} - -type scanPlanTextAnyToHstoreScanner struct{} - -func (s scanPlanTextAnyToHstoreScanner) Scan(src []byte, dst any) error { - scanner := (dst).(HstoreScanner) - - if src == nil { - return scanner.ScanHstore(Hstore(nil)) - } - return s.scanString(string(src), scanner) -} - -// scanString does not return nil hstore values because string cannot be nil. -func (scanPlanTextAnyToHstoreScanner) scanString(src string, scanner HstoreScanner) error { - hstore, err := parseHstore(src) - if err != nil { - return err - } - return scanner.ScanHstore(hstore) -} - -func (c HstoreCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c HstoreCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var hstore Hstore - err := codecScan(c, m, oid, format, src, &hstore) - if err != nil { - return nil, err - } - return hstore, nil -} - -type hstoreParser struct { - str string - pos int - nextBackslash int -} - -func newHSP(in string) *hstoreParser { - return &hstoreParser{ - pos: 0, - str: in, - nextBackslash: strings.IndexByte(in, '\\'), - } -} - -func (p *hstoreParser) atEnd() bool { - return p.pos >= len(p.str) -} - -// consume returns the next byte of the string, or end if the string is done. -func (p *hstoreParser) consume() (b byte, end bool) { - if p.pos >= len(p.str) { - return 0, true - } - b = p.str[p.pos] - p.pos++ - return b, false -} - -func unexpectedByteErr(actualB byte, expectedB byte) error { - return fmt.Errorf("expected '%c' ('%#v'); found '%c' ('%#v')", expectedB, expectedB, actualB, actualB) -} - -// consumeExpectedByte consumes expectedB from the string, or returns an error. -func (p *hstoreParser) consumeExpectedByte(expectedB byte) error { - nextB, end := p.consume() - if end { - return fmt.Errorf("expected '%c' ('%#v'); found end", expectedB, expectedB) - } - if nextB != expectedB { - return unexpectedByteErr(nextB, expectedB) - } - return nil -} - -// consumeExpected2 consumes two expected bytes or returns an error. -// This was a bit faster than using a string argument (better inlining? Not sure). -func (p *hstoreParser) consumeExpected2(one byte, two byte) error { - if p.pos+2 > len(p.str) { - return errors.New("unexpected end of string") - } - if p.str[p.pos] != one { - return unexpectedByteErr(p.str[p.pos], one) - } - if p.str[p.pos+1] != two { - return unexpectedByteErr(p.str[p.pos+1], two) - } - p.pos += 2 - return nil -} - -var errEOSInQuoted = errors.New(`found end before closing double-quote ('"')`) - -// consumeDoubleQuoted consumes a double-quoted string from p. The double quote must have been -// parsed already. This copies the string from the backing string so it can be garbage collected. -func (p *hstoreParser) consumeDoubleQuoted() (string, error) { - // fast path: assume most keys/values do not contain escapes - nextDoubleQuote := strings.IndexByte(p.str[p.pos:], '"') - if nextDoubleQuote == -1 { - return "", errEOSInQuoted - } - nextDoubleQuote += p.pos - if p.nextBackslash == -1 || p.nextBackslash > nextDoubleQuote { - // clone the string from the source string to ensure it can be garbage collected separately - // TODO: use strings.Clone on Go 1.20; this could get optimized away - s := strings.Clone(p.str[p.pos:nextDoubleQuote]) - p.pos = nextDoubleQuote + 1 - return s, nil - } - - // slow path: string contains escapes - s, err := p.consumeDoubleQuotedWithEscapes(p.nextBackslash) - p.nextBackslash = strings.IndexByte(p.str[p.pos:], '\\') - if p.nextBackslash != -1 { - p.nextBackslash += p.pos - } - return s, err -} - -// consumeDoubleQuotedWithEscapes consumes a double-quoted string containing escapes, starting -// at p.pos, and with the first backslash at firstBackslash. This copies the string so it can be -// garbage collected separately. -func (p *hstoreParser) consumeDoubleQuotedWithEscapes(firstBackslash int) (string, error) { - // copy the prefix that does not contain backslashes - var builder strings.Builder - builder.WriteString(p.str[p.pos:firstBackslash]) - - // skip to the backslash - p.pos = firstBackslash - - // copy bytes until the end, unescaping backslashes - for { - nextB, end := p.consume() - if end { - return "", errEOSInQuoted - } else if nextB == '"' { - break - } else if nextB == '\\' { - // escape: skip the backslash and copy the char - nextB, end = p.consume() - if end { - return "", errEOSInQuoted - } - if !(nextB == '\\' || nextB == '"') { - return "", fmt.Errorf("unexpected escape in quoted string: found '%#v'", nextB) - } - builder.WriteByte(nextB) - } else { - // normal byte: copy it - builder.WriteByte(nextB) - } - } - return builder.String(), nil -} - -// consumePairSeparator consumes the Hstore pair separator ", " or returns an error. -func (p *hstoreParser) consumePairSeparator() error { - return p.consumeExpected2(',', ' ') -} - -// consumeKVSeparator consumes the Hstore key/value separator "=>" or returns an error. -func (p *hstoreParser) consumeKVSeparator() error { - return p.consumeExpected2('=', '>') -} - -// consumeDoubleQuotedOrNull consumes the Hstore key/value separator "=>" or returns an error. -func (p *hstoreParser) consumeDoubleQuotedOrNull() (Text, error) { - // peek at the next byte - if p.atEnd() { - return Text{}, errors.New("found end instead of value") - } - next := p.str[p.pos] - if next == 'N' { - // must be the exact string NULL: use consumeExpected2 twice - err := p.consumeExpected2('N', 'U') - if err != nil { - return Text{}, err - } - err = p.consumeExpected2('L', 'L') - if err != nil { - return Text{}, err - } - return Text{String: "", Valid: false}, nil - } else if next != '"' { - return Text{}, unexpectedByteErr(next, '"') - } - - // skip the double quote - p.pos += 1 - s, err := p.consumeDoubleQuoted() - if err != nil { - return Text{}, err - } - return Text{String: s, Valid: true}, nil -} - -func parseHstore(s string) (Hstore, error) { - p := newHSP(s) - - // This is an over-estimate of the number of key/value pairs. Use '>' because I am guessing it - // is less likely to occur in keys/values than '=' or ','. - numPairsEstimate := strings.Count(s, ">") - // makes one allocation of strings for the entire Hstore, rather than one allocation per value. - valueStrings := make([]string, 0, numPairsEstimate) - result := make(Hstore, numPairsEstimate) - first := true - for !p.atEnd() { - if !first { - err := p.consumePairSeparator() - if err != nil { - return nil, err - } - } else { - first = false - } - - err := p.consumeExpectedByte('"') - if err != nil { - return nil, err - } - - key, err := p.consumeDoubleQuoted() - if err != nil { - return nil, err - } - - err = p.consumeKVSeparator() - if err != nil { - return nil, err - } - - value, err := p.consumeDoubleQuotedOrNull() - if err != nil { - return nil, err - } - if value.Valid { - valueStrings = append(valueStrings, value.String) - result[key] = &valueStrings[len(valueStrings)-1] - } else { - result[key] = nil - } - } - - return result, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/inet.go b/vendor/github.com/jackc/pgx/v5/pgtype/inet.go deleted file mode 100644 index 6ca10ea07..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/inet.go +++ /dev/null @@ -1,200 +0,0 @@ -package pgtype - -import ( - "bytes" - "database/sql/driver" - "errors" - "fmt" - "net/netip" -) - -// Network address family is dependent on server socket.h value for AF_INET. -// In practice, all platforms appear to have the same value. See -// src/include/utils/inet.h for more information. -const ( - defaultAFInet = 2 - defaultAFInet6 = 3 -) - -type NetipPrefixScanner interface { - ScanNetipPrefix(v netip.Prefix) error -} - -type NetipPrefixValuer interface { - NetipPrefixValue() (netip.Prefix, error) -} - -// InetCodec handles both inet and cidr PostgreSQL types. The preferred Go types are netip.Prefix and netip.Addr. If -// IsValid() is false then they are treated as SQL NULL. -type InetCodec struct{} - -func (InetCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (InetCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (InetCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(NetipPrefixValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanInetCodecBinary{} - case TextFormatCode: - return encodePlanInetCodecText{} - } - - return nil -} - -type encodePlanInetCodecBinary struct{} - -func (encodePlanInetCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - prefix, err := value.(NetipPrefixValuer).NetipPrefixValue() - if err != nil { - return nil, err - } - - if !prefix.IsValid() { - return nil, nil - } - - var family byte - if prefix.Addr().Is4() { - family = defaultAFInet - } else { - family = defaultAFInet6 - } - - buf = append(buf, family) - - ones := prefix.Bits() - buf = append(buf, byte(ones)) - - // is_cidr is ignored on server - buf = append(buf, 0) - - if family == defaultAFInet { - buf = append(buf, byte(4)) - b := prefix.Addr().As4() - buf = append(buf, b[:]...) - } else { - buf = append(buf, byte(16)) - b := prefix.Addr().As16() - buf = append(buf, b[:]...) - } - - return buf, nil -} - -type encodePlanInetCodecText struct{} - -func (encodePlanInetCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - prefix, err := value.(NetipPrefixValuer).NetipPrefixValue() - if err != nil { - return nil, err - } - - if !prefix.IsValid() { - return nil, nil - } - - return append(buf, prefix.String()...), nil -} - -func (InetCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case NetipPrefixScanner: - return scanPlanBinaryInetToNetipPrefixScanner{} - } - case TextFormatCode: - switch target.(type) { - case NetipPrefixScanner: - return scanPlanTextAnyToNetipPrefixScanner{} - } - } - - return nil -} - -func (c InetCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c InetCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var prefix netip.Prefix - err := codecScan(c, m, oid, format, src, (*netipPrefixWrapper)(&prefix)) - if err != nil { - return nil, err - } - - if !prefix.IsValid() { - return nil, nil - } - - return prefix, nil -} - -type scanPlanBinaryInetToNetipPrefixScanner struct{} - -func (scanPlanBinaryInetToNetipPrefixScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NetipPrefixScanner) - - if src == nil { - return scanner.ScanNetipPrefix(netip.Prefix{}) - } - - if len(src) != 8 && len(src) != 20 { - return fmt.Errorf("Received an invalid size for an inet: %d", len(src)) - } - - // ignore family - bits := src[1] - // ignore is_cidr - // ignore addressLength - implicit in length of message - - addr, ok := netip.AddrFromSlice(src[4:]) - if !ok { - return errors.New("netip.AddrFromSlice failed") - } - - return scanner.ScanNetipPrefix(netip.PrefixFrom(addr, int(bits))) -} - -type scanPlanTextAnyToNetipPrefixScanner struct{} - -func (scanPlanTextAnyToNetipPrefixScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NetipPrefixScanner) - - if src == nil { - return scanner.ScanNetipPrefix(netip.Prefix{}) - } - - var prefix netip.Prefix - if bytes.IndexByte(src, '/') == -1 { - addr, err := netip.ParseAddr(string(src)) - if err != nil { - return err - } - prefix = netip.PrefixFrom(addr, addr.BitLen()) - } else { - var err error - prefix, err = netip.ParsePrefix(string(src)) - if err != nil { - return err - } - } - - return scanner.ScanNetipPrefix(prefix) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int.go b/vendor/github.com/jackc/pgx/v5/pgtype/int.go deleted file mode 100644 index 90a20a26a..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/int.go +++ /dev/null @@ -1,1980 +0,0 @@ -// Do not edit. Generated from pgtype/int.go.erb -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "encoding/json" - "fmt" - "math" - "strconv" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Int64Scanner interface { - ScanInt64(Int8) error -} - -type Int64Valuer interface { - Int64Value() (Int8, error) -} - -type Int2 struct { - Int16 int16 - Valid bool -} - -// ScanInt64 implements the Int64Scanner interface. -func (dst *Int2) ScanInt64(n Int8) error { - if !n.Valid { - *dst = Int2{} - return nil - } - - if n.Int64 < math.MinInt16 { - return fmt.Errorf("%d is less than minimum value for Int2", n.Int64) - } - if n.Int64 > math.MaxInt16 { - return fmt.Errorf("%d is greater than maximum value for Int2", n.Int64) - } - *dst = Int2{Int16: int16(n.Int64), Valid: true} - - return nil -} - -func (n Int2) Int64Value() (Int8, error) { - return Int8{Int64: int64(n.Int16), Valid: n.Valid}, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Int2) Scan(src any) error { - if src == nil { - *dst = Int2{} - return nil - } - - var n int64 - - switch src := src.(type) { - case int64: - n = src - case string: - var err error - n, err = strconv.ParseInt(src, 10, 16) - if err != nil { - return err - } - case []byte: - var err error - n, err = strconv.ParseInt(string(src), 10, 16) - if err != nil { - return err - } - default: - return fmt.Errorf("cannot scan %T", src) - } - - if n < math.MinInt16 { - return fmt.Errorf("%d is greater than maximum value for Int2", n) - } - if n > math.MaxInt16 { - return fmt.Errorf("%d is greater than maximum value for Int2", n) - } - *dst = Int2{Int16: int16(n), Valid: true} - - return nil -} - -// Value implements the database/sql/driver Valuer interface. -func (src Int2) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - return int64(src.Int16), nil -} - -func (src Int2) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - return []byte(strconv.FormatInt(int64(src.Int16), 10)), nil -} - -func (dst *Int2) UnmarshalJSON(b []byte) error { - var n *int16 - err := json.Unmarshal(b, &n) - if err != nil { - return err - } - - if n == nil { - *dst = Int2{} - } else { - *dst = Int2{Int16: *n, Valid: true} - } - - return nil -} - -type Int2Codec struct{} - -func (Int2Codec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (Int2Codec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (Int2Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case int16: - return encodePlanInt2CodecBinaryInt16{} - case Int64Valuer: - return encodePlanInt2CodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case int16: - return encodePlanInt2CodecTextInt16{} - case Int64Valuer: - return encodePlanInt2CodecTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanInt2CodecBinaryInt16 struct{} - -func (encodePlanInt2CodecBinaryInt16) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(int16) - return pgio.AppendInt16(buf, int16(n)), nil -} - -type encodePlanInt2CodecTextInt16 struct{} - -func (encodePlanInt2CodecTextInt16) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(int16) - return append(buf, strconv.FormatInt(int64(n), 10)...), nil -} - -type encodePlanInt2CodecBinaryInt64Valuer struct{} - -func (encodePlanInt2CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if n.Int64 > math.MaxInt16 { - return nil, fmt.Errorf("%d is greater than maximum value for int2", n.Int64) - } - if n.Int64 < math.MinInt16 { - return nil, fmt.Errorf("%d is less than minimum value for int2", n.Int64) - } - - return pgio.AppendInt16(buf, int16(n.Int64)), nil -} - -type encodePlanInt2CodecTextInt64Valuer struct{} - -func (encodePlanInt2CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if n.Int64 > math.MaxInt16 { - return nil, fmt.Errorf("%d is greater than maximum value for int2", n.Int64) - } - if n.Int64 < math.MinInt16 { - return nil, fmt.Errorf("%d is less than minimum value for int2", n.Int64) - } - - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil -} - -func (Int2Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *int8: - return scanPlanBinaryInt2ToInt8{} - case *int16: - return scanPlanBinaryInt2ToInt16{} - case *int32: - return scanPlanBinaryInt2ToInt32{} - case *int64: - return scanPlanBinaryInt2ToInt64{} - case *int: - return scanPlanBinaryInt2ToInt{} - case *uint8: - return scanPlanBinaryInt2ToUint8{} - case *uint16: - return scanPlanBinaryInt2ToUint16{} - case *uint32: - return scanPlanBinaryInt2ToUint32{} - case *uint64: - return scanPlanBinaryInt2ToUint64{} - case *uint: - return scanPlanBinaryInt2ToUint{} - case Int64Scanner: - return scanPlanBinaryInt2ToInt64Scanner{} - case TextScanner: - return scanPlanBinaryInt2ToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *int8: - return scanPlanTextAnyToInt8{} - case *int16: - return scanPlanTextAnyToInt16{} - case *int32: - return scanPlanTextAnyToInt32{} - case *int64: - return scanPlanTextAnyToInt64{} - case *int: - return scanPlanTextAnyToInt{} - case *uint8: - return scanPlanTextAnyToUint8{} - case *uint16: - return scanPlanTextAnyToUint16{} - case *uint32: - return scanPlanTextAnyToUint32{} - case *uint64: - return scanPlanTextAnyToUint64{} - case *uint: - return scanPlanTextAnyToUint{} - case Int64Scanner: - return scanPlanTextAnyToInt64Scanner{} - } - } - - return nil -} - -func (c Int2Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var n int64 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -func (c Int2Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n int16 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -type scanPlanBinaryInt2ToInt8 struct{} - -func (scanPlanBinaryInt2ToInt8) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) - } - - p, ok := (dst).(*int8) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int16(binary.BigEndian.Uint16(src)) - if n < math.MinInt8 { - return fmt.Errorf("%d is less than minimum value for int8", n) - } else if n > math.MaxInt8 { - return fmt.Errorf("%d is greater than maximum value for int8", n) - } - - *p = int8(n) - - return nil -} - -type scanPlanBinaryInt2ToUint8 struct{} - -func (scanPlanBinaryInt2ToUint8) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) - } - - p, ok := (dst).(*uint8) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int16(binary.BigEndian.Uint16(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint8", n) - } - - if n > math.MaxUint8 { - return fmt.Errorf("%d is greater than maximum value for uint8", n) - } - - *p = uint8(n) - - return nil -} - -type scanPlanBinaryInt2ToInt16 struct{} - -func (scanPlanBinaryInt2ToInt16) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) - } - - p, ok := (dst).(*int16) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = int16(binary.BigEndian.Uint16(src)) - - return nil -} - -type scanPlanBinaryInt2ToUint16 struct{} - -func (scanPlanBinaryInt2ToUint16) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) - } - - p, ok := (dst).(*uint16) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int16(binary.BigEndian.Uint16(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint16", n) - } - - *p = uint16(n) - - return nil -} - -type scanPlanBinaryInt2ToInt32 struct{} - -func (scanPlanBinaryInt2ToInt32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) - } - - p, ok := (dst).(*int32) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = int32(int16(binary.BigEndian.Uint16(src))) - - return nil -} - -type scanPlanBinaryInt2ToUint32 struct{} - -func (scanPlanBinaryInt2ToUint32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) - } - - p, ok := (dst).(*uint32) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int16(binary.BigEndian.Uint16(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint32", n) - } - - *p = uint32(n) - - return nil -} - -type scanPlanBinaryInt2ToInt64 struct{} - -func (scanPlanBinaryInt2ToInt64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) - } - - p, ok := (dst).(*int64) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = int64(int16(binary.BigEndian.Uint16(src))) - - return nil -} - -type scanPlanBinaryInt2ToUint64 struct{} - -func (scanPlanBinaryInt2ToUint64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) - } - - p, ok := (dst).(*uint64) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int16(binary.BigEndian.Uint16(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint64", n) - } - - *p = uint64(n) - - return nil -} - -type scanPlanBinaryInt2ToInt struct{} - -func (scanPlanBinaryInt2ToInt) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) - } - - p, ok := (dst).(*int) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = int(int16(binary.BigEndian.Uint16(src))) - - return nil -} - -type scanPlanBinaryInt2ToUint struct{} - -func (scanPlanBinaryInt2ToUint) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for uint2: %v", len(src)) - } - - p, ok := (dst).(*uint) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(int16(binary.BigEndian.Uint16(src))) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint", n) - } - - *p = uint(n) - - return nil -} - -type scanPlanBinaryInt2ToInt64Scanner struct{} - -func (scanPlanBinaryInt2ToInt64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Int64Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanInt64(Int8{}) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) - } - - n := int64(int16(binary.BigEndian.Uint16(src))) - - return s.ScanInt64(Int8{Int64: n, Valid: true}) -} - -type scanPlanBinaryInt2ToTextScanner struct{} - -func (scanPlanBinaryInt2ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanText(Text{}) - } - - if len(src) != 2 { - return fmt.Errorf("invalid length for int2: %v", len(src)) - } - - n := int64(int16(binary.BigEndian.Uint16(src))) - - return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) -} - -type Int4 struct { - Int32 int32 - Valid bool -} - -// ScanInt64 implements the Int64Scanner interface. -func (dst *Int4) ScanInt64(n Int8) error { - if !n.Valid { - *dst = Int4{} - return nil - } - - if n.Int64 < math.MinInt32 { - return fmt.Errorf("%d is less than minimum value for Int4", n.Int64) - } - if n.Int64 > math.MaxInt32 { - return fmt.Errorf("%d is greater than maximum value for Int4", n.Int64) - } - *dst = Int4{Int32: int32(n.Int64), Valid: true} - - return nil -} - -func (n Int4) Int64Value() (Int8, error) { - return Int8{Int64: int64(n.Int32), Valid: n.Valid}, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Int4) Scan(src any) error { - if src == nil { - *dst = Int4{} - return nil - } - - var n int64 - - switch src := src.(type) { - case int64: - n = src - case string: - var err error - n, err = strconv.ParseInt(src, 10, 32) - if err != nil { - return err - } - case []byte: - var err error - n, err = strconv.ParseInt(string(src), 10, 32) - if err != nil { - return err - } - default: - return fmt.Errorf("cannot scan %T", src) - } - - if n < math.MinInt32 { - return fmt.Errorf("%d is greater than maximum value for Int4", n) - } - if n > math.MaxInt32 { - return fmt.Errorf("%d is greater than maximum value for Int4", n) - } - *dst = Int4{Int32: int32(n), Valid: true} - - return nil -} - -// Value implements the database/sql/driver Valuer interface. -func (src Int4) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - return int64(src.Int32), nil -} - -func (src Int4) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - return []byte(strconv.FormatInt(int64(src.Int32), 10)), nil -} - -func (dst *Int4) UnmarshalJSON(b []byte) error { - var n *int32 - err := json.Unmarshal(b, &n) - if err != nil { - return err - } - - if n == nil { - *dst = Int4{} - } else { - *dst = Int4{Int32: *n, Valid: true} - } - - return nil -} - -type Int4Codec struct{} - -func (Int4Codec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (Int4Codec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (Int4Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case int32: - return encodePlanInt4CodecBinaryInt32{} - case Int64Valuer: - return encodePlanInt4CodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case int32: - return encodePlanInt4CodecTextInt32{} - case Int64Valuer: - return encodePlanInt4CodecTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanInt4CodecBinaryInt32 struct{} - -func (encodePlanInt4CodecBinaryInt32) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(int32) - return pgio.AppendInt32(buf, int32(n)), nil -} - -type encodePlanInt4CodecTextInt32 struct{} - -func (encodePlanInt4CodecTextInt32) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(int32) - return append(buf, strconv.FormatInt(int64(n), 10)...), nil -} - -type encodePlanInt4CodecBinaryInt64Valuer struct{} - -func (encodePlanInt4CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if n.Int64 > math.MaxInt32 { - return nil, fmt.Errorf("%d is greater than maximum value for int4", n.Int64) - } - if n.Int64 < math.MinInt32 { - return nil, fmt.Errorf("%d is less than minimum value for int4", n.Int64) - } - - return pgio.AppendInt32(buf, int32(n.Int64)), nil -} - -type encodePlanInt4CodecTextInt64Valuer struct{} - -func (encodePlanInt4CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if n.Int64 > math.MaxInt32 { - return nil, fmt.Errorf("%d is greater than maximum value for int4", n.Int64) - } - if n.Int64 < math.MinInt32 { - return nil, fmt.Errorf("%d is less than minimum value for int4", n.Int64) - } - - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil -} - -func (Int4Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *int8: - return scanPlanBinaryInt4ToInt8{} - case *int16: - return scanPlanBinaryInt4ToInt16{} - case *int32: - return scanPlanBinaryInt4ToInt32{} - case *int64: - return scanPlanBinaryInt4ToInt64{} - case *int: - return scanPlanBinaryInt4ToInt{} - case *uint8: - return scanPlanBinaryInt4ToUint8{} - case *uint16: - return scanPlanBinaryInt4ToUint16{} - case *uint32: - return scanPlanBinaryInt4ToUint32{} - case *uint64: - return scanPlanBinaryInt4ToUint64{} - case *uint: - return scanPlanBinaryInt4ToUint{} - case Int64Scanner: - return scanPlanBinaryInt4ToInt64Scanner{} - case TextScanner: - return scanPlanBinaryInt4ToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *int8: - return scanPlanTextAnyToInt8{} - case *int16: - return scanPlanTextAnyToInt16{} - case *int32: - return scanPlanTextAnyToInt32{} - case *int64: - return scanPlanTextAnyToInt64{} - case *int: - return scanPlanTextAnyToInt{} - case *uint8: - return scanPlanTextAnyToUint8{} - case *uint16: - return scanPlanTextAnyToUint16{} - case *uint32: - return scanPlanTextAnyToUint32{} - case *uint64: - return scanPlanTextAnyToUint64{} - case *uint: - return scanPlanTextAnyToUint{} - case Int64Scanner: - return scanPlanTextAnyToInt64Scanner{} - } - } - - return nil -} - -func (c Int4Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var n int64 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -func (c Int4Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n int32 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -type scanPlanBinaryInt4ToInt8 struct{} - -func (scanPlanBinaryInt4ToInt8) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) - } - - p, ok := (dst).(*int8) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int32(binary.BigEndian.Uint32(src)) - if n < math.MinInt8 { - return fmt.Errorf("%d is less than minimum value for int8", n) - } else if n > math.MaxInt8 { - return fmt.Errorf("%d is greater than maximum value for int8", n) - } - - *p = int8(n) - - return nil -} - -type scanPlanBinaryInt4ToUint8 struct{} - -func (scanPlanBinaryInt4ToUint8) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) - } - - p, ok := (dst).(*uint8) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int32(binary.BigEndian.Uint32(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint8", n) - } - - if n > math.MaxUint8 { - return fmt.Errorf("%d is greater than maximum value for uint8", n) - } - - *p = uint8(n) - - return nil -} - -type scanPlanBinaryInt4ToInt16 struct{} - -func (scanPlanBinaryInt4ToInt16) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) - } - - p, ok := (dst).(*int16) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int32(binary.BigEndian.Uint32(src)) - if n < math.MinInt16 { - return fmt.Errorf("%d is less than minimum value for int16", n) - } else if n > math.MaxInt16 { - return fmt.Errorf("%d is greater than maximum value for int16", n) - } - - *p = int16(n) - - return nil -} - -type scanPlanBinaryInt4ToUint16 struct{} - -func (scanPlanBinaryInt4ToUint16) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) - } - - p, ok := (dst).(*uint16) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int32(binary.BigEndian.Uint32(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint16", n) - } - - if n > math.MaxUint16 { - return fmt.Errorf("%d is greater than maximum value for uint16", n) - } - - *p = uint16(n) - - return nil -} - -type scanPlanBinaryInt4ToInt32 struct{} - -func (scanPlanBinaryInt4ToInt32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) - } - - p, ok := (dst).(*int32) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = int32(binary.BigEndian.Uint32(src)) - - return nil -} - -type scanPlanBinaryInt4ToUint32 struct{} - -func (scanPlanBinaryInt4ToUint32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) - } - - p, ok := (dst).(*uint32) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int32(binary.BigEndian.Uint32(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint32", n) - } - - *p = uint32(n) - - return nil -} - -type scanPlanBinaryInt4ToInt64 struct{} - -func (scanPlanBinaryInt4ToInt64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) - } - - p, ok := (dst).(*int64) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = int64(int32(binary.BigEndian.Uint32(src))) - - return nil -} - -type scanPlanBinaryInt4ToUint64 struct{} - -func (scanPlanBinaryInt4ToUint64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) - } - - p, ok := (dst).(*uint64) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int32(binary.BigEndian.Uint32(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint64", n) - } - - *p = uint64(n) - - return nil -} - -type scanPlanBinaryInt4ToInt struct{} - -func (scanPlanBinaryInt4ToInt) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) - } - - p, ok := (dst).(*int) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = int(int32(binary.BigEndian.Uint32(src))) - - return nil -} - -type scanPlanBinaryInt4ToUint struct{} - -func (scanPlanBinaryInt4ToUint) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for uint4: %v", len(src)) - } - - p, ok := (dst).(*uint) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(int32(binary.BigEndian.Uint32(src))) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint", n) - } - - *p = uint(n) - - return nil -} - -type scanPlanBinaryInt4ToInt64Scanner struct{} - -func (scanPlanBinaryInt4ToInt64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Int64Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanInt64(Int8{}) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) - } - - n := int64(int32(binary.BigEndian.Uint32(src))) - - return s.ScanInt64(Int8{Int64: n, Valid: true}) -} - -type scanPlanBinaryInt4ToTextScanner struct{} - -func (scanPlanBinaryInt4ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanText(Text{}) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for int4: %v", len(src)) - } - - n := int64(int32(binary.BigEndian.Uint32(src))) - - return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) -} - -type Int8 struct { - Int64 int64 - Valid bool -} - -// ScanInt64 implements the Int64Scanner interface. -func (dst *Int8) ScanInt64(n Int8) error { - if !n.Valid { - *dst = Int8{} - return nil - } - - if n.Int64 < math.MinInt64 { - return fmt.Errorf("%d is less than minimum value for Int8", n.Int64) - } - if n.Int64 > math.MaxInt64 { - return fmt.Errorf("%d is greater than maximum value for Int8", n.Int64) - } - *dst = Int8{Int64: int64(n.Int64), Valid: true} - - return nil -} - -func (n Int8) Int64Value() (Int8, error) { - return Int8{Int64: int64(n.Int64), Valid: n.Valid}, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Int8) Scan(src any) error { - if src == nil { - *dst = Int8{} - return nil - } - - var n int64 - - switch src := src.(type) { - case int64: - n = src - case string: - var err error - n, err = strconv.ParseInt(src, 10, 64) - if err != nil { - return err - } - case []byte: - var err error - n, err = strconv.ParseInt(string(src), 10, 64) - if err != nil { - return err - } - default: - return fmt.Errorf("cannot scan %T", src) - } - - if n < math.MinInt64 { - return fmt.Errorf("%d is greater than maximum value for Int8", n) - } - if n > math.MaxInt64 { - return fmt.Errorf("%d is greater than maximum value for Int8", n) - } - *dst = Int8{Int64: int64(n), Valid: true} - - return nil -} - -// Value implements the database/sql/driver Valuer interface. -func (src Int8) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - return int64(src.Int64), nil -} - -func (src Int8) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - return []byte(strconv.FormatInt(int64(src.Int64), 10)), nil -} - -func (dst *Int8) UnmarshalJSON(b []byte) error { - var n *int64 - err := json.Unmarshal(b, &n) - if err != nil { - return err - } - - if n == nil { - *dst = Int8{} - } else { - *dst = Int8{Int64: *n, Valid: true} - } - - return nil -} - -type Int8Codec struct{} - -func (Int8Codec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (Int8Codec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (Int8Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case int64: - return encodePlanInt8CodecBinaryInt64{} - case Int64Valuer: - return encodePlanInt8CodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case int64: - return encodePlanInt8CodecTextInt64{} - case Int64Valuer: - return encodePlanInt8CodecTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanInt8CodecBinaryInt64 struct{} - -func (encodePlanInt8CodecBinaryInt64) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(int64) - return pgio.AppendInt64(buf, int64(n)), nil -} - -type encodePlanInt8CodecTextInt64 struct{} - -func (encodePlanInt8CodecTextInt64) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(int64) - return append(buf, strconv.FormatInt(int64(n), 10)...), nil -} - -type encodePlanInt8CodecBinaryInt64Valuer struct{} - -func (encodePlanInt8CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if n.Int64 > math.MaxInt64 { - return nil, fmt.Errorf("%d is greater than maximum value for int8", n.Int64) - } - if n.Int64 < math.MinInt64 { - return nil, fmt.Errorf("%d is less than minimum value for int8", n.Int64) - } - - return pgio.AppendInt64(buf, int64(n.Int64)), nil -} - -type encodePlanInt8CodecTextInt64Valuer struct{} - -func (encodePlanInt8CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if n.Int64 > math.MaxInt64 { - return nil, fmt.Errorf("%d is greater than maximum value for int8", n.Int64) - } - if n.Int64 < math.MinInt64 { - return nil, fmt.Errorf("%d is less than minimum value for int8", n.Int64) - } - - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil -} - -func (Int8Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *int8: - return scanPlanBinaryInt8ToInt8{} - case *int16: - return scanPlanBinaryInt8ToInt16{} - case *int32: - return scanPlanBinaryInt8ToInt32{} - case *int64: - return scanPlanBinaryInt8ToInt64{} - case *int: - return scanPlanBinaryInt8ToInt{} - case *uint8: - return scanPlanBinaryInt8ToUint8{} - case *uint16: - return scanPlanBinaryInt8ToUint16{} - case *uint32: - return scanPlanBinaryInt8ToUint32{} - case *uint64: - return scanPlanBinaryInt8ToUint64{} - case *uint: - return scanPlanBinaryInt8ToUint{} - case Int64Scanner: - return scanPlanBinaryInt8ToInt64Scanner{} - case TextScanner: - return scanPlanBinaryInt8ToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *int8: - return scanPlanTextAnyToInt8{} - case *int16: - return scanPlanTextAnyToInt16{} - case *int32: - return scanPlanTextAnyToInt32{} - case *int64: - return scanPlanTextAnyToInt64{} - case *int: - return scanPlanTextAnyToInt{} - case *uint8: - return scanPlanTextAnyToUint8{} - case *uint16: - return scanPlanTextAnyToUint16{} - case *uint32: - return scanPlanTextAnyToUint32{} - case *uint64: - return scanPlanTextAnyToUint64{} - case *uint: - return scanPlanTextAnyToUint{} - case Int64Scanner: - return scanPlanTextAnyToInt64Scanner{} - } - } - - return nil -} - -func (c Int8Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var n int64 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -func (c Int8Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n int64 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -type scanPlanBinaryInt8ToInt8 struct{} - -func (scanPlanBinaryInt8ToInt8) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) - } - - p, ok := (dst).(*int8) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(binary.BigEndian.Uint64(src)) - if n < math.MinInt8 { - return fmt.Errorf("%d is less than minimum value for int8", n) - } else if n > math.MaxInt8 { - return fmt.Errorf("%d is greater than maximum value for int8", n) - } - - *p = int8(n) - - return nil -} - -type scanPlanBinaryInt8ToUint8 struct{} - -func (scanPlanBinaryInt8ToUint8) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) - } - - p, ok := (dst).(*uint8) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(binary.BigEndian.Uint64(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint8", n) - } - - if n > math.MaxUint8 { - return fmt.Errorf("%d is greater than maximum value for uint8", n) - } - - *p = uint8(n) - - return nil -} - -type scanPlanBinaryInt8ToInt16 struct{} - -func (scanPlanBinaryInt8ToInt16) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) - } - - p, ok := (dst).(*int16) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(binary.BigEndian.Uint64(src)) - if n < math.MinInt16 { - return fmt.Errorf("%d is less than minimum value for int16", n) - } else if n > math.MaxInt16 { - return fmt.Errorf("%d is greater than maximum value for int16", n) - } - - *p = int16(n) - - return nil -} - -type scanPlanBinaryInt8ToUint16 struct{} - -func (scanPlanBinaryInt8ToUint16) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) - } - - p, ok := (dst).(*uint16) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(binary.BigEndian.Uint64(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint16", n) - } - - if n > math.MaxUint16 { - return fmt.Errorf("%d is greater than maximum value for uint16", n) - } - - *p = uint16(n) - - return nil -} - -type scanPlanBinaryInt8ToInt32 struct{} - -func (scanPlanBinaryInt8ToInt32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) - } - - p, ok := (dst).(*int32) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(binary.BigEndian.Uint64(src)) - if n < math.MinInt32 { - return fmt.Errorf("%d is less than minimum value for int32", n) - } else if n > math.MaxInt32 { - return fmt.Errorf("%d is greater than maximum value for int32", n) - } - - *p = int32(n) - - return nil -} - -type scanPlanBinaryInt8ToUint32 struct{} - -func (scanPlanBinaryInt8ToUint32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) - } - - p, ok := (dst).(*uint32) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(binary.BigEndian.Uint64(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint32", n) - } - - if n > math.MaxUint32 { - return fmt.Errorf("%d is greater than maximum value for uint32", n) - } - - *p = uint32(n) - - return nil -} - -type scanPlanBinaryInt8ToInt64 struct{} - -func (scanPlanBinaryInt8ToInt64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) - } - - p, ok := (dst).(*int64) - if !ok { - return ErrScanTargetTypeChanged - } - - *p = int64(binary.BigEndian.Uint64(src)) - - return nil -} - -type scanPlanBinaryInt8ToUint64 struct{} - -func (scanPlanBinaryInt8ToUint64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) - } - - p, ok := (dst).(*uint64) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(binary.BigEndian.Uint64(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint64", n) - } - - *p = uint64(n) - - return nil -} - -type scanPlanBinaryInt8ToInt struct{} - -func (scanPlanBinaryInt8ToInt) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) - } - - p, ok := (dst).(*int) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(binary.BigEndian.Uint64(src)) - if n < math.MinInt { - return fmt.Errorf("%d is less than minimum value for int", n) - } else if n > math.MaxInt { - return fmt.Errorf("%d is greater than maximum value for int", n) - } - - *p = int(n) - - return nil -} - -type scanPlanBinaryInt8ToUint struct{} - -func (scanPlanBinaryInt8ToUint) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for uint8: %v", len(src)) - } - - p, ok := (dst).(*uint) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(int64(binary.BigEndian.Uint64(src))) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint", n) - } - - if uint64(n) > math.MaxUint { - return fmt.Errorf("%d is greater than maximum value for uint", n) - } - - *p = uint(n) - - return nil -} - -type scanPlanBinaryInt8ToInt64Scanner struct{} - -func (scanPlanBinaryInt8ToInt64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Int64Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanInt64(Int8{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) - } - - n := int64(int64(binary.BigEndian.Uint64(src))) - - return s.ScanInt64(Int8{Int64: n, Valid: true}) -} - -type scanPlanBinaryInt8ToTextScanner struct{} - -func (scanPlanBinaryInt8ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanText(Text{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for int8: %v", len(src)) - } - - n := int64(int64(binary.BigEndian.Uint64(src))) - - return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) -} - -type scanPlanTextAnyToInt8 struct{} - -func (scanPlanTextAnyToInt8) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*int8) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseInt(string(src), 10, 8) - if err != nil { - return err - } - - *p = int8(n) - return nil -} - -type scanPlanTextAnyToUint8 struct{} - -func (scanPlanTextAnyToUint8) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*uint8) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseUint(string(src), 10, 8) - if err != nil { - return err - } - - *p = uint8(n) - return nil -} - -type scanPlanTextAnyToInt16 struct{} - -func (scanPlanTextAnyToInt16) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*int16) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseInt(string(src), 10, 16) - if err != nil { - return err - } - - *p = int16(n) - return nil -} - -type scanPlanTextAnyToUint16 struct{} - -func (scanPlanTextAnyToUint16) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*uint16) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseUint(string(src), 10, 16) - if err != nil { - return err - } - - *p = uint16(n) - return nil -} - -type scanPlanTextAnyToInt32 struct{} - -func (scanPlanTextAnyToInt32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*int32) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseInt(string(src), 10, 32) - if err != nil { - return err - } - - *p = int32(n) - return nil -} - -type scanPlanTextAnyToUint32 struct{} - -func (scanPlanTextAnyToUint32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*uint32) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseUint(string(src), 10, 32) - if err != nil { - return err - } - - *p = uint32(n) - return nil -} - -type scanPlanTextAnyToInt64 struct{} - -func (scanPlanTextAnyToInt64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*int64) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseInt(string(src), 10, 64) - if err != nil { - return err - } - - *p = int64(n) - return nil -} - -type scanPlanTextAnyToUint64 struct{} - -func (scanPlanTextAnyToUint64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*uint64) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseUint(string(src), 10, 64) - if err != nil { - return err - } - - *p = uint64(n) - return nil -} - -type scanPlanTextAnyToInt struct{} - -func (scanPlanTextAnyToInt) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*int) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseInt(string(src), 10, 0) - if err != nil { - return err - } - - *p = int(n) - return nil -} - -type scanPlanTextAnyToUint struct{} - -func (scanPlanTextAnyToUint) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*uint) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseUint(string(src), 10, 0) - if err != nil { - return err - } - - *p = uint(n) - return nil -} - -type scanPlanTextAnyToInt64Scanner struct{} - -func (scanPlanTextAnyToInt64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Int64Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanInt64(Int8{}) - } - - n, err := strconv.ParseInt(string(src), 10, 64) - if err != nil { - return err - } - - err = s.ScanInt64(Int8{Int64: n, Valid: true}) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb b/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb deleted file mode 100644 index e0c8b7a3f..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb +++ /dev/null @@ -1,548 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "encoding/json" - "fmt" - "math" - "strconv" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Int64Scanner interface { - ScanInt64(Int8) error -} - -type Int64Valuer interface { - Int64Value() (Int8, error) -} - - -<% [2, 4, 8].each do |pg_byte_size| %> -<% pg_bit_size = pg_byte_size * 8 %> -type Int<%= pg_byte_size %> struct { - Int<%= pg_bit_size %> int<%= pg_bit_size %> - Valid bool -} - -// ScanInt64 implements the Int64Scanner interface. -func (dst *Int<%= pg_byte_size %>) ScanInt64(n Int8) error { - if !n.Valid { - *dst = Int<%= pg_byte_size %>{} - return nil - } - - if n.Int64 < math.MinInt<%= pg_bit_size %> { - return fmt.Errorf("%d is less than minimum value for Int<%= pg_byte_size %>", n.Int64) - } - if n.Int64 > math.MaxInt<%= pg_bit_size %> { - return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n.Int64) - } - *dst = Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: int<%= pg_bit_size %>(n.Int64), Valid: true} - - return nil -} - -func (n Int<%= pg_byte_size %>) Int64Value() (Int8, error) { - return Int8{Int64: int64(n.Int<%= pg_bit_size %>), Valid: n.Valid}, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Int<%= pg_byte_size %>) Scan(src any) error { - if src == nil { - *dst = Int<%= pg_byte_size %>{} - return nil - } - - var n int64 - - switch src := src.(type) { - case int64: - n = src - case string: - var err error - n, err = strconv.ParseInt(src, 10, <%= pg_bit_size %>) - if err != nil { - return err - } - case []byte: - var err error - n, err = strconv.ParseInt(string(src), 10, <%= pg_bit_size %>) - if err != nil { - return err - } - default: - return fmt.Errorf("cannot scan %T", src) - } - - if n < math.MinInt<%= pg_bit_size %> { - return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n) - } - if n > math.MaxInt<%= pg_bit_size %> { - return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n) - } - *dst = Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: int<%= pg_bit_size %>(n), Valid: true} - - return nil -} - -// Value implements the database/sql/driver Valuer interface. -func (src Int<%= pg_byte_size %>) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - return int64(src.Int<%= pg_bit_size %>), nil -} - -func (src Int<%= pg_byte_size %>) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - return []byte(strconv.FormatInt(int64(src.Int<%= pg_bit_size %>), 10)), nil -} - -func (dst *Int<%= pg_byte_size %>) UnmarshalJSON(b []byte) error { - var n *int<%= pg_bit_size %> - err := json.Unmarshal(b, &n) - if err != nil { - return err - } - - if n == nil { - *dst = Int<%= pg_byte_size %>{} - } else { - *dst = Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: *n, Valid: true} - } - - return nil -} - -type Int<%= pg_byte_size %>Codec struct{} - -func (Int<%= pg_byte_size %>Codec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (Int<%= pg_byte_size %>Codec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (Int<%= pg_byte_size %>Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case int<%= pg_bit_size %>: - return encodePlanInt<%= pg_byte_size %>CodecBinaryInt<%= pg_bit_size %>{} - case Int64Valuer: - return encodePlanInt<%= pg_byte_size %>CodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case int<%= pg_bit_size %>: - return encodePlanInt<%= pg_byte_size %>CodecTextInt<%= pg_bit_size %>{} - case Int64Valuer: - return encodePlanInt<%= pg_byte_size %>CodecTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanInt<%= pg_byte_size %>CodecBinaryInt<%= pg_bit_size %> struct{} - -func (encodePlanInt<%= pg_byte_size %>CodecBinaryInt<%= pg_bit_size %>) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(int<%= pg_bit_size %>) - return pgio.AppendInt<%= pg_bit_size %>(buf, int<%= pg_bit_size %>(n)), nil -} - -type encodePlanInt<%= pg_byte_size %>CodecTextInt<%= pg_bit_size %> struct{} - -func (encodePlanInt<%= pg_byte_size %>CodecTextInt<%= pg_bit_size %>) Encode(value any, buf []byte) (newBuf []byte, err error) { - n := value.(int<%= pg_bit_size %>) - return append(buf, strconv.FormatInt(int64(n), 10)...), nil -} - -type encodePlanInt<%= pg_byte_size %>CodecBinaryInt64Valuer struct{} - -func (encodePlanInt<%= pg_byte_size %>CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if n.Int64 > math.MaxInt<%= pg_bit_size %> { - return nil, fmt.Errorf("%d is greater than maximum value for int<%= pg_byte_size %>", n.Int64) - } - if n.Int64 < math.MinInt<%= pg_bit_size %> { - return nil, fmt.Errorf("%d is less than minimum value for int<%= pg_byte_size %>", n.Int64) - } - - return pgio.AppendInt<%= pg_bit_size %>(buf, int<%= pg_bit_size %>(n.Int64)), nil -} - -type encodePlanInt<%= pg_byte_size %>CodecTextInt64Valuer struct{} - -func (encodePlanInt<%= pg_byte_size %>CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if n.Int64 > math.MaxInt<%= pg_bit_size %> { - return nil, fmt.Errorf("%d is greater than maximum value for int<%= pg_byte_size %>", n.Int64) - } - if n.Int64 < math.MinInt<%= pg_bit_size %> { - return nil, fmt.Errorf("%d is less than minimum value for int<%= pg_byte_size %>", n.Int64) - } - - return append(buf, strconv.FormatInt(n.Int64, 10)...), nil -} - -func (Int<%= pg_byte_size %>Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *int8: - return scanPlanBinaryInt<%= pg_byte_size %>ToInt8{} - case *int16: - return scanPlanBinaryInt<%= pg_byte_size %>ToInt16{} - case *int32: - return scanPlanBinaryInt<%= pg_byte_size %>ToInt32{} - case *int64: - return scanPlanBinaryInt<%= pg_byte_size %>ToInt64{} - case *int: - return scanPlanBinaryInt<%= pg_byte_size %>ToInt{} - case *uint8: - return scanPlanBinaryInt<%= pg_byte_size %>ToUint8{} - case *uint16: - return scanPlanBinaryInt<%= pg_byte_size %>ToUint16{} - case *uint32: - return scanPlanBinaryInt<%= pg_byte_size %>ToUint32{} - case *uint64: - return scanPlanBinaryInt<%= pg_byte_size %>ToUint64{} - case *uint: - return scanPlanBinaryInt<%= pg_byte_size %>ToUint{} - case Int64Scanner: - return scanPlanBinaryInt<%= pg_byte_size %>ToInt64Scanner{} - case TextScanner: - return scanPlanBinaryInt<%= pg_byte_size %>ToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *int8: - return scanPlanTextAnyToInt8{} - case *int16: - return scanPlanTextAnyToInt16{} - case *int32: - return scanPlanTextAnyToInt32{} - case *int64: - return scanPlanTextAnyToInt64{} - case *int: - return scanPlanTextAnyToInt{} - case *uint8: - return scanPlanTextAnyToUint8{} - case *uint16: - return scanPlanTextAnyToUint16{} - case *uint32: - return scanPlanTextAnyToUint32{} - case *uint64: - return scanPlanTextAnyToUint64{} - case *uint: - return scanPlanTextAnyToUint{} - case Int64Scanner: - return scanPlanTextAnyToInt64Scanner{} - } - } - - return nil -} - -func (c Int<%= pg_byte_size %>Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var n int64 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -func (c Int<%= pg_byte_size %>Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n int<%= pg_bit_size %> - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -<%# PostgreSQL binary format integer to fixed size Go integers %> -<% [8, 16, 32, 64].each do |dst_bit_size| %> -type scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %> struct{} - -func (scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %>) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) - } - - p, ok := (dst).(*int<%= dst_bit_size %>) - if !ok { - return ErrScanTargetTypeChanged - } - - <% if dst_bit_size < pg_bit_size %> - n := int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) - if n < math.MinInt<%= dst_bit_size %> { - return fmt.Errorf("%d is less than minimum value for int<%= dst_bit_size %>", n) - } else if n > math.MaxInt<%= dst_bit_size %> { - return fmt.Errorf("%d is greater than maximum value for int<%= dst_bit_size %>", n) - } - - *p = int<%= dst_bit_size %>(n) - <% elsif dst_bit_size == pg_bit_size %> - *p = int<%= dst_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) - <% else %> - *p = int<%= dst_bit_size %>(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) - <% end %> - - return nil -} - -type scanPlanBinaryInt<%= pg_byte_size %>ToUint<%= dst_bit_size %> struct{} - -func (scanPlanBinaryInt<%= pg_byte_size %>ToUint<%= dst_bit_size %>) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for uint<%= pg_byte_size %>: %v", len(src)) - } - - p, ok := (dst).(*uint<%= dst_bit_size %>) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint<%= dst_bit_size %>", n) - } - <% if dst_bit_size < pg_bit_size %> - if n > math.MaxUint<%= dst_bit_size %> { - return fmt.Errorf("%d is greater than maximum value for uint<%= dst_bit_size %>", n) - } - <% end %> - *p = uint<%= dst_bit_size %>(n) - - return nil -} -<% end %> - -<%# PostgreSQL binary format integer to Go machine integers %> -type scanPlanBinaryInt<%= pg_byte_size %>ToInt struct{} - -func (scanPlanBinaryInt<%= pg_byte_size %>ToInt) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) - } - - p, ok := (dst).(*int) - if !ok { - return ErrScanTargetTypeChanged - } - - <% if 32 < pg_bit_size %> - n := int64(binary.BigEndian.Uint<%= pg_bit_size %>(src)) - if n < math.MinInt { - return fmt.Errorf("%d is less than minimum value for int", n) - } else if n > math.MaxInt { - return fmt.Errorf("%d is greater than maximum value for int", n) - } - - *p = int(n) - <% else %> - *p = int(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) - <% end %> - - return nil -} - -type scanPlanBinaryInt<%= pg_byte_size %>ToUint struct{} - -func (scanPlanBinaryInt<%= pg_byte_size %>ToUint) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for uint<%= pg_byte_size %>: %v", len(src)) - } - - p, ok := (dst).(*uint) - if !ok { - return ErrScanTargetTypeChanged - } - - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) - if n < 0 { - return fmt.Errorf("%d is less than minimum value for uint", n) - } - <% if 32 < pg_bit_size %> - if uint64(n) > math.MaxUint { - return fmt.Errorf("%d is greater than maximum value for uint", n) - } - <% end %> - *p = uint(n) - - return nil -} - -<%# PostgreSQL binary format integer to Go Int64Scanner %> -type scanPlanBinaryInt<%= pg_byte_size %>ToInt64Scanner struct{} - -func (scanPlanBinaryInt<%= pg_byte_size %>ToInt64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Int64Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanInt64(Int8{}) - } - - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) - } - - - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) - - return s.ScanInt64(Int8{Int64: n, Valid: true}) -} - -<%# PostgreSQL binary format integer to Go TextScanner %> -type scanPlanBinaryInt<%= pg_byte_size %>ToTextScanner struct{} - -func (scanPlanBinaryInt<%= pg_byte_size %>ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanText(Text{}) - } - - if len(src) != <%= pg_byte_size %> { - return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) - } - - - n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) - - return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) -} -<% end %> - -<%# Any text to all integer types %> -<% [ - ["8", 8], - ["16", 16], - ["32", 32], - ["64", 64], - ["", 0] -].each do |type_suffix, bit_size| %> -type scanPlanTextAnyToInt<%= type_suffix %> struct{} - -func (scanPlanTextAnyToInt<%= type_suffix %>) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*int<%= type_suffix %>) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseInt(string(src), 10, <%= bit_size %>) - if err != nil { - return err - } - - *p = int<%= type_suffix %>(n) - return nil -} - -type scanPlanTextAnyToUint<%= type_suffix %> struct{} - -func (scanPlanTextAnyToUint<%= type_suffix %>) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p, ok := (dst).(*uint<%= type_suffix %>) - if !ok { - return ErrScanTargetTypeChanged - } - - n, err := strconv.ParseUint(string(src), 10, <%= bit_size %>) - if err != nil { - return err - } - - *p = uint<%= type_suffix %>(n) - return nil -} -<% end %> - -type scanPlanTextAnyToInt64Scanner struct{} - -func (scanPlanTextAnyToInt64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Int64Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanInt64(Int8{}) - } - - n, err := strconv.ParseInt(string(src), 10, 64) - if err != nil { - return err - } - - err = s.ScanInt64(Int8{Int64: n, Valid: true}) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int_test.go.erb b/vendor/github.com/jackc/pgx/v5/pgtype/int_test.go.erb deleted file mode 100644 index ac9a3f143..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/int_test.go.erb +++ /dev/null @@ -1,93 +0,0 @@ -package pgtype_test - -import ( - "math" - "testing" - - "github.com/jackc/pgx/v5/pgtype" -) - -<% [2, 4, 8].each do |pg_byte_size| %> -<% pg_bit_size = pg_byte_size * 8 %> -func TestInt<%= pg_byte_size %>Codec(t *testing.T) { - pgxtest.RunValueRoundTripTests(context.Background(), t, defaultConnTestRunner, nil, "int<%= pg_byte_size %>", []pgxtest.ValueRoundTripTest{ - {int8(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {int16(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {int32(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {int64(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {uint8(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {uint16(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {uint32(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {uint64(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {int(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {uint(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 1, Valid: true}, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {int32(-1), new(pgtype.Int<%= pg_byte_size %>), isExpectedEq(pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: -1, Valid: true})}, - {1, new(int8), isExpectedEq(int8(1))}, - {1, new(int16), isExpectedEq(int16(1))}, - {1, new(int32), isExpectedEq(int32(1))}, - {1, new(int64), isExpectedEq(int64(1))}, - {1, new(uint8), isExpectedEq(uint8(1))}, - {1, new(uint16), isExpectedEq(uint16(1))}, - {1, new(uint32), isExpectedEq(uint32(1))}, - {1, new(uint64), isExpectedEq(uint64(1))}, - {1, new(int), isExpectedEq(int(1))}, - {1, new(uint), isExpectedEq(uint(1))}, - {-1, new(int8), isExpectedEq(int8(-1))}, - {-1, new(int16), isExpectedEq(int16(-1))}, - {-1, new(int32), isExpectedEq(int32(-1))}, - {-1, new(int64), isExpectedEq(int64(-1))}, - {-1, new(int), isExpectedEq(int(-1))}, - {math.MinInt<%= pg_bit_size %>, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(math.MinInt<%= pg_bit_size %>))}, - {-1, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(-1))}, - {0, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(0))}, - {1, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, - {math.MaxInt<%= pg_bit_size %>, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(math.MaxInt<%= pg_bit_size %>))}, - {1, new(pgtype.Int<%= pg_byte_size %>), isExpectedEq(pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 1, Valid: true})}, - {"1", new(string), isExpectedEq("1")}, - {pgtype.Int<%= pg_byte_size %>{}, new(pgtype.Int<%= pg_byte_size %>), isExpectedEq(pgtype.Int<%= pg_byte_size %>{})}, - {nil, new(*int<%= pg_bit_size %>), isExpectedEq((*int<%= pg_bit_size %>)(nil))}, - }) -} - -func TestInt<%= pg_byte_size %>MarshalJSON(t *testing.T) { - successfulTests := []struct { - source pgtype.Int<%= pg_byte_size %> - result string - }{ - {source: pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 0}, result: "null"}, - {source: pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 1, Valid: true}, result: "1"}, - } - for i, tt := range successfulTests { - r, err := tt.source.MarshalJSON() - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if string(r) != tt.result { - t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, string(r)) - } - } -} - -func TestInt<%= pg_byte_size %>UnmarshalJSON(t *testing.T) { - successfulTests := []struct { - source string - result pgtype.Int<%= pg_byte_size %> - }{ - {source: "null", result: pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 0}}, - {source: "1", result: pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 1, Valid: true}}, - } - for i, tt := range successfulTests { - var r pgtype.Int<%= pg_byte_size %> - err := r.UnmarshalJSON([]byte(tt.source)) - if err != nil { - t.Errorf("%d: %v", i, err) - } - - if r != tt.result { - t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, r) - } - } -} -<% end %> diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test.go.erb b/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test.go.erb deleted file mode 100644 index 6f4011534..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test.go.erb +++ /dev/null @@ -1,62 +0,0 @@ -package pgtype_test - -import ( - "context" - "testing" - - "github.com/jackc/pgx/v5/pgtype/testutil" - "github.com/jackc/pgx/v5" -) - -<% - [ - ["int4", ["int16", "int32", "int64", "uint64", "pgtype.Int4"], [[1, 1], [1, 10], [10, 1], [100, 10]]], - ["numeric", ["int64", "float64", "pgtype.Numeric"], [[1, 1], [1, 10], [10, 1], [100, 10]]], - ].each do |pg_type, go_types, rows_columns| -%> -<% go_types.each do |go_type| %> -<% rows_columns.each do |rows, columns| %> -<% [["Text", "pgx.TextFormatCode"], ["Binary", "pgx.BinaryFormatCode"]].each do |format_name, format_code| %> -func BenchmarkQuery<%= format_name %>FormatDecode_PG_<%= pg_type %>_to_Go_<%= go_type.gsub(/\W/, "_") %>_<%= rows %>_rows_<%= columns %>_columns(b *testing.B) { - defaultConnTestRunner.RunTest(context.Background(), b, func(ctx context.Context, _ testing.TB, conn *pgx.Conn) { - b.ResetTimer() - var v [<%= columns %>]<%= go_type %> - for i := 0; i < b.N; i++ { - rows, _ := conn.Query( - ctx, - `select <% columns.times do |col_idx| %><% if col_idx != 0 %>, <% end %>n::<%= pg_type %> + <%= col_idx%><% end %> from generate_series(1, <%= rows %>) n`, - pgx.QueryResultFormats{<%= format_code %>}, - ) - _, err := pgx.ForEachRow(rows, []any{<% columns.times do |col_idx| %><% if col_idx != 0 %>, <% end %>&v[<%= col_idx%>]<% end %>}, func() error { return nil }) - if err != nil { - b.Fatal(err) - } - } - }) -} -<% end %> -<% end %> -<% end %> -<% end %> - -<% [10, 100, 1000].each do |array_size| %> -<% [["Text", "pgx.TextFormatCode"], ["Binary", "pgx.BinaryFormatCode"]].each do |format_name, format_code| %> -func BenchmarkQuery<%= format_name %>FormatDecode_PG_Int4Array_With_Go_Int4Array_<%= array_size %>(b *testing.B) { - defaultConnTestRunner.RunTest(context.Background(), b, func(ctx context.Context, _ testing.TB, conn *pgx.Conn) { - b.ResetTimer() - var v []int32 - for i := 0; i < b.N; i++ { - rows, _ := conn.Query( - ctx, - `select array_agg(n) from generate_series(1, <%= array_size %>) n`, - pgx.QueryResultFormats{<%= format_code %>}, - ) - _, err := pgx.ForEachRow(rows, []any{&v}, func() error { return nil }) - if err != nil { - b.Fatal(err) - } - } - }) -} -<% end %> -<% end %> diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test_gen.sh b/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test_gen.sh deleted file mode 100644 index 22ac01aaf..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test_gen.sh +++ /dev/null @@ -1,2 +0,0 @@ -erb integration_benchmark_test.go.erb > integration_benchmark_test.go -goimports -w integration_benchmark_test.go diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/interval.go b/vendor/github.com/jackc/pgx/v5/pgtype/interval.go deleted file mode 100644 index 4b5116295..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/interval.go +++ /dev/null @@ -1,297 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -const ( - microsecondsPerSecond = 1000000 - microsecondsPerMinute = 60 * microsecondsPerSecond - microsecondsPerHour = 60 * microsecondsPerMinute - microsecondsPerDay = 24 * microsecondsPerHour - microsecondsPerMonth = 30 * microsecondsPerDay -) - -type IntervalScanner interface { - ScanInterval(v Interval) error -} - -type IntervalValuer interface { - IntervalValue() (Interval, error) -} - -type Interval struct { - Microseconds int64 - Days int32 - Months int32 - Valid bool -} - -func (interval *Interval) ScanInterval(v Interval) error { - *interval = v - return nil -} - -func (interval Interval) IntervalValue() (Interval, error) { - return interval, nil -} - -// Scan implements the database/sql Scanner interface. -func (interval *Interval) Scan(src any) error { - if src == nil { - *interval = Interval{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToIntervalScanner{}.Scan([]byte(src), interval) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (interval Interval) Value() (driver.Value, error) { - if !interval.Valid { - return nil, nil - } - - buf, err := IntervalCodec{}.PlanEncode(nil, 0, TextFormatCode, interval).Encode(interval, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type IntervalCodec struct{} - -func (IntervalCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (IntervalCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (IntervalCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(IntervalValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanIntervalCodecBinary{} - case TextFormatCode: - return encodePlanIntervalCodecText{} - } - - return nil -} - -type encodePlanIntervalCodecBinary struct{} - -func (encodePlanIntervalCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - interval, err := value.(IntervalValuer).IntervalValue() - if err != nil { - return nil, err - } - - if !interval.Valid { - return nil, nil - } - - buf = pgio.AppendInt64(buf, interval.Microseconds) - buf = pgio.AppendInt32(buf, interval.Days) - buf = pgio.AppendInt32(buf, interval.Months) - return buf, nil -} - -type encodePlanIntervalCodecText struct{} - -func (encodePlanIntervalCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - interval, err := value.(IntervalValuer).IntervalValue() - if err != nil { - return nil, err - } - - if !interval.Valid { - return nil, nil - } - - if interval.Months != 0 { - buf = append(buf, strconv.FormatInt(int64(interval.Months), 10)...) - buf = append(buf, " mon "...) - } - - if interval.Days != 0 { - buf = append(buf, strconv.FormatInt(int64(interval.Days), 10)...) - buf = append(buf, " day "...) - } - - absMicroseconds := interval.Microseconds - if absMicroseconds < 0 { - absMicroseconds = -absMicroseconds - buf = append(buf, '-') - } - - hours := absMicroseconds / microsecondsPerHour - minutes := (absMicroseconds % microsecondsPerHour) / microsecondsPerMinute - seconds := (absMicroseconds % microsecondsPerMinute) / microsecondsPerSecond - - timeStr := fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds) - buf = append(buf, timeStr...) - - microseconds := absMicroseconds % microsecondsPerSecond - if microseconds != 0 { - buf = append(buf, fmt.Sprintf(".%06d", microseconds)...) - } - - return buf, nil -} - -func (IntervalCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case IntervalScanner: - return scanPlanBinaryIntervalToIntervalScanner{} - } - case TextFormatCode: - switch target.(type) { - case IntervalScanner: - return scanPlanTextAnyToIntervalScanner{} - } - } - - return nil -} - -type scanPlanBinaryIntervalToIntervalScanner struct{} - -func (scanPlanBinaryIntervalToIntervalScanner) Scan(src []byte, dst any) error { - scanner := (dst).(IntervalScanner) - - if src == nil { - return scanner.ScanInterval(Interval{}) - } - - if len(src) != 16 { - return fmt.Errorf("Received an invalid size for an interval: %d", len(src)) - } - - microseconds := int64(binary.BigEndian.Uint64(src)) - days := int32(binary.BigEndian.Uint32(src[8:])) - months := int32(binary.BigEndian.Uint32(src[12:])) - - return scanner.ScanInterval(Interval{Microseconds: microseconds, Days: days, Months: months, Valid: true}) -} - -type scanPlanTextAnyToIntervalScanner struct{} - -func (scanPlanTextAnyToIntervalScanner) Scan(src []byte, dst any) error { - scanner := (dst).(IntervalScanner) - - if src == nil { - return scanner.ScanInterval(Interval{}) - } - - var microseconds int64 - var days int32 - var months int32 - - parts := strings.Split(string(src), " ") - - for i := 0; i < len(parts)-1; i += 2 { - scalar, err := strconv.ParseInt(parts[i], 10, 64) - if err != nil { - return fmt.Errorf("bad interval format") - } - - switch parts[i+1] { - case "year", "years": - months += int32(scalar * 12) - case "mon", "mons": - months += int32(scalar) - case "day", "days": - days = int32(scalar) - } - } - - if len(parts)%2 == 1 { - timeParts := strings.SplitN(parts[len(parts)-1], ":", 3) - if len(timeParts) != 3 { - return fmt.Errorf("bad interval format") - } - - var negative bool - if timeParts[0][0] == '-' { - negative = true - timeParts[0] = timeParts[0][1:] - } - - hours, err := strconv.ParseInt(timeParts[0], 10, 64) - if err != nil { - return fmt.Errorf("bad interval hour format: %s", timeParts[0]) - } - - minutes, err := strconv.ParseInt(timeParts[1], 10, 64) - if err != nil { - return fmt.Errorf("bad interval minute format: %s", timeParts[1]) - } - - sec, secFrac, secFracFound := strings.Cut(timeParts[2], ".") - - seconds, err := strconv.ParseInt(sec, 10, 64) - if err != nil { - return fmt.Errorf("bad interval second format: %s", sec) - } - - var uSeconds int64 - if secFracFound { - uSeconds, err = strconv.ParseInt(secFrac, 10, 64) - if err != nil { - return fmt.Errorf("bad interval decimal format: %s", secFrac) - } - - for i := 0; i < 6-len(secFrac); i++ { - uSeconds *= 10 - } - } - - microseconds = hours * microsecondsPerHour - microseconds += minutes * microsecondsPerMinute - microseconds += seconds * microsecondsPerSecond - microseconds += uSeconds - - if negative { - microseconds = -microseconds - } - } - - return scanner.ScanInterval(Interval{Months: months, Days: days, Microseconds: microseconds, Valid: true}) -} - -func (c IntervalCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c IntervalCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var interval Interval - err := codecScan(c, m, oid, format, src, &interval) - if err != nil { - return nil, err - } - return interval, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/json.go b/vendor/github.com/jackc/pgx/v5/pgtype/json.go deleted file mode 100644 index 48b9f9771..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/json.go +++ /dev/null @@ -1,239 +0,0 @@ -package pgtype - -import ( - "database/sql" - "database/sql/driver" - "encoding/json" - "fmt" - "reflect" -) - -type JSONCodec struct { - Marshal func(v any) ([]byte, error) - Unmarshal func(data []byte, v any) error -} - -func (*JSONCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (*JSONCodec) PreferredFormat() int16 { - return TextFormatCode -} - -func (c *JSONCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch value.(type) { - case string: - return encodePlanJSONCodecEitherFormatString{} - case []byte: - return encodePlanJSONCodecEitherFormatByteSlice{} - - // Handle json.RawMessage specifically because if it is run through json.Marshal it may be mutated. - // e.g. `{"foo": "bar"}` -> `{"foo":"bar"}`. - case json.RawMessage: - return encodePlanJSONCodecEitherFormatJSONRawMessage{} - - // Cannot rely on driver.Valuer being handled later because anything can be marshalled. - // - // https://github.com/jackc/pgx/issues/1430 - // - // Check for driver.Valuer must come before json.Marshaler so that it is guaranteed to be used - // when both are implemented https://github.com/jackc/pgx/issues/1805 - case driver.Valuer: - return &encodePlanDriverValuer{m: m, oid: oid, formatCode: format} - - // Must come before trying wrap encode plans because a pointer to a struct may be unwrapped to a struct that can be - // marshalled. - // - // https://github.com/jackc/pgx/issues/1681 - case json.Marshaler: - return &encodePlanJSONCodecEitherFormatMarshal{ - marshal: c.Marshal, - } - } - - // Because anything can be marshalled the normal wrapping in Map.PlanScan doesn't get a chance to run. So try the - // appropriate wrappers here. - for _, f := range []TryWrapEncodePlanFunc{ - TryWrapDerefPointerEncodePlan, - TryWrapFindUnderlyingTypeEncodePlan, - } { - if wrapperPlan, nextValue, ok := f(value); ok { - if nextPlan := c.PlanEncode(m, oid, format, nextValue); nextPlan != nil { - wrapperPlan.SetNext(nextPlan) - return wrapperPlan - } - } - } - - return &encodePlanJSONCodecEitherFormatMarshal{ - marshal: c.Marshal, - } -} - -type encodePlanJSONCodecEitherFormatString struct{} - -func (encodePlanJSONCodecEitherFormatString) Encode(value any, buf []byte) (newBuf []byte, err error) { - jsonString := value.(string) - buf = append(buf, jsonString...) - return buf, nil -} - -type encodePlanJSONCodecEitherFormatByteSlice struct{} - -func (encodePlanJSONCodecEitherFormatByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { - jsonBytes := value.([]byte) - if jsonBytes == nil { - return nil, nil - } - - buf = append(buf, jsonBytes...) - return buf, nil -} - -type encodePlanJSONCodecEitherFormatJSONRawMessage struct{} - -func (encodePlanJSONCodecEitherFormatJSONRawMessage) Encode(value any, buf []byte) (newBuf []byte, err error) { - jsonBytes := value.(json.RawMessage) - if jsonBytes == nil { - return nil, nil - } - - buf = append(buf, jsonBytes...) - return buf, nil -} - -type encodePlanJSONCodecEitherFormatMarshal struct { - marshal func(v any) ([]byte, error) -} - -func (e *encodePlanJSONCodecEitherFormatMarshal) Encode(value any, buf []byte) (newBuf []byte, err error) { - jsonBytes, err := e.marshal(value) - if err != nil { - return nil, err - } - - buf = append(buf, jsonBytes...) - return buf, nil -} - -func (c *JSONCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch target.(type) { - case *string: - return scanPlanAnyToString{} - - case **string: - // This is to fix **string scanning. It seems wrong to special case **string, but it's not clear what a better - // solution would be. - // - // https://github.com/jackc/pgx/issues/1470 -- **string - // https://github.com/jackc/pgx/issues/1691 -- ** anything else - - if wrapperPlan, nextDst, ok := TryPointerPointerScanPlan(target); ok { - if nextPlan := m.planScan(oid, format, nextDst, 0); nextPlan != nil { - if _, failed := nextPlan.(*scanPlanFail); !failed { - wrapperPlan.SetNext(nextPlan) - return wrapperPlan - } - } - } - - case *[]byte: - return scanPlanJSONToByteSlice{} - case BytesScanner: - return scanPlanBinaryBytesToBytesScanner{} - - } - - // Cannot rely on sql.Scanner being handled later because scanPlanJSONToJSONUnmarshal will take precedence. - // - // https://github.com/jackc/pgx/issues/1418 - if isSQLScanner(target) { - return &scanPlanSQLScanner{formatCode: format} - } - - return &scanPlanJSONToJSONUnmarshal{ - unmarshal: c.Unmarshal, - } -} - -// we need to check if the target is a pointer to a sql.Scanner (or any of the pointer ref tree implements a sql.Scanner). -// -// https://github.com/jackc/pgx/issues/2146 -func isSQLScanner(v any) bool { - val := reflect.ValueOf(v) - for val.Kind() == reflect.Ptr { - if _, ok := val.Interface().(sql.Scanner); ok { - return true - } - val = val.Elem() - } - return false -} - -type scanPlanAnyToString struct{} - -func (scanPlanAnyToString) Scan(src []byte, dst any) error { - p := dst.(*string) - *p = string(src) - return nil -} - -type scanPlanJSONToByteSlice struct{} - -func (scanPlanJSONToByteSlice) Scan(src []byte, dst any) error { - dstBuf := dst.(*[]byte) - if src == nil { - *dstBuf = nil - return nil - } - - *dstBuf = make([]byte, len(src)) - copy(*dstBuf, src) - return nil -} - -type scanPlanJSONToJSONUnmarshal struct { - unmarshal func(data []byte, v any) error -} - -func (s *scanPlanJSONToJSONUnmarshal) Scan(src []byte, dst any) error { - if src == nil { - dstValue := reflect.ValueOf(dst) - if dstValue.Kind() == reflect.Ptr { - el := dstValue.Elem() - switch el.Kind() { - case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface: - el.Set(reflect.Zero(el.Type())) - return nil - } - } - - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - elem := reflect.ValueOf(dst).Elem() - elem.Set(reflect.Zero(elem.Type())) - - return s.unmarshal(src, dst) -} - -func (c *JSONCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - dstBuf := make([]byte, len(src)) - copy(dstBuf, src) - return dstBuf, nil -} - -func (c *JSONCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var dst any - err := c.Unmarshal(src, &dst) - return dst, err -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/jsonb.go b/vendor/github.com/jackc/pgx/v5/pgtype/jsonb.go deleted file mode 100644 index 4d4eb58e5..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/jsonb.go +++ /dev/null @@ -1,129 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "fmt" -) - -type JSONBCodec struct { - Marshal func(v any) ([]byte, error) - Unmarshal func(data []byte, v any) error -} - -func (*JSONBCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (*JSONBCodec) PreferredFormat() int16 { - return TextFormatCode -} - -func (c *JSONBCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - plan := (&JSONCodec{Marshal: c.Marshal, Unmarshal: c.Unmarshal}).PlanEncode(m, oid, TextFormatCode, value) - if plan != nil { - return &encodePlanJSONBCodecBinaryWrapper{textPlan: plan} - } - case TextFormatCode: - return (&JSONCodec{Marshal: c.Marshal, Unmarshal: c.Unmarshal}).PlanEncode(m, oid, format, value) - } - - return nil -} - -type encodePlanJSONBCodecBinaryWrapper struct { - textPlan EncodePlan -} - -func (plan *encodePlanJSONBCodecBinaryWrapper) Encode(value any, buf []byte) (newBuf []byte, err error) { - buf = append(buf, 1) - return plan.textPlan.Encode(value, buf) -} - -func (c *JSONBCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case BinaryFormatCode: - plan := (&JSONCodec{Marshal: c.Marshal, Unmarshal: c.Unmarshal}).PlanScan(m, oid, TextFormatCode, target) - if plan != nil { - return &scanPlanJSONBCodecBinaryUnwrapper{textPlan: plan} - } - case TextFormatCode: - return (&JSONCodec{Marshal: c.Marshal, Unmarshal: c.Unmarshal}).PlanScan(m, oid, format, target) - } - - return nil -} - -type scanPlanJSONBCodecBinaryUnwrapper struct { - textPlan ScanPlan -} - -func (plan *scanPlanJSONBCodecBinaryUnwrapper) Scan(src []byte, dst any) error { - if src == nil { - return plan.textPlan.Scan(src, dst) - } - - if len(src) == 0 { - return fmt.Errorf("jsonb too short") - } - - if src[0] != 1 { - return fmt.Errorf("unknown jsonb version number %d", src[0]) - } - - return plan.textPlan.Scan(src[1:], dst) -} - -func (c *JSONBCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - switch format { - case BinaryFormatCode: - if len(src) == 0 { - return nil, fmt.Errorf("jsonb too short") - } - - if src[0] != 1 { - return nil, fmt.Errorf("unknown jsonb version number %d", src[0]) - } - - dstBuf := make([]byte, len(src)-1) - copy(dstBuf, src[1:]) - return dstBuf, nil - case TextFormatCode: - dstBuf := make([]byte, len(src)) - copy(dstBuf, src) - return dstBuf, nil - default: - return nil, fmt.Errorf("unknown format code: %v", format) - } -} - -func (c *JSONBCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - switch format { - case BinaryFormatCode: - if len(src) == 0 { - return nil, fmt.Errorf("jsonb too short") - } - - if src[0] != 1 { - return nil, fmt.Errorf("unknown jsonb version number %d", src[0]) - } - - src = src[1:] - case TextFormatCode: - default: - return nil, fmt.Errorf("unknown format code: %v", format) - } - - var dst any - err := c.Unmarshal(src, &dst) - return dst, err -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/line.go b/vendor/github.com/jackc/pgx/v5/pgtype/line.go deleted file mode 100644 index 4ae8003e8..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/line.go +++ /dev/null @@ -1,225 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type LineScanner interface { - ScanLine(v Line) error -} - -type LineValuer interface { - LineValue() (Line, error) -} - -type Line struct { - A, B, C float64 - Valid bool -} - -func (line *Line) ScanLine(v Line) error { - *line = v - return nil -} - -func (line Line) LineValue() (Line, error) { - return line, nil -} - -func (line *Line) Set(src any) error { - return fmt.Errorf("cannot convert %v to Line", src) -} - -// Scan implements the database/sql Scanner interface. -func (line *Line) Scan(src any) error { - if src == nil { - *line = Line{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToLineScanner{}.Scan([]byte(src), line) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (line Line) Value() (driver.Value, error) { - if !line.Valid { - return nil, nil - } - - buf, err := LineCodec{}.PlanEncode(nil, 0, TextFormatCode, line).Encode(line, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type LineCodec struct{} - -func (LineCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (LineCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (LineCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(LineValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanLineCodecBinary{} - case TextFormatCode: - return encodePlanLineCodecText{} - } - - return nil -} - -type encodePlanLineCodecBinary struct{} - -func (encodePlanLineCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - line, err := value.(LineValuer).LineValue() - if err != nil { - return nil, err - } - - if !line.Valid { - return nil, nil - } - - buf = pgio.AppendUint64(buf, math.Float64bits(line.A)) - buf = pgio.AppendUint64(buf, math.Float64bits(line.B)) - buf = pgio.AppendUint64(buf, math.Float64bits(line.C)) - return buf, nil -} - -type encodePlanLineCodecText struct{} - -func (encodePlanLineCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - line, err := value.(LineValuer).LineValue() - if err != nil { - return nil, err - } - - if !line.Valid { - return nil, nil - } - - buf = append(buf, fmt.Sprintf(`{%s,%s,%s}`, - strconv.FormatFloat(line.A, 'f', -1, 64), - strconv.FormatFloat(line.B, 'f', -1, 64), - strconv.FormatFloat(line.C, 'f', -1, 64), - )...) - return buf, nil -} - -func (LineCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case LineScanner: - return scanPlanBinaryLineToLineScanner{} - } - case TextFormatCode: - switch target.(type) { - case LineScanner: - return scanPlanTextAnyToLineScanner{} - } - } - - return nil -} - -type scanPlanBinaryLineToLineScanner struct{} - -func (scanPlanBinaryLineToLineScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LineScanner) - - if src == nil { - return scanner.ScanLine(Line{}) - } - - if len(src) != 24 { - return fmt.Errorf("invalid length for line: %v", len(src)) - } - - a := binary.BigEndian.Uint64(src) - b := binary.BigEndian.Uint64(src[8:]) - c := binary.BigEndian.Uint64(src[16:]) - - return scanner.ScanLine(Line{ - A: math.Float64frombits(a), - B: math.Float64frombits(b), - C: math.Float64frombits(c), - Valid: true, - }) -} - -type scanPlanTextAnyToLineScanner struct{} - -func (scanPlanTextAnyToLineScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LineScanner) - - if src == nil { - return scanner.ScanLine(Line{}) - } - - if len(src) < 7 { - return fmt.Errorf("invalid length for line: %v", len(src)) - } - - parts := strings.SplitN(string(src[1:len(src)-1]), ",", 3) - if len(parts) < 3 { - return fmt.Errorf("invalid format for line") - } - - a, err := strconv.ParseFloat(parts[0], 64) - if err != nil { - return err - } - - b, err := strconv.ParseFloat(parts[1], 64) - if err != nil { - return err - } - - c, err := strconv.ParseFloat(parts[2], 64) - if err != nil { - return err - } - - return scanner.ScanLine(Line{A: a, B: b, C: c, Valid: true}) -} - -func (c LineCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c LineCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var line Line - err := codecScan(c, m, oid, format, src, &line) - if err != nil { - return nil, err - } - return line, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go b/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go deleted file mode 100644 index 05a86e1c8..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go +++ /dev/null @@ -1,238 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type LsegScanner interface { - ScanLseg(v Lseg) error -} - -type LsegValuer interface { - LsegValue() (Lseg, error) -} - -type Lseg struct { - P [2]Vec2 - Valid bool -} - -func (lseg *Lseg) ScanLseg(v Lseg) error { - *lseg = v - return nil -} - -func (lseg Lseg) LsegValue() (Lseg, error) { - return lseg, nil -} - -// Scan implements the database/sql Scanner interface. -func (lseg *Lseg) Scan(src any) error { - if src == nil { - *lseg = Lseg{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToLsegScanner{}.Scan([]byte(src), lseg) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (lseg Lseg) Value() (driver.Value, error) { - if !lseg.Valid { - return nil, nil - } - - buf, err := LsegCodec{}.PlanEncode(nil, 0, TextFormatCode, lseg).Encode(lseg, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type LsegCodec struct{} - -func (LsegCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (LsegCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (LsegCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(LsegValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanLsegCodecBinary{} - case TextFormatCode: - return encodePlanLsegCodecText{} - } - - return nil -} - -type encodePlanLsegCodecBinary struct{} - -func (encodePlanLsegCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - lseg, err := value.(LsegValuer).LsegValue() - if err != nil { - return nil, err - } - - if !lseg.Valid { - return nil, nil - } - - buf = pgio.AppendUint64(buf, math.Float64bits(lseg.P[0].X)) - buf = pgio.AppendUint64(buf, math.Float64bits(lseg.P[0].Y)) - buf = pgio.AppendUint64(buf, math.Float64bits(lseg.P[1].X)) - buf = pgio.AppendUint64(buf, math.Float64bits(lseg.P[1].Y)) - return buf, nil -} - -type encodePlanLsegCodecText struct{} - -func (encodePlanLsegCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - lseg, err := value.(LsegValuer).LsegValue() - if err != nil { - return nil, err - } - - if !lseg.Valid { - return nil, nil - } - - buf = append(buf, fmt.Sprintf(`[(%s,%s),(%s,%s)]`, - strconv.FormatFloat(lseg.P[0].X, 'f', -1, 64), - strconv.FormatFloat(lseg.P[0].Y, 'f', -1, 64), - strconv.FormatFloat(lseg.P[1].X, 'f', -1, 64), - strconv.FormatFloat(lseg.P[1].Y, 'f', -1, 64), - )...) - return buf, nil -} - -func (LsegCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case LsegScanner: - return scanPlanBinaryLsegToLsegScanner{} - } - case TextFormatCode: - switch target.(type) { - case LsegScanner: - return scanPlanTextAnyToLsegScanner{} - } - } - - return nil -} - -type scanPlanBinaryLsegToLsegScanner struct{} - -func (scanPlanBinaryLsegToLsegScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LsegScanner) - - if src == nil { - return scanner.ScanLseg(Lseg{}) - } - - if len(src) != 32 { - return fmt.Errorf("invalid length for lseg: %v", len(src)) - } - - x1 := binary.BigEndian.Uint64(src) - y1 := binary.BigEndian.Uint64(src[8:]) - x2 := binary.BigEndian.Uint64(src[16:]) - y2 := binary.BigEndian.Uint64(src[24:]) - - return scanner.ScanLseg(Lseg{ - P: [2]Vec2{ - {math.Float64frombits(x1), math.Float64frombits(y1)}, - {math.Float64frombits(x2), math.Float64frombits(y2)}, - }, - Valid: true, - }) -} - -type scanPlanTextAnyToLsegScanner struct{} - -func (scanPlanTextAnyToLsegScanner) Scan(src []byte, dst any) error { - scanner := (dst).(LsegScanner) - - if src == nil { - return scanner.ScanLseg(Lseg{}) - } - - if len(src) < 11 { - return fmt.Errorf("invalid length for lseg: %v", len(src)) - } - - str := string(src[2:]) - - var end int - end = strings.IndexByte(str, ',') - - x1, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+1:] - end = strings.IndexByte(str, ')') - - y1, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+3:] - end = strings.IndexByte(str, ',') - - x2, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+1 : len(str)-2] - - y2, err := strconv.ParseFloat(str, 64) - if err != nil { - return err - } - - return scanner.ScanLseg(Lseg{P: [2]Vec2{{x1, y1}, {x2, y2}}, Valid: true}) -} - -func (c LsegCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c LsegCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var lseg Lseg - err := codecScan(c, m, oid, format, src, &lseg) - if err != nil { - return nil, err - } - return lseg, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go deleted file mode 100644 index 6af317794..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go +++ /dev/null @@ -1,122 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "fmt" -) - -type LtreeCodec struct{} - -func (l LtreeCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -// PreferredFormat returns the preferred format. -func (l LtreeCodec) PreferredFormat() int16 { - return TextFormatCode -} - -// PlanEncode returns an EncodePlan for encoding value into PostgreSQL format for oid and format. If no plan can be -// found then nil is returned. -func (l LtreeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case TextFormatCode: - return (TextCodec)(l).PlanEncode(m, oid, format, value) - case BinaryFormatCode: - switch value.(type) { - case string: - return encodeLtreeCodecBinaryString{} - case []byte: - return encodeLtreeCodecBinaryByteSlice{} - case TextValuer: - return encodeLtreeCodecBinaryTextValuer{} - } - } - - return nil -} - -type encodeLtreeCodecBinaryString struct{} - -func (encodeLtreeCodecBinaryString) Encode(value any, buf []byte) (newBuf []byte, err error) { - ltree := value.(string) - buf = append(buf, 1) - return append(buf, ltree...), nil -} - -type encodeLtreeCodecBinaryByteSlice struct{} - -func (encodeLtreeCodecBinaryByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { - ltree := value.([]byte) - buf = append(buf, 1) - return append(buf, ltree...), nil -} - -type encodeLtreeCodecBinaryTextValuer struct{} - -func (encodeLtreeCodecBinaryTextValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - t, err := value.(TextValuer).TextValue() - if err != nil { - return nil, err - } - if !t.Valid { - return nil, nil - } - - buf = append(buf, 1) - return append(buf, t.String...), nil -} - -// PlanScan returns a ScanPlan for scanning a PostgreSQL value into a destination with the same type as target. If -// no plan can be found then nil is returned. -func (l LtreeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case TextFormatCode: - return (TextCodec)(l).PlanScan(m, oid, format, target) - case BinaryFormatCode: - switch target.(type) { - case *string: - return scanPlanBinaryLtreeToString{} - case TextScanner: - return scanPlanBinaryLtreeToTextScanner{} - } - } - - return nil -} - -type scanPlanBinaryLtreeToString struct{} - -func (scanPlanBinaryLtreeToString) Scan(src []byte, target any) error { - version := src[0] - if version != 1 { - return fmt.Errorf("unsupported ltree version %d", version) - } - - p := (target).(*string) - *p = string(src[1:]) - - return nil -} - -type scanPlanBinaryLtreeToTextScanner struct{} - -func (scanPlanBinaryLtreeToTextScanner) Scan(src []byte, target any) error { - version := src[0] - if version != 1 { - return fmt.Errorf("unsupported ltree version %d", version) - } - - scanner := (target).(TextScanner) - return scanner.ScanText(Text{String: string(src[1:]), Valid: true}) -} - -// DecodeDatabaseSQLValue returns src decoded into a value compatible with the sql.Scanner interface. -func (l LtreeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return (TextCodec)(l).DecodeDatabaseSQLValue(m, oid, format, src) -} - -// DecodeValue returns src decoded into its default format. -func (l LtreeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - return (TextCodec)(l).DecodeValue(m, oid, format, src) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go b/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go deleted file mode 100644 index e913ec903..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go +++ /dev/null @@ -1,162 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "net" -) - -type MacaddrCodec struct{} - -func (MacaddrCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (MacaddrCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (MacaddrCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case net.HardwareAddr: - return encodePlanMacaddrCodecBinaryHardwareAddr{} - case TextValuer: - return encodePlanMacAddrCodecTextValuer{} - - } - case TextFormatCode: - switch value.(type) { - case net.HardwareAddr: - return encodePlanMacaddrCodecTextHardwareAddr{} - case TextValuer: - return encodePlanTextCodecTextValuer{} - } - } - - return nil -} - -type encodePlanMacaddrCodecBinaryHardwareAddr struct{} - -func (encodePlanMacaddrCodecBinaryHardwareAddr) Encode(value any, buf []byte) (newBuf []byte, err error) { - addr := value.(net.HardwareAddr) - if addr == nil { - return nil, nil - } - - return append(buf, addr...), nil -} - -type encodePlanMacAddrCodecTextValuer struct{} - -func (encodePlanMacAddrCodecTextValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - t, err := value.(TextValuer).TextValue() - if err != nil { - return nil, err - } - if !t.Valid { - return nil, nil - } - - addr, err := net.ParseMAC(t.String) - if err != nil { - return nil, err - } - - return append(buf, addr...), nil -} - -type encodePlanMacaddrCodecTextHardwareAddr struct{} - -func (encodePlanMacaddrCodecTextHardwareAddr) Encode(value any, buf []byte) (newBuf []byte, err error) { - addr := value.(net.HardwareAddr) - if addr == nil { - return nil, nil - } - - return append(buf, addr.String()...), nil -} - -func (MacaddrCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case BinaryFormatCode: - switch target.(type) { - case *net.HardwareAddr: - return scanPlanBinaryMacaddrToHardwareAddr{} - case TextScanner: - return scanPlanBinaryMacaddrToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *net.HardwareAddr: - return scanPlanTextMacaddrToHardwareAddr{} - case TextScanner: - return scanPlanTextAnyToTextScanner{} - } - } - - return nil -} - -type scanPlanBinaryMacaddrToHardwareAddr struct{} - -func (scanPlanBinaryMacaddrToHardwareAddr) Scan(src []byte, dst any) error { - dstBuf := dst.(*net.HardwareAddr) - if src == nil { - *dstBuf = nil - return nil - } - - *dstBuf = make([]byte, len(src)) - copy(*dstBuf, src) - return nil -} - -type scanPlanBinaryMacaddrToTextScanner struct{} - -func (scanPlanBinaryMacaddrToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) - if src == nil { - return scanner.ScanText(Text{}) - } - - return scanner.ScanText(Text{String: net.HardwareAddr(src).String(), Valid: true}) -} - -type scanPlanTextMacaddrToHardwareAddr struct{} - -func (scanPlanTextMacaddrToHardwareAddr) Scan(src []byte, dst any) error { - p := dst.(*net.HardwareAddr) - - if src == nil { - *p = nil - return nil - } - - addr, err := net.ParseMAC(string(src)) - if err != nil { - return err - } - - *p = addr - - return nil -} - -func (c MacaddrCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c MacaddrCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var addr net.HardwareAddr - err := codecScan(c, m, oid, format, src, &addr) - if err != nil { - return nil, err - } - return addr, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go deleted file mode 100644 index e57637880..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go +++ /dev/null @@ -1,443 +0,0 @@ -package pgtype - -import ( - "bytes" - "database/sql/driver" - "encoding/binary" - "fmt" - "reflect" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// MultirangeGetter is a type that can be converted into a PostgreSQL multirange. -type MultirangeGetter interface { - // IsNull returns true if the value is SQL NULL. - IsNull() bool - - // Len returns the number of elements in the multirange. - Len() int - - // Index returns the element at i. - Index(i int) any - - // IndexType returns a non-nil scan target of the type Index will return. This is used by MultirangeCodec.PlanEncode. - IndexType() any -} - -// MultirangeSetter is a type can be set from a PostgreSQL multirange. -type MultirangeSetter interface { - // ScanNull sets the value to SQL NULL. - ScanNull() error - - // SetLen prepares the value such that ScanIndex can be called for each element. This will remove any existing - // elements. - SetLen(n int) error - - // ScanIndex returns a value usable as a scan target for i. SetLen must be called before ScanIndex. - ScanIndex(i int) any - - // ScanIndexType returns a non-nil scan target of the type ScanIndex will return. This is used by - // MultirangeCodec.PlanScan. - ScanIndexType() any -} - -// MultirangeCodec is a codec for any multirange type. -type MultirangeCodec struct { - ElementType *Type -} - -func (c *MultirangeCodec) FormatSupported(format int16) bool { - return c.ElementType.Codec.FormatSupported(format) -} - -func (c *MultirangeCodec) PreferredFormat() int16 { - return c.ElementType.Codec.PreferredFormat() -} - -func (c *MultirangeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - multirangeValuer, ok := value.(MultirangeGetter) - if !ok { - return nil - } - - elementType := multirangeValuer.IndexType() - - elementEncodePlan := m.PlanEncode(c.ElementType.OID, format, elementType) - if elementEncodePlan == nil { - return nil - } - - switch format { - case BinaryFormatCode: - return &encodePlanMultirangeCodecBinary{ac: c, m: m, oid: oid} - case TextFormatCode: - return &encodePlanMultirangeCodecText{ac: c, m: m, oid: oid} - } - - return nil -} - -type encodePlanMultirangeCodecText struct { - ac *MultirangeCodec - m *Map - oid uint32 -} - -func (p *encodePlanMultirangeCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - multirange := value.(MultirangeGetter) - - if multirange.IsNull() { - return nil, nil - } - - elementCount := multirange.Len() - - buf = append(buf, '{') - - var encodePlan EncodePlan - var lastElemType reflect.Type - inElemBuf := make([]byte, 0, 32) - for i := 0; i < elementCount; i++ { - if i > 0 { - buf = append(buf, ',') - } - - elem := multirange.Index(i) - var elemBuf []byte - if elem != nil { - elemType := reflect.TypeOf(elem) - if lastElemType != elemType { - lastElemType = elemType - encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, TextFormatCode, elem) - if encodePlan == nil { - return nil, fmt.Errorf("unable to encode %v", multirange.Index(i)) - } - } - elemBuf, err = encodePlan.Encode(elem, inElemBuf) - if err != nil { - return nil, err - } - } - - if elemBuf == nil { - return nil, fmt.Errorf("multirange cannot contain NULL element") - } else { - buf = append(buf, elemBuf...) - } - } - - buf = append(buf, '}') - - return buf, nil -} - -type encodePlanMultirangeCodecBinary struct { - ac *MultirangeCodec - m *Map - oid uint32 -} - -func (p *encodePlanMultirangeCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - multirange := value.(MultirangeGetter) - - if multirange.IsNull() { - return nil, nil - } - - elementCount := multirange.Len() - - buf = pgio.AppendInt32(buf, int32(elementCount)) - - var encodePlan EncodePlan - var lastElemType reflect.Type - for i := 0; i < elementCount; i++ { - sp := len(buf) - buf = pgio.AppendInt32(buf, -1) - - elem := multirange.Index(i) - var elemBuf []byte - if elem != nil { - elemType := reflect.TypeOf(elem) - if lastElemType != elemType { - lastElemType = elemType - encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, BinaryFormatCode, elem) - if encodePlan == nil { - return nil, fmt.Errorf("unable to encode %v", multirange.Index(i)) - } - } - elemBuf, err = encodePlan.Encode(elem, buf) - if err != nil { - return nil, err - } - } - - if elemBuf == nil { - return nil, fmt.Errorf("multirange cannot contain NULL element") - } else { - buf = elemBuf - pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) - } - } - - return buf, nil -} - -func (c *MultirangeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - multirangeScanner, ok := target.(MultirangeSetter) - if !ok { - return nil - } - - elementType := multirangeScanner.ScanIndexType() - - elementScanPlan := m.PlanScan(c.ElementType.OID, format, elementType) - if _, ok := elementScanPlan.(*scanPlanFail); ok { - return nil - } - - return &scanPlanMultirangeCodec{ - multirangeCodec: c, - m: m, - oid: oid, - formatCode: format, - } -} - -func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, multirange MultirangeSetter) error { - rp := 0 - - elementCount := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - err := multirange.SetLen(elementCount) - if err != nil { - return err - } - - if elementCount == 0 { - return nil - } - - elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, multirange.ScanIndex(0)) - if elementScanPlan == nil { - elementScanPlan = m.PlanScan(c.ElementType.OID, BinaryFormatCode, multirange.ScanIndex(0)) - } - - for i := 0; i < elementCount; i++ { - elem := multirange.ScanIndex(i) - elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) - rp += 4 - var elemSrc []byte - if elemLen >= 0 { - elemSrc = src[rp : rp+elemLen] - rp += elemLen - } - err = elementScanPlan.Scan(elemSrc, elem) - if err != nil { - return fmt.Errorf("failed to scan multirange element %d: %w", i, err) - } - } - - return nil -} - -func (c *MultirangeCodec) decodeText(m *Map, multirangeOID uint32, src []byte, multirange MultirangeSetter) error { - elements, err := parseUntypedTextMultirange(src) - if err != nil { - return err - } - - err = multirange.SetLen(len(elements)) - if err != nil { - return err - } - - if len(elements) == 0 { - return nil - } - - elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, TextFormatCode, multirange.ScanIndex(0)) - if elementScanPlan == nil { - elementScanPlan = m.PlanScan(c.ElementType.OID, TextFormatCode, multirange.ScanIndex(0)) - } - - for i, s := range elements { - elem := multirange.ScanIndex(i) - err = elementScanPlan.Scan([]byte(s), elem) - if err != nil { - return err - } - } - - return nil -} - -type scanPlanMultirangeCodec struct { - multirangeCodec *MultirangeCodec - m *Map - oid uint32 - formatCode int16 - elementScanPlan ScanPlan -} - -func (spac *scanPlanMultirangeCodec) Scan(src []byte, dst any) error { - c := spac.multirangeCodec - m := spac.m - oid := spac.oid - formatCode := spac.formatCode - - multirange := dst.(MultirangeSetter) - - if src == nil { - return multirange.ScanNull() - } - - switch formatCode { - case BinaryFormatCode: - return c.decodeBinary(m, oid, src, multirange) - case TextFormatCode: - return c.decodeText(m, oid, src, multirange) - default: - return fmt.Errorf("unknown format code %d", formatCode) - } -} - -func (c *MultirangeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - switch format { - case TextFormatCode: - return string(src), nil - case BinaryFormatCode: - buf := make([]byte, len(src)) - copy(buf, src) - return buf, nil - default: - return nil, fmt.Errorf("unknown format code %d", format) - } -} - -func (c *MultirangeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var multirange Multirange[Range[any]] - err := m.PlanScan(oid, format, &multirange).Scan(src, &multirange) - return multirange, err -} - -func parseUntypedTextMultirange(src []byte) ([]string, error) { - elements := make([]string, 0) - - buf := bytes.NewBuffer(src) - - skipWhitespace(buf) - - r, _, err := buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid array: %w", err) - } - - if r != '{' { - return nil, fmt.Errorf("invalid multirange, expected '{' got %v", r) - } - -parseValueLoop: - for { - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid multirange: %w", err) - } - - switch r { - case ',': // skip range separator - case '}': - break parseValueLoop - default: - buf.UnreadRune() - value, err := parseRange(buf) - if err != nil { - return nil, fmt.Errorf("invalid multirange value: %w", err) - } - elements = append(elements, value) - } - } - - skipWhitespace(buf) - - if buf.Len() > 0 { - return nil, fmt.Errorf("unexpected trailing data: %v", buf.String()) - } - - return elements, nil - -} - -func parseRange(buf *bytes.Buffer) (string, error) { - s := &bytes.Buffer{} - - boundSepRead := false - for { - r, _, err := buf.ReadRune() - if err != nil { - return "", err - } - - switch r { - case ',', '}': - if r == ',' && !boundSepRead { - boundSepRead = true - break - } - buf.UnreadRune() - return s.String(), nil - } - - s.WriteRune(r) - } -} - -// Multirange is a generic multirange type. -// -// T should implement RangeValuer and *T should implement RangeScanner. However, there does not appear to be a way to -// enforce the RangeScanner constraint. -type Multirange[T RangeValuer] []T - -func (r Multirange[T]) IsNull() bool { - return r == nil -} - -func (r Multirange[T]) Len() int { - return len(r) -} - -func (r Multirange[T]) Index(i int) any { - return r[i] -} - -func (r Multirange[T]) IndexType() any { - var zero T - return zero -} - -func (r *Multirange[T]) ScanNull() error { - *r = nil - return nil -} - -func (r *Multirange[T]) SetLen(n int) error { - *r = make([]T, n) - return nil -} - -func (r Multirange[T]) ScanIndex(i int) any { - return &r[i] -} - -func (r Multirange[T]) ScanIndexType() any { - return new(T) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go deleted file mode 100644 index 4dbec7861..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go +++ /dev/null @@ -1,823 +0,0 @@ -package pgtype - -import ( - "bytes" - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "math/big" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// PostgreSQL internal numeric storage uses 16-bit "digits" with base of 10,000 -const nbase = 10000 - -const ( - pgNumericNaN = 0x00000000c0000000 - pgNumericNaNSign = 0xc000 - - pgNumericPosInf = 0x00000000d0000000 - pgNumericPosInfSign = 0xd000 - - pgNumericNegInf = 0x00000000f0000000 - pgNumericNegInfSign = 0xf000 -) - -var big0 *big.Int = big.NewInt(0) -var big1 *big.Int = big.NewInt(1) -var big10 *big.Int = big.NewInt(10) -var big100 *big.Int = big.NewInt(100) -var big1000 *big.Int = big.NewInt(1000) - -var bigNBase *big.Int = big.NewInt(nbase) -var bigNBaseX2 *big.Int = big.NewInt(nbase * nbase) -var bigNBaseX3 *big.Int = big.NewInt(nbase * nbase * nbase) -var bigNBaseX4 *big.Int = big.NewInt(nbase * nbase * nbase * nbase) - -type NumericScanner interface { - ScanNumeric(v Numeric) error -} - -type NumericValuer interface { - NumericValue() (Numeric, error) -} - -type Numeric struct { - Int *big.Int - Exp int32 - NaN bool - InfinityModifier InfinityModifier - Valid bool -} - -func (n *Numeric) ScanNumeric(v Numeric) error { - *n = v - return nil -} - -func (n Numeric) NumericValue() (Numeric, error) { - return n, nil -} - -func (n Numeric) Float64Value() (Float8, error) { - if !n.Valid { - return Float8{}, nil - } else if n.NaN { - return Float8{Float64: math.NaN(), Valid: true}, nil - } else if n.InfinityModifier == Infinity { - return Float8{Float64: math.Inf(1), Valid: true}, nil - } else if n.InfinityModifier == NegativeInfinity { - return Float8{Float64: math.Inf(-1), Valid: true}, nil - } - - buf := make([]byte, 0, 32) - - if n.Int == nil { - buf = append(buf, '0') - } else { - buf = append(buf, n.Int.String()...) - } - buf = append(buf, 'e') - buf = append(buf, strconv.FormatInt(int64(n.Exp), 10)...) - - f, err := strconv.ParseFloat(string(buf), 64) - if err != nil { - return Float8{}, err - } - - return Float8{Float64: f, Valid: true}, nil -} - -func (n *Numeric) ScanInt64(v Int8) error { - if !v.Valid { - *n = Numeric{} - return nil - } - - *n = Numeric{Int: big.NewInt(v.Int64), Valid: true} - return nil -} - -func (n Numeric) Int64Value() (Int8, error) { - if !n.Valid { - return Int8{}, nil - } - - bi, err := n.toBigInt() - if err != nil { - return Int8{}, err - } - - if !bi.IsInt64() { - return Int8{}, fmt.Errorf("cannot convert %v to int64", n) - } - - return Int8{Int64: bi.Int64(), Valid: true}, nil -} - -func (n *Numeric) ScanScientific(src string) error { - if !strings.ContainsAny("eE", src) { - return scanPlanTextAnyToNumericScanner{}.Scan([]byte(src), n) - } - - if bigF, ok := new(big.Float).SetString(string(src)); ok { - smallF, _ := bigF.Float64() - src = strconv.FormatFloat(smallF, 'f', -1, 64) - } - - num, exp, err := parseNumericString(src) - if err != nil { - return err - } - - *n = Numeric{Int: num, Exp: exp, Valid: true} - - return nil -} - -func (n *Numeric) toBigInt() (*big.Int, error) { - if n.Exp == 0 { - return n.Int, nil - } - - num := &big.Int{} - num.Set(n.Int) - if n.Exp > 0 { - mul := &big.Int{} - mul.Exp(big10, big.NewInt(int64(n.Exp)), nil) - num.Mul(num, mul) - return num, nil - } - - div := &big.Int{} - div.Exp(big10, big.NewInt(int64(-n.Exp)), nil) - remainder := &big.Int{} - num.DivMod(num, div, remainder) - if remainder.Cmp(big0) != 0 { - return nil, fmt.Errorf("cannot convert %v to integer", n) - } - return num, nil -} - -func parseNumericString(str string) (n *big.Int, exp int32, err error) { - idx := strings.IndexByte(str, '.') - - if idx == -1 { - for len(str) > 1 && str[len(str)-1] == '0' && str[len(str)-2] != '-' { - str = str[:len(str)-1] - exp++ - } - } else { - exp = int32(-(len(str) - idx - 1)) - str = str[:idx] + str[idx+1:] - } - - accum := &big.Int{} - if _, ok := accum.SetString(str, 10); !ok { - return nil, 0, fmt.Errorf("%s is not a number", str) - } - - return accum, exp, nil -} - -func nbaseDigitsToInt64(src []byte) (accum int64, bytesRead, digitsRead int) { - digits := len(src) / 2 - if digits > 4 { - digits = 4 - } - - rp := 0 - - for i := 0; i < digits; i++ { - if i > 0 { - accum *= nbase - } - accum += int64(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - } - - return accum, rp, digits -} - -// Scan implements the database/sql Scanner interface. -func (n *Numeric) Scan(src any) error { - if src == nil { - *n = Numeric{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToNumericScanner{}.Scan([]byte(src), n) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (n Numeric) Value() (driver.Value, error) { - if !n.Valid { - return nil, nil - } - - buf, err := NumericCodec{}.PlanEncode(nil, 0, TextFormatCode, n).Encode(n, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -func (n Numeric) MarshalJSON() ([]byte, error) { - if !n.Valid { - return []byte("null"), nil - } - - if n.NaN { - return []byte(`"NaN"`), nil - } - - return n.numberTextBytes(), nil -} - -func (n *Numeric) UnmarshalJSON(src []byte) error { - if bytes.Equal(src, []byte(`null`)) { - *n = Numeric{} - return nil - } - if bytes.Equal(src, []byte(`"NaN"`)) { - *n = Numeric{NaN: true, Valid: true} - return nil - } - return scanPlanTextAnyToNumericScanner{}.Scan(src, n) -} - -// numberString returns a string of the number. undefined if NaN, infinite, or NULL -func (n Numeric) numberTextBytes() []byte { - intStr := n.Int.String() - - buf := &bytes.Buffer{} - - if len(intStr) > 0 && intStr[:1] == "-" { - intStr = intStr[1:] - buf.WriteByte('-') - } - - exp := int(n.Exp) - if exp > 0 { - buf.WriteString(intStr) - for i := 0; i < exp; i++ { - buf.WriteByte('0') - } - } else if exp < 0 { - if len(intStr) <= -exp { - buf.WriteString("0.") - leadingZeros := -exp - len(intStr) - for i := 0; i < leadingZeros; i++ { - buf.WriteByte('0') - } - buf.WriteString(intStr) - } else if len(intStr) > -exp { - dpPos := len(intStr) + exp - buf.WriteString(intStr[:dpPos]) - buf.WriteByte('.') - buf.WriteString(intStr[dpPos:]) - } - } else { - buf.WriteString(intStr) - } - - return buf.Bytes() -} - -type NumericCodec struct{} - -func (NumericCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (NumericCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (NumericCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case NumericValuer: - return encodePlanNumericCodecBinaryNumericValuer{} - case Float64Valuer: - return encodePlanNumericCodecBinaryFloat64Valuer{} - case Int64Valuer: - return encodePlanNumericCodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case NumericValuer: - return encodePlanNumericCodecTextNumericValuer{} - case Float64Valuer: - return encodePlanNumericCodecTextFloat64Valuer{} - case Int64Valuer: - return encodePlanNumericCodecTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanNumericCodecBinaryNumericValuer struct{} - -func (encodePlanNumericCodecBinaryNumericValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(NumericValuer).NumericValue() - if err != nil { - return nil, err - } - - return encodeNumericBinary(n, buf) -} - -type encodePlanNumericCodecBinaryFloat64Valuer struct{} - -func (encodePlanNumericCodecBinaryFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Float64Valuer).Float64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if math.IsNaN(n.Float64) { - return encodeNumericBinary(Numeric{NaN: true, Valid: true}, buf) - } else if math.IsInf(n.Float64, 1) { - return encodeNumericBinary(Numeric{InfinityModifier: Infinity, Valid: true}, buf) - } else if math.IsInf(n.Float64, -1) { - return encodeNumericBinary(Numeric{InfinityModifier: NegativeInfinity, Valid: true}, buf) - } - num, exp, err := parseNumericString(strconv.FormatFloat(n.Float64, 'f', -1, 64)) - if err != nil { - return nil, err - } - - return encodeNumericBinary(Numeric{Int: num, Exp: exp, Valid: true}, buf) -} - -type encodePlanNumericCodecBinaryInt64Valuer struct{} - -func (encodePlanNumericCodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - return encodeNumericBinary(Numeric{Int: big.NewInt(n.Int64), Valid: true}, buf) -} - -func encodeNumericBinary(n Numeric, buf []byte) (newBuf []byte, err error) { - if !n.Valid { - return nil, nil - } - - if n.NaN { - buf = pgio.AppendUint64(buf, pgNumericNaN) - return buf, nil - } else if n.InfinityModifier == Infinity { - buf = pgio.AppendUint64(buf, pgNumericPosInf) - return buf, nil - } else if n.InfinityModifier == NegativeInfinity { - buf = pgio.AppendUint64(buf, pgNumericNegInf) - return buf, nil - } - - var sign int16 - if n.Int.Cmp(big0) < 0 { - sign = 16384 - } - - absInt := &big.Int{} - wholePart := &big.Int{} - fracPart := &big.Int{} - remainder := &big.Int{} - absInt.Abs(n.Int) - - // Normalize absInt and exp to where exp is always a multiple of 4. This makes - // converting to 16-bit base 10,000 digits easier. - var exp int32 - switch n.Exp % 4 { - case 1, -3: - exp = n.Exp - 1 - absInt.Mul(absInt, big10) - case 2, -2: - exp = n.Exp - 2 - absInt.Mul(absInt, big100) - case 3, -1: - exp = n.Exp - 3 - absInt.Mul(absInt, big1000) - default: - exp = n.Exp - } - - if exp < 0 { - divisor := &big.Int{} - divisor.Exp(big10, big.NewInt(int64(-exp)), nil) - wholePart.DivMod(absInt, divisor, fracPart) - fracPart.Add(fracPart, divisor) - } else { - wholePart = absInt - } - - var wholeDigits, fracDigits []int16 - - for wholePart.Cmp(big0) != 0 { - wholePart.DivMod(wholePart, bigNBase, remainder) - wholeDigits = append(wholeDigits, int16(remainder.Int64())) - } - - if fracPart.Cmp(big0) != 0 { - for fracPart.Cmp(big1) != 0 { - fracPart.DivMod(fracPart, bigNBase, remainder) - fracDigits = append(fracDigits, int16(remainder.Int64())) - } - } - - buf = pgio.AppendInt16(buf, int16(len(wholeDigits)+len(fracDigits))) - - var weight int16 - if len(wholeDigits) > 0 { - weight = int16(len(wholeDigits) - 1) - if exp > 0 { - weight += int16(exp / 4) - } - } else { - weight = int16(exp/4) - 1 + int16(len(fracDigits)) - } - buf = pgio.AppendInt16(buf, weight) - - buf = pgio.AppendInt16(buf, sign) - - var dscale int16 - if n.Exp < 0 { - dscale = int16(-n.Exp) - } - buf = pgio.AppendInt16(buf, dscale) - - for i := len(wholeDigits) - 1; i >= 0; i-- { - buf = pgio.AppendInt16(buf, wholeDigits[i]) - } - - for i := len(fracDigits) - 1; i >= 0; i-- { - buf = pgio.AppendInt16(buf, fracDigits[i]) - } - - return buf, nil -} - -type encodePlanNumericCodecTextNumericValuer struct{} - -func (encodePlanNumericCodecTextNumericValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(NumericValuer).NumericValue() - if err != nil { - return nil, err - } - - return encodeNumericText(n, buf) -} - -type encodePlanNumericCodecTextFloat64Valuer struct{} - -func (encodePlanNumericCodecTextFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Float64Valuer).Float64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - if math.IsNaN(n.Float64) { - buf = append(buf, "NaN"...) - } else if math.IsInf(n.Float64, 1) { - buf = append(buf, "Infinity"...) - } else if math.IsInf(n.Float64, -1) { - buf = append(buf, "-Infinity"...) - } else { - buf = append(buf, strconv.FormatFloat(n.Float64, 'f', -1, 64)...) - } - return buf, nil -} - -type encodePlanNumericCodecTextInt64Valuer struct{} - -func (encodePlanNumericCodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - n, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !n.Valid { - return nil, nil - } - - buf = append(buf, strconv.FormatInt(n.Int64, 10)...) - return buf, nil -} - -func encodeNumericText(n Numeric, buf []byte) (newBuf []byte, err error) { - if !n.Valid { - return nil, nil - } - - if n.NaN { - buf = append(buf, "NaN"...) - return buf, nil - } else if n.InfinityModifier == Infinity { - buf = append(buf, "Infinity"...) - return buf, nil - } else if n.InfinityModifier == NegativeInfinity { - buf = append(buf, "-Infinity"...) - return buf, nil - } - - buf = append(buf, n.numberTextBytes()...) - - return buf, nil -} - -func (NumericCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case NumericScanner: - return scanPlanBinaryNumericToNumericScanner{} - case Float64Scanner: - return scanPlanBinaryNumericToFloat64Scanner{} - case Int64Scanner: - return scanPlanBinaryNumericToInt64Scanner{} - case TextScanner: - return scanPlanBinaryNumericToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case NumericScanner: - return scanPlanTextAnyToNumericScanner{} - case Float64Scanner: - return scanPlanTextAnyToFloat64Scanner{} - case Int64Scanner: - return scanPlanTextAnyToInt64Scanner{} - } - } - - return nil -} - -type scanPlanBinaryNumericToNumericScanner struct{} - -func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NumericScanner) - - if src == nil { - return scanner.ScanNumeric(Numeric{}) - } - - if len(src) < 8 { - return fmt.Errorf("numeric incomplete %v", src) - } - - rp := 0 - ndigits := binary.BigEndian.Uint16(src[rp:]) - rp += 2 - weight := int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - sign := binary.BigEndian.Uint16(src[rp:]) - rp += 2 - dscale := int16(binary.BigEndian.Uint16(src[rp:])) - rp += 2 - - if sign == pgNumericNaNSign { - return scanner.ScanNumeric(Numeric{NaN: true, Valid: true}) - } else if sign == pgNumericPosInfSign { - return scanner.ScanNumeric(Numeric{InfinityModifier: Infinity, Valid: true}) - } else if sign == pgNumericNegInfSign { - return scanner.ScanNumeric(Numeric{InfinityModifier: NegativeInfinity, Valid: true}) - } - - if ndigits == 0 { - return scanner.ScanNumeric(Numeric{Int: big.NewInt(0), Valid: true}) - } - - if len(src[rp:]) < int(ndigits)*2 { - return fmt.Errorf("numeric incomplete %v", src) - } - - accum := &big.Int{} - - for i := 0; i < int(ndigits+3)/4; i++ { - int64accum, bytesRead, digitsRead := nbaseDigitsToInt64(src[rp:]) - rp += bytesRead - - if i > 0 { - var mul *big.Int - switch digitsRead { - case 1: - mul = bigNBase - case 2: - mul = bigNBaseX2 - case 3: - mul = bigNBaseX3 - case 4: - mul = bigNBaseX4 - default: - return fmt.Errorf("invalid digitsRead: %d (this can't happen)", digitsRead) - } - accum.Mul(accum, mul) - } - - accum.Add(accum, big.NewInt(int64accum)) - } - - exp := (int32(weight) - int32(ndigits) + 1) * 4 - - if dscale > 0 { - fracNBaseDigits := int16(int32(ndigits) - int32(weight) - 1) - fracDecimalDigits := fracNBaseDigits * 4 - - if dscale > fracDecimalDigits { - multCount := int(dscale - fracDecimalDigits) - for i := 0; i < multCount; i++ { - accum.Mul(accum, big10) - exp-- - } - } else if dscale < fracDecimalDigits { - divCount := int(fracDecimalDigits - dscale) - for i := 0; i < divCount; i++ { - accum.Div(accum, big10) - exp++ - } - } - } - - reduced := &big.Int{} - remainder := &big.Int{} - if exp >= 0 { - for { - reduced.DivMod(accum, big10, remainder) - if remainder.Cmp(big0) != 0 { - break - } - accum.Set(reduced) - exp++ - } - } - - if sign != 0 { - accum.Neg(accum) - } - - return scanner.ScanNumeric(Numeric{Int: accum, Exp: exp, Valid: true}) -} - -type scanPlanBinaryNumericToFloat64Scanner struct{} - -func (scanPlanBinaryNumericToFloat64Scanner) Scan(src []byte, dst any) error { - scanner := (dst).(Float64Scanner) - - if src == nil { - return scanner.ScanFloat64(Float8{}) - } - - var n Numeric - - err := scanPlanBinaryNumericToNumericScanner{}.Scan(src, &n) - if err != nil { - return err - } - - f8, err := n.Float64Value() - if err != nil { - return err - } - - return scanner.ScanFloat64(f8) -} - -type scanPlanBinaryNumericToInt64Scanner struct{} - -func (scanPlanBinaryNumericToInt64Scanner) Scan(src []byte, dst any) error { - scanner := (dst).(Int64Scanner) - - if src == nil { - return scanner.ScanInt64(Int8{}) - } - - var n Numeric - - err := scanPlanBinaryNumericToNumericScanner{}.Scan(src, &n) - if err != nil { - return err - } - - bigInt, err := n.toBigInt() - if err != nil { - return err - } - - if !bigInt.IsInt64() { - return fmt.Errorf("%v is out of range for int64", bigInt) - } - - return scanner.ScanInt64(Int8{Int64: bigInt.Int64(), Valid: true}) -} - -type scanPlanBinaryNumericToTextScanner struct{} - -func (scanPlanBinaryNumericToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) - - if src == nil { - return scanner.ScanText(Text{}) - } - - var n Numeric - - err := scanPlanBinaryNumericToNumericScanner{}.Scan(src, &n) - if err != nil { - return err - } - - sbuf, err := encodeNumericText(n, nil) - if err != nil { - return err - } - - return scanner.ScanText(Text{String: string(sbuf), Valid: true}) -} - -type scanPlanTextAnyToNumericScanner struct{} - -func (scanPlanTextAnyToNumericScanner) Scan(src []byte, dst any) error { - scanner := (dst).(NumericScanner) - - if src == nil { - return scanner.ScanNumeric(Numeric{}) - } - - if string(src) == "NaN" { - return scanner.ScanNumeric(Numeric{NaN: true, Valid: true}) - } else if string(src) == "Infinity" { - return scanner.ScanNumeric(Numeric{InfinityModifier: Infinity, Valid: true}) - } else if string(src) == "-Infinity" { - return scanner.ScanNumeric(Numeric{InfinityModifier: NegativeInfinity, Valid: true}) - } - - num, exp, err := parseNumericString(string(src)) - if err != nil { - return err - } - - return scanner.ScanNumeric(Numeric{Int: num, Exp: exp, Valid: true}) -} - -func (c NumericCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - if format == TextFormatCode { - return string(src), nil - } - - var n Numeric - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - - buf, err := m.Encode(oid, TextFormatCode, n, nil) - if err != nil { - return nil, err - } - return string(buf), nil -} - -func (c NumericCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n Numeric - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/path.go b/vendor/github.com/jackc/pgx/v5/pgtype/path.go deleted file mode 100644 index 73e0ec52f..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/path.go +++ /dev/null @@ -1,272 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type PathScanner interface { - ScanPath(v Path) error -} - -type PathValuer interface { - PathValue() (Path, error) -} - -type Path struct { - P []Vec2 - Closed bool - Valid bool -} - -func (path *Path) ScanPath(v Path) error { - *path = v - return nil -} - -func (path Path) PathValue() (Path, error) { - return path, nil -} - -// Scan implements the database/sql Scanner interface. -func (path *Path) Scan(src any) error { - if src == nil { - *path = Path{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToPathScanner{}.Scan([]byte(src), path) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (path Path) Value() (driver.Value, error) { - if !path.Valid { - return nil, nil - } - - buf, err := PathCodec{}.PlanEncode(nil, 0, TextFormatCode, path).Encode(path, nil) - if err != nil { - return nil, err - } - - return string(buf), err -} - -type PathCodec struct{} - -func (PathCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (PathCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (PathCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(PathValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanPathCodecBinary{} - case TextFormatCode: - return encodePlanPathCodecText{} - } - - return nil -} - -type encodePlanPathCodecBinary struct{} - -func (encodePlanPathCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - path, err := value.(PathValuer).PathValue() - if err != nil { - return nil, err - } - - if !path.Valid { - return nil, nil - } - - var closeByte byte - if path.Closed { - closeByte = 1 - } - buf = append(buf, closeByte) - - buf = pgio.AppendInt32(buf, int32(len(path.P))) - - for _, p := range path.P { - buf = pgio.AppendUint64(buf, math.Float64bits(p.X)) - buf = pgio.AppendUint64(buf, math.Float64bits(p.Y)) - } - - return buf, nil -} - -type encodePlanPathCodecText struct{} - -func (encodePlanPathCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - path, err := value.(PathValuer).PathValue() - if err != nil { - return nil, err - } - - if !path.Valid { - return nil, nil - } - - var startByte, endByte byte - if path.Closed { - startByte = '(' - endByte = ')' - } else { - startByte = '[' - endByte = ']' - } - buf = append(buf, startByte) - - for i, p := range path.P { - if i > 0 { - buf = append(buf, ',') - } - buf = append(buf, fmt.Sprintf(`(%s,%s)`, - strconv.FormatFloat(p.X, 'f', -1, 64), - strconv.FormatFloat(p.Y, 'f', -1, 64), - )...) - } - - buf = append(buf, endByte) - - return buf, nil -} - -func (PathCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case PathScanner: - return scanPlanBinaryPathToPathScanner{} - } - case TextFormatCode: - switch target.(type) { - case PathScanner: - return scanPlanTextAnyToPathScanner{} - } - } - - return nil -} - -type scanPlanBinaryPathToPathScanner struct{} - -func (scanPlanBinaryPathToPathScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PathScanner) - - if src == nil { - return scanner.ScanPath(Path{}) - } - - if len(src) < 5 { - return fmt.Errorf("invalid length for Path: %v", len(src)) - } - - closed := src[0] == 1 - pointCount := int(binary.BigEndian.Uint32(src[1:])) - - rp := 5 - - if 5+pointCount*16 != len(src) { - return fmt.Errorf("invalid length for Path with %d points: %v", pointCount, len(src)) - } - - points := make([]Vec2, pointCount) - for i := 0; i < len(points); i++ { - x := binary.BigEndian.Uint64(src[rp:]) - rp += 8 - y := binary.BigEndian.Uint64(src[rp:]) - rp += 8 - points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)} - } - - return scanner.ScanPath(Path{ - P: points, - Closed: closed, - Valid: true, - }) -} - -type scanPlanTextAnyToPathScanner struct{} - -func (scanPlanTextAnyToPathScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PathScanner) - - if src == nil { - return scanner.ScanPath(Path{}) - } - - if len(src) < 7 { - return fmt.Errorf("invalid length for Path: %v", len(src)) - } - - closed := src[0] == '(' - points := make([]Vec2, 0) - - str := string(src[2:]) - - for { - end := strings.IndexByte(str, ',') - x, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+1:] - end = strings.IndexByte(str, ')') - - y, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - points = append(points, Vec2{x, y}) - - if end+3 < len(str) { - str = str[end+3:] - } else { - break - } - } - - return scanner.ScanPath(Path{P: points, Closed: closed, Valid: true}) -} - -func (c PathCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c PathCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var path Path - err := codecScan(c, m, oid, format, src, &path) - if err != nil { - return nil, err - } - return path, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go deleted file mode 100644 index f9d43edd7..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go +++ /dev/null @@ -1,2104 +0,0 @@ -package pgtype - -import ( - "database/sql" - "database/sql/driver" - "errors" - "fmt" - "net" - "net/netip" - "reflect" - "time" -) - -// PostgreSQL oids for common types -const ( - BoolOID = 16 - ByteaOID = 17 - QCharOID = 18 - NameOID = 19 - Int8OID = 20 - Int2OID = 21 - Int4OID = 23 - TextOID = 25 - OIDOID = 26 - TIDOID = 27 - XIDOID = 28 - CIDOID = 29 - JSONOID = 114 - XMLOID = 142 - XMLArrayOID = 143 - JSONArrayOID = 199 - XID8ArrayOID = 271 - PointOID = 600 - LsegOID = 601 - PathOID = 602 - BoxOID = 603 - PolygonOID = 604 - LineOID = 628 - LineArrayOID = 629 - CIDROID = 650 - CIDRArrayOID = 651 - Float4OID = 700 - Float8OID = 701 - CircleOID = 718 - CircleArrayOID = 719 - UnknownOID = 705 - Macaddr8OID = 774 - MacaddrOID = 829 - InetOID = 869 - BoolArrayOID = 1000 - QCharArrayOID = 1002 - NameArrayOID = 1003 - Int2ArrayOID = 1005 - Int4ArrayOID = 1007 - TextArrayOID = 1009 - TIDArrayOID = 1010 - ByteaArrayOID = 1001 - XIDArrayOID = 1011 - CIDArrayOID = 1012 - BPCharArrayOID = 1014 - VarcharArrayOID = 1015 - Int8ArrayOID = 1016 - PointArrayOID = 1017 - LsegArrayOID = 1018 - PathArrayOID = 1019 - BoxArrayOID = 1020 - Float4ArrayOID = 1021 - Float8ArrayOID = 1022 - PolygonArrayOID = 1027 - OIDArrayOID = 1028 - ACLItemOID = 1033 - ACLItemArrayOID = 1034 - MacaddrArrayOID = 1040 - InetArrayOID = 1041 - BPCharOID = 1042 - VarcharOID = 1043 - DateOID = 1082 - TimeOID = 1083 - TimestampOID = 1114 - TimestampArrayOID = 1115 - DateArrayOID = 1182 - TimeArrayOID = 1183 - TimestamptzOID = 1184 - TimestamptzArrayOID = 1185 - IntervalOID = 1186 - IntervalArrayOID = 1187 - NumericArrayOID = 1231 - TimetzOID = 1266 - TimetzArrayOID = 1270 - BitOID = 1560 - BitArrayOID = 1561 - VarbitOID = 1562 - VarbitArrayOID = 1563 - NumericOID = 1700 - RecordOID = 2249 - RecordArrayOID = 2287 - UUIDOID = 2950 - UUIDArrayOID = 2951 - JSONBOID = 3802 - JSONBArrayOID = 3807 - DaterangeOID = 3912 - DaterangeArrayOID = 3913 - Int4rangeOID = 3904 - Int4rangeArrayOID = 3905 - NumrangeOID = 3906 - NumrangeArrayOID = 3907 - TsrangeOID = 3908 - TsrangeArrayOID = 3909 - TstzrangeOID = 3910 - TstzrangeArrayOID = 3911 - Int8rangeOID = 3926 - Int8rangeArrayOID = 3927 - JSONPathOID = 4072 - JSONPathArrayOID = 4073 - Int4multirangeOID = 4451 - NummultirangeOID = 4532 - TsmultirangeOID = 4533 - TstzmultirangeOID = 4534 - DatemultirangeOID = 4535 - Int8multirangeOID = 4536 - XID8OID = 5069 - Int4multirangeArrayOID = 6150 - NummultirangeArrayOID = 6151 - TsmultirangeArrayOID = 6152 - TstzmultirangeArrayOID = 6153 - DatemultirangeArrayOID = 6155 - Int8multirangeArrayOID = 6157 -) - -type InfinityModifier int8 - -const ( - Infinity InfinityModifier = 1 - Finite InfinityModifier = 0 - NegativeInfinity InfinityModifier = -Infinity -) - -func (im InfinityModifier) String() string { - switch im { - case Finite: - return "finite" - case Infinity: - return "infinity" - case NegativeInfinity: - return "-infinity" - default: - return "invalid" - } -} - -// PostgreSQL format codes -const ( - TextFormatCode = 0 - BinaryFormatCode = 1 -) - -// A Codec converts between Go and PostgreSQL values. A Codec must not be mutated after it is registered with a Map. -type Codec interface { - // FormatSupported returns true if the format is supported. - FormatSupported(int16) bool - - // PreferredFormat returns the preferred format. - PreferredFormat() int16 - - // PlanEncode returns an EncodePlan for encoding value into PostgreSQL format for oid and format. If no plan can be - // found then nil is returned. - PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan - - // PlanScan returns a ScanPlan for scanning a PostgreSQL value into a destination with the same type as target. If - // no plan can be found then nil is returned. - PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan - - // DecodeDatabaseSQLValue returns src decoded into a value compatible with the sql.Scanner interface. - DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) - - // DecodeValue returns src decoded into its default format. - DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) -} - -type nullAssignmentError struct { - dst any -} - -func (e *nullAssignmentError) Error() string { - return fmt.Sprintf("cannot assign NULL to %T", e.dst) -} - -// Type represents a PostgreSQL data type. It must not be mutated after it is registered with a Map. -type Type struct { - Codec Codec - Name string - OID uint32 -} - -// Map is the mapping between PostgreSQL server types and Go type handling logic. It can encode values for -// transmission to a PostgreSQL server and scan received values. -type Map struct { - oidToType map[uint32]*Type - nameToType map[string]*Type - reflectTypeToName map[reflect.Type]string - oidToFormatCode map[uint32]int16 - - reflectTypeToType map[reflect.Type]*Type - - memoizedScanPlans map[uint32]map[reflect.Type][2]ScanPlan - memoizedEncodePlans map[uint32]map[reflect.Type][2]EncodePlan - - // TryWrapEncodePlanFuncs is a slice of functions that will wrap a value that cannot be encoded by the Codec. Every - // time a wrapper is found the PlanEncode method will be recursively called with the new value. This allows several layers of wrappers - // to be built up. There are default functions placed in this slice by NewMap(). In most cases these functions - // should run last. i.e. Additional functions should typically be prepended not appended. - TryWrapEncodePlanFuncs []TryWrapEncodePlanFunc - - // TryWrapScanPlanFuncs is a slice of functions that will wrap a target that cannot be scanned into by the Codec. Every - // time a wrapper is found the PlanScan method will be recursively called with the new target. This allows several layers of wrappers - // to be built up. There are default functions placed in this slice by NewMap(). In most cases these functions - // should run last. i.e. Additional functions should typically be prepended not appended. - TryWrapScanPlanFuncs []TryWrapScanPlanFunc -} - -// Copy returns a new Map containing the same registered types. -func (m *Map) Copy() *Map { - newMap := NewMap() - for _, type_ := range m.oidToType { - newMap.RegisterType(type_) - } - return newMap -} - -func NewMap() *Map { - defaultMapInitOnce.Do(initDefaultMap) - - return &Map{ - oidToType: make(map[uint32]*Type), - nameToType: make(map[string]*Type), - reflectTypeToName: make(map[reflect.Type]string), - oidToFormatCode: make(map[uint32]int16), - - memoizedScanPlans: make(map[uint32]map[reflect.Type][2]ScanPlan), - memoizedEncodePlans: make(map[uint32]map[reflect.Type][2]EncodePlan), - - TryWrapEncodePlanFuncs: []TryWrapEncodePlanFunc{ - TryWrapDerefPointerEncodePlan, - TryWrapBuiltinTypeEncodePlan, - TryWrapFindUnderlyingTypeEncodePlan, - TryWrapStructEncodePlan, - TryWrapSliceEncodePlan, - TryWrapMultiDimSliceEncodePlan, - TryWrapArrayEncodePlan, - }, - - TryWrapScanPlanFuncs: []TryWrapScanPlanFunc{ - TryPointerPointerScanPlan, - TryWrapBuiltinTypeScanPlan, - TryFindUnderlyingTypeScanPlan, - TryWrapStructScanPlan, - TryWrapPtrSliceScanPlan, - TryWrapPtrMultiDimSliceScanPlan, - TryWrapPtrArrayScanPlan, - }, - } -} - -// RegisterTypes registers multiple data types in the sequence they are provided. -func (m *Map) RegisterTypes(types []*Type) { - for _, t := range types { - m.RegisterType(t) - } -} - -// RegisterType registers a data type with the Map. t must not be mutated after it is registered. -func (m *Map) RegisterType(t *Type) { - m.oidToType[t.OID] = t - m.nameToType[t.Name] = t - m.oidToFormatCode[t.OID] = t.Codec.PreferredFormat() - - // Invalidated by type registration - m.reflectTypeToType = nil - for k := range m.memoizedScanPlans { - delete(m.memoizedScanPlans, k) - } - for k := range m.memoizedEncodePlans { - delete(m.memoizedEncodePlans, k) - } -} - -// RegisterDefaultPgType registers a mapping of a Go type to a PostgreSQL type name. Typically the data type to be -// encoded or decoded is determined by the PostgreSQL OID. But if the OID of a value to be encoded or decoded is -// unknown, this additional mapping will be used by TypeForValue to determine a suitable data type. -func (m *Map) RegisterDefaultPgType(value any, name string) { - m.reflectTypeToName[reflect.TypeOf(value)] = name - - // Invalidated by type registration - m.reflectTypeToType = nil - for k := range m.memoizedScanPlans { - delete(m.memoizedScanPlans, k) - } - for k := range m.memoizedEncodePlans { - delete(m.memoizedEncodePlans, k) - } -} - -// TypeForOID returns the Type registered for the given OID. The returned Type must not be mutated. -func (m *Map) TypeForOID(oid uint32) (*Type, bool) { - if dt, ok := m.oidToType[oid]; ok { - return dt, true - } - - dt, ok := defaultMap.oidToType[oid] - return dt, ok -} - -// TypeForName returns the Type registered for the given name. The returned Type must not be mutated. -func (m *Map) TypeForName(name string) (*Type, bool) { - if dt, ok := m.nameToType[name]; ok { - return dt, true - } - dt, ok := defaultMap.nameToType[name] - return dt, ok -} - -func (m *Map) buildReflectTypeToType() { - m.reflectTypeToType = make(map[reflect.Type]*Type) - - for reflectType, name := range m.reflectTypeToName { - if dt, ok := m.TypeForName(name); ok { - m.reflectTypeToType[reflectType] = dt - } - } -} - -// TypeForValue finds a data type suitable for v. Use RegisterType to register types that can encode and decode -// themselves. Use RegisterDefaultPgType to register that can be handled by a registered data type. The returned Type -// must not be mutated. -func (m *Map) TypeForValue(v any) (*Type, bool) { - if m.reflectTypeToType == nil { - m.buildReflectTypeToType() - } - - if dt, ok := m.reflectTypeToType[reflect.TypeOf(v)]; ok { - return dt, true - } - - dt, ok := defaultMap.reflectTypeToType[reflect.TypeOf(v)] - return dt, ok -} - -// FormatCodeForOID returns the preferred format code for type oid. If the type is not registered it returns the text -// format code. -func (m *Map) FormatCodeForOID(oid uint32) int16 { - if fc, ok := m.oidToFormatCode[oid]; ok { - return fc - } - - if fc, ok := defaultMap.oidToFormatCode[oid]; ok { - return fc - } - - return TextFormatCode -} - -// EncodePlan is a precompiled plan to encode a particular type into a particular OID and format. -type EncodePlan interface { - // Encode appends the encoded bytes of value to buf. If value is the SQL value NULL then append nothing and return - // (nil, nil). The caller of Encode is responsible for writing the correct NULL value or the length of the data - // written. - Encode(value any, buf []byte) (newBuf []byte, err error) -} - -// ScanPlan is a precompiled plan to scan into a type of destination. -type ScanPlan interface { - // Scan scans src into target. src is only valid during the call to Scan. The ScanPlan must not retain a reference to - // src. - Scan(src []byte, target any) error -} - -type scanPlanCodecSQLScanner struct { - c Codec - m *Map - oid uint32 - formatCode int16 -} - -func (plan *scanPlanCodecSQLScanner) Scan(src []byte, dst any) error { - value, err := plan.c.DecodeDatabaseSQLValue(plan.m, plan.oid, plan.formatCode, src) - if err != nil { - return err - } - - scanner := dst.(sql.Scanner) - return scanner.Scan(value) -} - -type scanPlanSQLScanner struct { - formatCode int16 -} - -func (plan *scanPlanSQLScanner) Scan(src []byte, dst any) error { - scanner := getSQLScanner(dst) - - if scanner == nil { - return fmt.Errorf("cannot scan into %T", dst) - } - - if src == nil { - // This is necessary because interface value []byte:nil does not equal nil:nil for the binary format path and the - // text format path would be converted to empty string. - return scanner.Scan(nil) - } else if plan.formatCode == BinaryFormatCode { - return scanner.Scan(src) - } else { - return scanner.Scan(string(src)) - } -} - -// we don't know if the target is a sql.Scanner or a pointer on a sql.Scanner, so we need to check recursively -func getSQLScanner(target any) sql.Scanner { - val := reflect.ValueOf(target) - for val.Kind() == reflect.Ptr { - if _, ok := val.Interface().(sql.Scanner); ok { - if val.IsNil() { - val.Set(reflect.New(val.Type().Elem())) - } - return val.Interface().(sql.Scanner) - } - val = val.Elem() - } - return nil -} - -type scanPlanString struct{} - -func (scanPlanString) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p := (dst).(*string) - *p = string(src) - return nil -} - -type scanPlanAnyTextToBytes struct{} - -func (scanPlanAnyTextToBytes) Scan(src []byte, dst any) error { - dstBuf := dst.(*[]byte) - if src == nil { - *dstBuf = nil - return nil - } - - *dstBuf = make([]byte, len(src)) - copy(*dstBuf, src) - return nil -} - -type scanPlanFail struct { - m *Map - oid uint32 - formatCode int16 -} - -func (plan *scanPlanFail) Scan(src []byte, dst any) error { - // If src is NULL it might be possible to scan into dst even though it is the types are not compatible. While this - // may seem to be a contrived case it can occur when selecting NULL directly. PostgreSQL assigns it the type of text. - // It would be surprising to the caller to have to cast the NULL (e.g. `select null::int`). So try to figure out a - // compatible data type for dst and scan with that. - // - // See https://github.com/jackc/pgx/issues/1326 - if src == nil { - // As a horrible hack try all types to find anything that can scan into dst. - for oid := range plan.m.oidToType { - // using planScan instead of Scan or PlanScan to avoid polluting the planned scan cache. - plan := plan.m.planScan(oid, plan.formatCode, dst, 0) - if _, ok := plan.(*scanPlanFail); !ok { - return plan.Scan(src, dst) - } - } - for oid := range defaultMap.oidToType { - if _, ok := plan.m.oidToType[oid]; !ok { - plan := plan.m.planScan(oid, plan.formatCode, dst, 0) - if _, ok := plan.(*scanPlanFail); !ok { - return plan.Scan(src, dst) - } - } - } - } - - var format string - switch plan.formatCode { - case TextFormatCode: - format = "text" - case BinaryFormatCode: - format = "binary" - default: - format = fmt.Sprintf("unknown %d", plan.formatCode) - } - - var dataTypeName string - if t, ok := plan.m.TypeForOID(plan.oid); ok { - dataTypeName = t.Name - } else { - dataTypeName = "unknown type" - } - - return fmt.Errorf("cannot scan %s (OID %d) in %v format into %T", dataTypeName, plan.oid, format, dst) -} - -// TryWrapScanPlanFunc is a function that tries to create a wrapper plan for target. If successful it returns a plan -// that will convert the target passed to Scan and then call the next plan. nextTarget is target as it will be converted -// by plan. It must be used to find another suitable ScanPlan. When it is found SetNext must be called on plan for it -// to be usabled. ok indicates if a suitable wrapper was found. -type TryWrapScanPlanFunc func(target any) (plan WrappedScanPlanNextSetter, nextTarget any, ok bool) - -type pointerPointerScanPlan struct { - dstType reflect.Type - next ScanPlan -} - -func (plan *pointerPointerScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *pointerPointerScanPlan) Scan(src []byte, dst any) error { - el := reflect.ValueOf(dst).Elem() - if src == nil { - el.Set(reflect.Zero(el.Type())) - return nil - } - - el.Set(reflect.New(el.Type().Elem())) - return plan.next.Scan(src, el.Interface()) -} - -// TryPointerPointerScanPlan handles a pointer to a pointer by setting the target to nil for SQL NULL and allocating and -// scanning for non-NULL. -func TryPointerPointerScanPlan(target any) (plan WrappedScanPlanNextSetter, nextTarget any, ok bool) { - if dstValue := reflect.ValueOf(target); dstValue.Kind() == reflect.Ptr { - elemValue := dstValue.Elem() - if elemValue.Kind() == reflect.Ptr { - plan = &pointerPointerScanPlan{dstType: dstValue.Type()} - return plan, reflect.Zero(elemValue.Type()).Interface(), true - } - } - - return nil, nil, false -} - -// SkipUnderlyingTypePlanner prevents PlanScan and PlanDecode from trying to use the underlying type. -type SkipUnderlyingTypePlanner interface { - SkipUnderlyingTypePlan() -} - -var elemKindToPointerTypes map[reflect.Kind]reflect.Type = map[reflect.Kind]reflect.Type{ - reflect.Int: reflect.TypeOf(new(int)), - reflect.Int8: reflect.TypeOf(new(int8)), - reflect.Int16: reflect.TypeOf(new(int16)), - reflect.Int32: reflect.TypeOf(new(int32)), - reflect.Int64: reflect.TypeOf(new(int64)), - reflect.Uint: reflect.TypeOf(new(uint)), - reflect.Uint8: reflect.TypeOf(new(uint8)), - reflect.Uint16: reflect.TypeOf(new(uint16)), - reflect.Uint32: reflect.TypeOf(new(uint32)), - reflect.Uint64: reflect.TypeOf(new(uint64)), - reflect.Float32: reflect.TypeOf(new(float32)), - reflect.Float64: reflect.TypeOf(new(float64)), - reflect.String: reflect.TypeOf(new(string)), - reflect.Bool: reflect.TypeOf(new(bool)), -} - -type underlyingTypeScanPlan struct { - dstType reflect.Type - nextDstType reflect.Type - next ScanPlan -} - -func (plan *underlyingTypeScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *underlyingTypeScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, reflect.ValueOf(dst).Convert(plan.nextDstType).Interface()) -} - -// TryFindUnderlyingTypeScanPlan tries to convert to a Go builtin type. e.g. If value was of type MyString and -// MyString was defined as a string then a wrapper plan would be returned that converts MyString to string. -func TryFindUnderlyingTypeScanPlan(dst any) (plan WrappedScanPlanNextSetter, nextDst any, ok bool) { - if _, ok := dst.(SkipUnderlyingTypePlanner); ok { - return nil, nil, false - } - - dstValue := reflect.ValueOf(dst) - - if dstValue.Kind() == reflect.Ptr { - var elemValue reflect.Value - if dstValue.IsNil() { - elemValue = reflect.New(dstValue.Type().Elem()).Elem() - } else { - elemValue = dstValue.Elem() - } - nextDstType := elemKindToPointerTypes[elemValue.Kind()] - if nextDstType == nil { - if elemValue.Kind() == reflect.Slice { - if elemValue.Type().Elem().Kind() == reflect.Uint8 { - var v *[]byte - nextDstType = reflect.TypeOf(v) - } - } - - // Get underlying type of any array. - // https://github.com/jackc/pgx/issues/2107 - if elemValue.Kind() == reflect.Array { - nextDstType = reflect.PointerTo(reflect.ArrayOf(elemValue.Len(), elemValue.Type().Elem())) - } - } - - if nextDstType != nil && dstValue.Type() != nextDstType && dstValue.CanConvert(nextDstType) { - return &underlyingTypeScanPlan{dstType: dstValue.Type(), nextDstType: nextDstType}, dstValue.Convert(nextDstType).Interface(), true - } - } - - return nil, nil, false -} - -type WrappedScanPlanNextSetter interface { - SetNext(ScanPlan) - ScanPlan -} - -// TryWrapBuiltinTypeScanPlan tries to wrap a builtin type with a wrapper that provides additional methods. e.g. If -// value was of type int32 then a wrapper plan would be returned that converts target to a value that implements -// Int64Scanner. -func TryWrapBuiltinTypeScanPlan(target any) (plan WrappedScanPlanNextSetter, nextDst any, ok bool) { - switch target := target.(type) { - case *int8: - return &wrapInt8ScanPlan{}, (*int8Wrapper)(target), true - case *int16: - return &wrapInt16ScanPlan{}, (*int16Wrapper)(target), true - case *int32: - return &wrapInt32ScanPlan{}, (*int32Wrapper)(target), true - case *int64: - return &wrapInt64ScanPlan{}, (*int64Wrapper)(target), true - case *int: - return &wrapIntScanPlan{}, (*intWrapper)(target), true - case *uint8: - return &wrapUint8ScanPlan{}, (*uint8Wrapper)(target), true - case *uint16: - return &wrapUint16ScanPlan{}, (*uint16Wrapper)(target), true - case *uint32: - return &wrapUint32ScanPlan{}, (*uint32Wrapper)(target), true - case *uint64: - return &wrapUint64ScanPlan{}, (*uint64Wrapper)(target), true - case *uint: - return &wrapUintScanPlan{}, (*uintWrapper)(target), true - case *float32: - return &wrapFloat32ScanPlan{}, (*float32Wrapper)(target), true - case *float64: - return &wrapFloat64ScanPlan{}, (*float64Wrapper)(target), true - case *string: - return &wrapStringScanPlan{}, (*stringWrapper)(target), true - case *time.Time: - return &wrapTimeScanPlan{}, (*timeWrapper)(target), true - case *time.Duration: - return &wrapDurationScanPlan{}, (*durationWrapper)(target), true - case *net.IPNet: - return &wrapNetIPNetScanPlan{}, (*netIPNetWrapper)(target), true - case *net.IP: - return &wrapNetIPScanPlan{}, (*netIPWrapper)(target), true - case *netip.Prefix: - return &wrapNetipPrefixScanPlan{}, (*netipPrefixWrapper)(target), true - case *netip.Addr: - return &wrapNetipAddrScanPlan{}, (*netipAddrWrapper)(target), true - case *map[string]*string: - return &wrapMapStringToPointerStringScanPlan{}, (*mapStringToPointerStringWrapper)(target), true - case *map[string]string: - return &wrapMapStringToStringScanPlan{}, (*mapStringToStringWrapper)(target), true - case *[16]byte: - return &wrapByte16ScanPlan{}, (*byte16Wrapper)(target), true - case *[]byte: - return &wrapByteSliceScanPlan{}, (*byteSliceWrapper)(target), true - } - - return nil, nil, false -} - -type wrapInt8ScanPlan struct { - next ScanPlan -} - -func (plan *wrapInt8ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapInt8ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*int8Wrapper)(dst.(*int8))) -} - -type wrapInt16ScanPlan struct { - next ScanPlan -} - -func (plan *wrapInt16ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapInt16ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*int16Wrapper)(dst.(*int16))) -} - -type wrapInt32ScanPlan struct { - next ScanPlan -} - -func (plan *wrapInt32ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapInt32ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*int32Wrapper)(dst.(*int32))) -} - -type wrapInt64ScanPlan struct { - next ScanPlan -} - -func (plan *wrapInt64ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapInt64ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*int64Wrapper)(dst.(*int64))) -} - -type wrapIntScanPlan struct { - next ScanPlan -} - -func (plan *wrapIntScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapIntScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*intWrapper)(dst.(*int))) -} - -type wrapUint8ScanPlan struct { - next ScanPlan -} - -func (plan *wrapUint8ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapUint8ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*uint8Wrapper)(dst.(*uint8))) -} - -type wrapUint16ScanPlan struct { - next ScanPlan -} - -func (plan *wrapUint16ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapUint16ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*uint16Wrapper)(dst.(*uint16))) -} - -type wrapUint32ScanPlan struct { - next ScanPlan -} - -func (plan *wrapUint32ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapUint32ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*uint32Wrapper)(dst.(*uint32))) -} - -type wrapUint64ScanPlan struct { - next ScanPlan -} - -func (plan *wrapUint64ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapUint64ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*uint64Wrapper)(dst.(*uint64))) -} - -type wrapUintScanPlan struct { - next ScanPlan -} - -func (plan *wrapUintScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapUintScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*uintWrapper)(dst.(*uint))) -} - -type wrapFloat32ScanPlan struct { - next ScanPlan -} - -func (plan *wrapFloat32ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapFloat32ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*float32Wrapper)(dst.(*float32))) -} - -type wrapFloat64ScanPlan struct { - next ScanPlan -} - -func (plan *wrapFloat64ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapFloat64ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*float64Wrapper)(dst.(*float64))) -} - -type wrapStringScanPlan struct { - next ScanPlan -} - -func (plan *wrapStringScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapStringScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*stringWrapper)(dst.(*string))) -} - -type wrapTimeScanPlan struct { - next ScanPlan -} - -func (plan *wrapTimeScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapTimeScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*timeWrapper)(dst.(*time.Time))) -} - -type wrapDurationScanPlan struct { - next ScanPlan -} - -func (plan *wrapDurationScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapDurationScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*durationWrapper)(dst.(*time.Duration))) -} - -type wrapNetIPNetScanPlan struct { - next ScanPlan -} - -func (plan *wrapNetIPNetScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapNetIPNetScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*netIPNetWrapper)(dst.(*net.IPNet))) -} - -type wrapNetIPScanPlan struct { - next ScanPlan -} - -func (plan *wrapNetIPScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapNetIPScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*netIPWrapper)(dst.(*net.IP))) -} - -type wrapNetipPrefixScanPlan struct { - next ScanPlan -} - -func (plan *wrapNetipPrefixScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapNetipPrefixScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*netipPrefixWrapper)(dst.(*netip.Prefix))) -} - -type wrapNetipAddrScanPlan struct { - next ScanPlan -} - -func (plan *wrapNetipAddrScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapNetipAddrScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*netipAddrWrapper)(dst.(*netip.Addr))) -} - -type wrapMapStringToPointerStringScanPlan struct { - next ScanPlan -} - -func (plan *wrapMapStringToPointerStringScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapMapStringToPointerStringScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*mapStringToPointerStringWrapper)(dst.(*map[string]*string))) -} - -type wrapMapStringToStringScanPlan struct { - next ScanPlan -} - -func (plan *wrapMapStringToStringScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapMapStringToStringScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*mapStringToStringWrapper)(dst.(*map[string]string))) -} - -type wrapByte16ScanPlan struct { - next ScanPlan -} - -func (plan *wrapByte16ScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapByte16ScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*byte16Wrapper)(dst.(*[16]byte))) -} - -type wrapByteSliceScanPlan struct { - next ScanPlan -} - -func (plan *wrapByteSliceScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapByteSliceScanPlan) Scan(src []byte, dst any) error { - return plan.next.Scan(src, (*byteSliceWrapper)(dst.(*[]byte))) -} - -type pointerEmptyInterfaceScanPlan struct { - codec Codec - m *Map - oid uint32 - formatCode int16 -} - -func (plan *pointerEmptyInterfaceScanPlan) Scan(src []byte, dst any) error { - value, err := plan.codec.DecodeValue(plan.m, plan.oid, plan.formatCode, src) - if err != nil { - return err - } - - ptrAny := dst.(*any) - *ptrAny = value - - return nil -} - -// TryWrapStructPlan tries to wrap a struct with a wrapper that implements CompositeIndexGetter. -func TryWrapStructScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { - targetValue := reflect.ValueOf(target) - if targetValue.Kind() != reflect.Ptr { - return nil, nil, false - } - - var targetElemValue reflect.Value - if targetValue.IsNil() { - targetElemValue = reflect.Zero(targetValue.Type().Elem()) - } else { - targetElemValue = targetValue.Elem() - } - targetElemType := targetElemValue.Type() - - if targetElemType.Kind() == reflect.Struct { - exportedFields := getExportedFieldValues(targetElemValue) - if len(exportedFields) == 0 { - return nil, nil, false - } - - w := ptrStructWrapper{ - s: target, - exportedFields: exportedFields, - } - return &wrapAnyPtrStructScanPlan{}, &w, true - } - - return nil, nil, false -} - -type wrapAnyPtrStructScanPlan struct { - next ScanPlan -} - -func (plan *wrapAnyPtrStructScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapAnyPtrStructScanPlan) Scan(src []byte, target any) error { - w := ptrStructWrapper{ - s: target, - exportedFields: getExportedFieldValues(reflect.ValueOf(target).Elem()), - } - - return plan.next.Scan(src, &w) -} - -// TryWrapPtrSliceScanPlan tries to wrap a pointer to a single dimension slice. -func TryWrapPtrSliceScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { - // Avoid using reflect path for common types. - switch target := target.(type) { - case *[]int16: - return &wrapPtrSliceScanPlan[int16]{}, (*FlatArray[int16])(target), true - case *[]int32: - return &wrapPtrSliceScanPlan[int32]{}, (*FlatArray[int32])(target), true - case *[]int64: - return &wrapPtrSliceScanPlan[int64]{}, (*FlatArray[int64])(target), true - case *[]float32: - return &wrapPtrSliceScanPlan[float32]{}, (*FlatArray[float32])(target), true - case *[]float64: - return &wrapPtrSliceScanPlan[float64]{}, (*FlatArray[float64])(target), true - case *[]string: - return &wrapPtrSliceScanPlan[string]{}, (*FlatArray[string])(target), true - case *[]time.Time: - return &wrapPtrSliceScanPlan[time.Time]{}, (*FlatArray[time.Time])(target), true - } - - targetType := reflect.TypeOf(target) - if targetType.Kind() != reflect.Ptr { - return nil, nil, false - } - - targetElemType := targetType.Elem() - - if targetElemType.Kind() == reflect.Slice { - slice := reflect.New(targetElemType).Elem() - return &wrapPtrSliceReflectScanPlan{}, &anySliceArrayReflect{slice: slice}, true - } - return nil, nil, false -} - -type wrapPtrSliceScanPlan[T any] struct { - next ScanPlan -} - -func (plan *wrapPtrSliceScanPlan[T]) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapPtrSliceScanPlan[T]) Scan(src []byte, target any) error { - return plan.next.Scan(src, (*FlatArray[T])(target.(*[]T))) -} - -type wrapPtrSliceReflectScanPlan struct { - next ScanPlan -} - -func (plan *wrapPtrSliceReflectScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapPtrSliceReflectScanPlan) Scan(src []byte, target any) error { - return plan.next.Scan(src, &anySliceArrayReflect{slice: reflect.ValueOf(target).Elem()}) -} - -// TryWrapPtrMultiDimSliceScanPlan tries to wrap a pointer to a multi-dimension slice. -func TryWrapPtrMultiDimSliceScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { - targetValue := reflect.ValueOf(target) - if targetValue.Kind() != reflect.Ptr { - return nil, nil, false - } - - targetElemValue := targetValue.Elem() - - if targetElemValue.Kind() == reflect.Slice { - elemElemKind := targetElemValue.Type().Elem().Kind() - if elemElemKind == reflect.Slice { - if !isRagged(targetElemValue) { - return &wrapPtrMultiDimSliceScanPlan{}, &anyMultiDimSliceArray{slice: targetValue.Elem()}, true - } - } - } - - return nil, nil, false -} - -type wrapPtrMultiDimSliceScanPlan struct { - next ScanPlan -} - -func (plan *wrapPtrMultiDimSliceScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapPtrMultiDimSliceScanPlan) Scan(src []byte, target any) error { - return plan.next.Scan(src, &anyMultiDimSliceArray{slice: reflect.ValueOf(target).Elem()}) -} - -// TryWrapPtrArrayScanPlan tries to wrap a pointer to a single dimension array. -func TryWrapPtrArrayScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { - targetValue := reflect.ValueOf(target) - if targetValue.Kind() != reflect.Ptr { - return nil, nil, false - } - - targetElemValue := targetValue.Elem() - - if targetElemValue.Kind() == reflect.Array { - return &wrapPtrArrayReflectScanPlan{}, &anyArrayArrayReflect{array: targetElemValue}, true - } - return nil, nil, false -} - -type wrapPtrArrayReflectScanPlan struct { - next ScanPlan -} - -func (plan *wrapPtrArrayReflectScanPlan) SetNext(next ScanPlan) { plan.next = next } - -func (plan *wrapPtrArrayReflectScanPlan) Scan(src []byte, target any) error { - return plan.next.Scan(src, &anyArrayArrayReflect{array: reflect.ValueOf(target).Elem()}) -} - -// PlanScan prepares a plan to scan a value into target. -func (m *Map) PlanScan(oid uint32, formatCode int16, target any) ScanPlan { - return m.planScanDepth(oid, formatCode, target, 0) -} - -func (m *Map) planScanDepth(oid uint32, formatCode int16, target any, depth int) ScanPlan { - if depth > 8 { - return &scanPlanFail{m: m, oid: oid, formatCode: formatCode} - } - - oidMemo := m.memoizedScanPlans[oid] - if oidMemo == nil { - oidMemo = make(map[reflect.Type][2]ScanPlan) - m.memoizedScanPlans[oid] = oidMemo - } - targetReflectType := reflect.TypeOf(target) - typeMemo := oidMemo[targetReflectType] - plan := typeMemo[formatCode] - if plan == nil { - plan = m.planScan(oid, formatCode, target, depth) - typeMemo[formatCode] = plan - oidMemo[targetReflectType] = typeMemo - } - - return plan -} - -func (m *Map) planScan(oid uint32, formatCode int16, target any, depth int) ScanPlan { - if target == nil { - return &scanPlanFail{m: m, oid: oid, formatCode: formatCode} - } - - if _, ok := target.(*UndecodedBytes); ok { - return scanPlanAnyToUndecodedBytes{} - } - - switch formatCode { - case BinaryFormatCode: - switch target.(type) { - case *string: - switch oid { - case TextOID, VarcharOID: - return scanPlanString{} - } - } - case TextFormatCode: - switch target.(type) { - case *string: - return scanPlanString{} - case *[]byte: - if oid != ByteaOID { - return scanPlanAnyTextToBytes{} - } - case TextScanner: - return scanPlanTextAnyToTextScanner{} - } - } - - var dt *Type - - if dataType, ok := m.TypeForOID(oid); ok { - dt = dataType - } else if dataType, ok := m.TypeForValue(target); ok { - dt = dataType - oid = dt.OID // Preserve assumed OID in case we are recursively called below. - } - - if dt != nil { - if plan := dt.Codec.PlanScan(m, oid, formatCode, target); plan != nil { - return plan - } - } - - // This needs to happen before trying m.TryWrapScanPlanFuncs. Otherwise, a sql.Scanner would not get called if it was - // defined on a type that could be unwrapped such as `type myString string`. - // - // https://github.com/jackc/pgtype/issues/197 - if _, ok := target.(sql.Scanner); ok { - if dt == nil { - return &scanPlanSQLScanner{formatCode: formatCode} - } else { - return &scanPlanCodecSQLScanner{c: dt.Codec, m: m, oid: oid, formatCode: formatCode} - } - } - - for _, f := range m.TryWrapScanPlanFuncs { - if wrapperPlan, nextDst, ok := f(target); ok { - if nextPlan := m.planScanDepth(oid, formatCode, nextDst, depth+1); nextPlan != nil { - if _, failed := nextPlan.(*scanPlanFail); !failed { - wrapperPlan.SetNext(nextPlan) - return wrapperPlan - } - } - } - } - - if dt != nil { - if _, ok := target.(*any); ok { - return &pointerEmptyInterfaceScanPlan{codec: dt.Codec, m: m, oid: oid, formatCode: formatCode} - } - } - - return &scanPlanFail{m: m, oid: oid, formatCode: formatCode} -} - -func (m *Map) Scan(oid uint32, formatCode int16, src []byte, dst any) error { - if dst == nil { - return nil - } - - plan := m.PlanScan(oid, formatCode, dst) - return plan.Scan(src, dst) -} - -var ErrScanTargetTypeChanged = errors.New("scan target type changed") - -func codecScan(codec Codec, m *Map, oid uint32, format int16, src []byte, dst any) error { - scanPlan := codec.PlanScan(m, oid, format, dst) - if scanPlan == nil { - return fmt.Errorf("PlanScan did not find a plan") - } - return scanPlan.Scan(src, dst) -} - -func codecDecodeToTextFormat(codec Codec, m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - if format == TextFormatCode { - return string(src), nil - } else { - value, err := codec.DecodeValue(m, oid, format, src) - if err != nil { - return nil, err - } - buf, err := m.Encode(oid, TextFormatCode, value, nil) - if err != nil { - return nil, err - } - return string(buf), nil - } -} - -// PlanEncode returns an Encode plan for encoding value into PostgreSQL format for oid and format. If no plan can be -// found then nil is returned. -func (m *Map) PlanEncode(oid uint32, format int16, value any) EncodePlan { - return m.planEncodeDepth(oid, format, value, 0) -} - -func (m *Map) planEncodeDepth(oid uint32, format int16, value any, depth int) EncodePlan { - // Guard against infinite recursion. - if depth > 8 { - return nil - } - - oidMemo := m.memoizedEncodePlans[oid] - if oidMemo == nil { - oidMemo = make(map[reflect.Type][2]EncodePlan) - m.memoizedEncodePlans[oid] = oidMemo - } - targetReflectType := reflect.TypeOf(value) - typeMemo := oidMemo[targetReflectType] - plan := typeMemo[format] - if plan == nil { - plan = m.planEncode(oid, format, value, depth) - typeMemo[format] = plan - oidMemo[targetReflectType] = typeMemo - } - - return plan -} - -func (m *Map) planEncode(oid uint32, format int16, value any, depth int) EncodePlan { - if format == TextFormatCode { - switch value.(type) { - case string: - return encodePlanStringToAnyTextFormat{} - case TextValuer: - return encodePlanTextValuerToAnyTextFormat{} - } - } - - var dt *Type - if dataType, ok := m.TypeForOID(oid); ok { - dt = dataType - } else { - // If no type for the OID was found, then either it is unknowable (e.g. the simple protocol) or it is an - // unregistered type. In either case try to find the type and OID that matches the value (e.g. a []byte would be - // registered to PostgreSQL bytea). - if dataType, ok := m.TypeForValue(value); ok { - dt = dataType - oid = dt.OID // Preserve assumed OID in case we are recursively called below. - } - } - - if dt != nil { - if plan := dt.Codec.PlanEncode(m, oid, format, value); plan != nil { - return plan - } - } - - for _, f := range m.TryWrapEncodePlanFuncs { - if wrapperPlan, nextValue, ok := f(value); ok { - if nextPlan := m.planEncodeDepth(oid, format, nextValue, depth+1); nextPlan != nil { - wrapperPlan.SetNext(nextPlan) - return wrapperPlan - } - } - } - - if _, ok := value.(driver.Valuer); ok { - return &encodePlanDriverValuer{m: m, oid: oid, formatCode: format} - } - - return nil -} - -type encodePlanStringToAnyTextFormat struct{} - -func (encodePlanStringToAnyTextFormat) Encode(value any, buf []byte) (newBuf []byte, err error) { - s := value.(string) - return append(buf, s...), nil -} - -type encodePlanTextValuerToAnyTextFormat struct{} - -func (encodePlanTextValuerToAnyTextFormat) Encode(value any, buf []byte) (newBuf []byte, err error) { - t, err := value.(TextValuer).TextValue() - if err != nil { - return nil, err - } - if !t.Valid { - return nil, nil - } - - return append(buf, t.String...), nil -} - -type encodePlanDriverValuer struct { - m *Map - oid uint32 - formatCode int16 -} - -func (plan *encodePlanDriverValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - dv := value.(driver.Valuer) - if dv == nil { - return nil, nil - } - v, err := dv.Value() - if err != nil { - return nil, err - } - if v == nil { - return nil, nil - } - - newBuf, err = plan.m.Encode(plan.oid, plan.formatCode, v, buf) - if err == nil { - return newBuf, nil - } - - s, ok := v.(string) - if !ok { - return nil, err - } - - var scannedValue any - scanErr := plan.m.Scan(plan.oid, TextFormatCode, []byte(s), &scannedValue) - if scanErr != nil { - return nil, err - } - - // Prevent infinite loop. We can't encode this. See https://github.com/jackc/pgx/issues/1331. - if reflect.TypeOf(value) == reflect.TypeOf(scannedValue) { - return nil, fmt.Errorf("tried to encode %v via encoding to text and scanning but failed due to receiving same type back", value) - } - - var err2 error - newBuf, err2 = plan.m.Encode(plan.oid, BinaryFormatCode, scannedValue, buf) - if err2 != nil { - return nil, err - } - - return newBuf, nil -} - -// TryWrapEncodePlanFunc is a function that tries to create a wrapper plan for value. If successful it returns a plan -// that will convert the value passed to Encode and then call the next plan. nextValue is value as it will be converted -// by plan. It must be used to find another suitable EncodePlan. When it is found SetNext must be called on plan for it -// to be usabled. ok indicates if a suitable wrapper was found. -type TryWrapEncodePlanFunc func(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) - -type derefPointerEncodePlan struct { - next EncodePlan -} - -func (plan *derefPointerEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *derefPointerEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - ptr := reflect.ValueOf(value) - - if ptr.IsNil() { - return nil, nil - } - - return plan.next.Encode(ptr.Elem().Interface(), buf) -} - -// TryWrapDerefPointerEncodePlan tries to dereference a pointer. e.g. If value was of type *string then a wrapper plan -// would be returned that dereferences the value. -func TryWrapDerefPointerEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { - if _, ok := value.(driver.Valuer); ok { - return nil, nil, false - } - - if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Ptr { - return &derefPointerEncodePlan{}, reflect.New(valueType.Elem()).Elem().Interface(), true - } - - return nil, nil, false -} - -var kindToTypes map[reflect.Kind]reflect.Type = map[reflect.Kind]reflect.Type{ - reflect.Int: reflect.TypeOf(int(0)), - reflect.Int8: reflect.TypeOf(int8(0)), - reflect.Int16: reflect.TypeOf(int16(0)), - reflect.Int32: reflect.TypeOf(int32(0)), - reflect.Int64: reflect.TypeOf(int64(0)), - reflect.Uint: reflect.TypeOf(uint(0)), - reflect.Uint8: reflect.TypeOf(uint8(0)), - reflect.Uint16: reflect.TypeOf(uint16(0)), - reflect.Uint32: reflect.TypeOf(uint32(0)), - reflect.Uint64: reflect.TypeOf(uint64(0)), - reflect.Float32: reflect.TypeOf(float32(0)), - reflect.Float64: reflect.TypeOf(float64(0)), - reflect.String: reflect.TypeOf(""), - reflect.Bool: reflect.TypeOf(false), -} - -var byteSliceType = reflect.TypeOf([]byte{}) - -type underlyingTypeEncodePlan struct { - nextValueType reflect.Type - next EncodePlan -} - -func (plan *underlyingTypeEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *underlyingTypeEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(reflect.ValueOf(value).Convert(plan.nextValueType).Interface(), buf) -} - -// TryWrapFindUnderlyingTypeEncodePlan tries to convert to a Go builtin type. e.g. If value was of type MyString and -// MyString was defined as a string then a wrapper plan would be returned that converts MyString to string. -func TryWrapFindUnderlyingTypeEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { - if value == nil { - return nil, nil, false - } - - if _, ok := value.(driver.Valuer); ok { - return nil, nil, false - } - - if _, ok := value.(SkipUnderlyingTypePlanner); ok { - return nil, nil, false - } - - refValue := reflect.ValueOf(value) - - nextValueType := kindToTypes[refValue.Kind()] - if nextValueType != nil && refValue.Type() != nextValueType { - return &underlyingTypeEncodePlan{nextValueType: nextValueType}, refValue.Convert(nextValueType).Interface(), true - } - - // []byte is a special case. It is a slice but we treat it as a scalar type. In the case of a named type like - // json.RawMessage which is defined as []byte the underlying type should be considered as []byte. But any other slice - // does not have a special underlying type. - // - // https://github.com/jackc/pgx/issues/1763 - if refValue.Type() != byteSliceType && refValue.Type().AssignableTo(byteSliceType) { - return &underlyingTypeEncodePlan{nextValueType: byteSliceType}, refValue.Convert(byteSliceType).Interface(), true - } - - // Get underlying type of any array. - // https://github.com/jackc/pgx/issues/2107 - if refValue.Kind() == reflect.Array { - underlyingArrayType := reflect.ArrayOf(refValue.Len(), refValue.Type().Elem()) - if refValue.Type() != underlyingArrayType { - return &underlyingTypeEncodePlan{nextValueType: underlyingArrayType}, refValue.Convert(underlyingArrayType).Interface(), true - } - } - - return nil, nil, false -} - -type WrappedEncodePlanNextSetter interface { - SetNext(EncodePlan) - EncodePlan -} - -// TryWrapBuiltinTypeEncodePlan tries to wrap a builtin type with a wrapper that provides additional methods. e.g. If -// value was of type int32 then a wrapper plan would be returned that converts value to a type that implements -// Int64Valuer. -func TryWrapBuiltinTypeEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { - if _, ok := value.(driver.Valuer); ok { - return nil, nil, false - } - - switch value := value.(type) { - case int8: - return &wrapInt8EncodePlan{}, int8Wrapper(value), true - case int16: - return &wrapInt16EncodePlan{}, int16Wrapper(value), true - case int32: - return &wrapInt32EncodePlan{}, int32Wrapper(value), true - case int64: - return &wrapInt64EncodePlan{}, int64Wrapper(value), true - case int: - return &wrapIntEncodePlan{}, intWrapper(value), true - case uint8: - return &wrapUint8EncodePlan{}, uint8Wrapper(value), true - case uint16: - return &wrapUint16EncodePlan{}, uint16Wrapper(value), true - case uint32: - return &wrapUint32EncodePlan{}, uint32Wrapper(value), true - case uint64: - return &wrapUint64EncodePlan{}, uint64Wrapper(value), true - case uint: - return &wrapUintEncodePlan{}, uintWrapper(value), true - case float32: - return &wrapFloat32EncodePlan{}, float32Wrapper(value), true - case float64: - return &wrapFloat64EncodePlan{}, float64Wrapper(value), true - case string: - return &wrapStringEncodePlan{}, stringWrapper(value), true - case time.Time: - return &wrapTimeEncodePlan{}, timeWrapper(value), true - case time.Duration: - return &wrapDurationEncodePlan{}, durationWrapper(value), true - case net.IPNet: - return &wrapNetIPNetEncodePlan{}, netIPNetWrapper(value), true - case net.IP: - return &wrapNetIPEncodePlan{}, netIPWrapper(value), true - case netip.Prefix: - return &wrapNetipPrefixEncodePlan{}, netipPrefixWrapper(value), true - case netip.Addr: - return &wrapNetipAddrEncodePlan{}, netipAddrWrapper(value), true - case map[string]*string: - return &wrapMapStringToPointerStringEncodePlan{}, mapStringToPointerStringWrapper(value), true - case map[string]string: - return &wrapMapStringToStringEncodePlan{}, mapStringToStringWrapper(value), true - case [16]byte: - return &wrapByte16EncodePlan{}, byte16Wrapper(value), true - case []byte: - return &wrapByteSliceEncodePlan{}, byteSliceWrapper(value), true - case fmt.Stringer: - return &wrapFmtStringerEncodePlan{}, fmtStringerWrapper{value}, true - } - - return nil, nil, false -} - -type wrapInt8EncodePlan struct { - next EncodePlan -} - -func (plan *wrapInt8EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapInt8EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(int8Wrapper(value.(int8)), buf) -} - -type wrapInt16EncodePlan struct { - next EncodePlan -} - -func (plan *wrapInt16EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapInt16EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(int16Wrapper(value.(int16)), buf) -} - -type wrapInt32EncodePlan struct { - next EncodePlan -} - -func (plan *wrapInt32EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapInt32EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(int32Wrapper(value.(int32)), buf) -} - -type wrapInt64EncodePlan struct { - next EncodePlan -} - -func (plan *wrapInt64EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapInt64EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(int64Wrapper(value.(int64)), buf) -} - -type wrapIntEncodePlan struct { - next EncodePlan -} - -func (plan *wrapIntEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapIntEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(intWrapper(value.(int)), buf) -} - -type wrapUint8EncodePlan struct { - next EncodePlan -} - -func (plan *wrapUint8EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapUint8EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(uint8Wrapper(value.(uint8)), buf) -} - -type wrapUint16EncodePlan struct { - next EncodePlan -} - -func (plan *wrapUint16EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapUint16EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(uint16Wrapper(value.(uint16)), buf) -} - -type wrapUint32EncodePlan struct { - next EncodePlan -} - -func (plan *wrapUint32EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapUint32EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(uint32Wrapper(value.(uint32)), buf) -} - -type wrapUint64EncodePlan struct { - next EncodePlan -} - -func (plan *wrapUint64EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapUint64EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(uint64Wrapper(value.(uint64)), buf) -} - -type wrapUintEncodePlan struct { - next EncodePlan -} - -func (plan *wrapUintEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapUintEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(uintWrapper(value.(uint)), buf) -} - -type wrapFloat32EncodePlan struct { - next EncodePlan -} - -func (plan *wrapFloat32EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapFloat32EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(float32Wrapper(value.(float32)), buf) -} - -type wrapFloat64EncodePlan struct { - next EncodePlan -} - -func (plan *wrapFloat64EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapFloat64EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(float64Wrapper(value.(float64)), buf) -} - -type wrapStringEncodePlan struct { - next EncodePlan -} - -func (plan *wrapStringEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapStringEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(stringWrapper(value.(string)), buf) -} - -type wrapTimeEncodePlan struct { - next EncodePlan -} - -func (plan *wrapTimeEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapTimeEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(timeWrapper(value.(time.Time)), buf) -} - -type wrapDurationEncodePlan struct { - next EncodePlan -} - -func (plan *wrapDurationEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapDurationEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(durationWrapper(value.(time.Duration)), buf) -} - -type wrapNetIPNetEncodePlan struct { - next EncodePlan -} - -func (plan *wrapNetIPNetEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapNetIPNetEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(netIPNetWrapper(value.(net.IPNet)), buf) -} - -type wrapNetIPEncodePlan struct { - next EncodePlan -} - -func (plan *wrapNetIPEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapNetIPEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(netIPWrapper(value.(net.IP)), buf) -} - -type wrapNetipPrefixEncodePlan struct { - next EncodePlan -} - -func (plan *wrapNetipPrefixEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapNetipPrefixEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(netipPrefixWrapper(value.(netip.Prefix)), buf) -} - -type wrapNetipAddrEncodePlan struct { - next EncodePlan -} - -func (plan *wrapNetipAddrEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapNetipAddrEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(netipAddrWrapper(value.(netip.Addr)), buf) -} - -type wrapMapStringToPointerStringEncodePlan struct { - next EncodePlan -} - -func (plan *wrapMapStringToPointerStringEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapMapStringToPointerStringEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(mapStringToPointerStringWrapper(value.(map[string]*string)), buf) -} - -type wrapMapStringToStringEncodePlan struct { - next EncodePlan -} - -func (plan *wrapMapStringToStringEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapMapStringToStringEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(mapStringToStringWrapper(value.(map[string]string)), buf) -} - -type wrapByte16EncodePlan struct { - next EncodePlan -} - -func (plan *wrapByte16EncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapByte16EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(byte16Wrapper(value.([16]byte)), buf) -} - -type wrapByteSliceEncodePlan struct { - next EncodePlan -} - -func (plan *wrapByteSliceEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapByteSliceEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(byteSliceWrapper(value.([]byte)), buf) -} - -type wrapFmtStringerEncodePlan struct { - next EncodePlan -} - -func (plan *wrapFmtStringerEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapFmtStringerEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode(fmtStringerWrapper{value.(fmt.Stringer)}, buf) -} - -// TryWrapStructPlan tries to wrap a struct with a wrapper that implements CompositeIndexGetter. -func TryWrapStructEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { - if _, ok := value.(driver.Valuer); ok { - return nil, nil, false - } - - if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Struct { - exportedFields := getExportedFieldValues(reflect.ValueOf(value)) - if len(exportedFields) == 0 { - return nil, nil, false - } - - w := structWrapper{ - s: value, - exportedFields: exportedFields, - } - return &wrapAnyStructEncodePlan{}, w, true - } - - return nil, nil, false -} - -type wrapAnyStructEncodePlan struct { - next EncodePlan -} - -func (plan *wrapAnyStructEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapAnyStructEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - w := structWrapper{ - s: value, - exportedFields: getExportedFieldValues(reflect.ValueOf(value)), - } - - return plan.next.Encode(w, buf) -} - -func getExportedFieldValues(structValue reflect.Value) []reflect.Value { - structType := structValue.Type() - exportedFields := make([]reflect.Value, 0, structValue.NumField()) - for i := 0; i < structType.NumField(); i++ { - sf := structType.Field(i) - if sf.IsExported() { - exportedFields = append(exportedFields, structValue.Field(i)) - } - } - - return exportedFields -} - -func TryWrapSliceEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { - if _, ok := value.(driver.Valuer); ok { - return nil, nil, false - } - - // Avoid using reflect path for common types. - switch value := value.(type) { - case []int16: - return &wrapSliceEncodePlan[int16]{}, (FlatArray[int16])(value), true - case []int32: - return &wrapSliceEncodePlan[int32]{}, (FlatArray[int32])(value), true - case []int64: - return &wrapSliceEncodePlan[int64]{}, (FlatArray[int64])(value), true - case []float32: - return &wrapSliceEncodePlan[float32]{}, (FlatArray[float32])(value), true - case []float64: - return &wrapSliceEncodePlan[float64]{}, (FlatArray[float64])(value), true - case []string: - return &wrapSliceEncodePlan[string]{}, (FlatArray[string])(value), true - case []time.Time: - return &wrapSliceEncodePlan[time.Time]{}, (FlatArray[time.Time])(value), true - } - - if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Slice { - w := anySliceArrayReflect{ - slice: reflect.ValueOf(value), - } - return &wrapSliceEncodeReflectPlan{}, w, true - } - - return nil, nil, false -} - -type wrapSliceEncodePlan[T any] struct { - next EncodePlan -} - -func (plan *wrapSliceEncodePlan[T]) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapSliceEncodePlan[T]) Encode(value any, buf []byte) (newBuf []byte, err error) { - return plan.next.Encode((FlatArray[T])(value.([]T)), buf) -} - -type wrapSliceEncodeReflectPlan struct { - next EncodePlan -} - -func (plan *wrapSliceEncodeReflectPlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapSliceEncodeReflectPlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - w := anySliceArrayReflect{ - slice: reflect.ValueOf(value), - } - - return plan.next.Encode(w, buf) -} - -func TryWrapMultiDimSliceEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { - if _, ok := value.(driver.Valuer); ok { - return nil, nil, false - } - - sliceValue := reflect.ValueOf(value) - if sliceValue.Kind() == reflect.Slice { - valueElemType := sliceValue.Type().Elem() - - if valueElemType.Kind() == reflect.Slice { - if !isRagged(sliceValue) { - w := anyMultiDimSliceArray{ - slice: reflect.ValueOf(value), - } - return &wrapMultiDimSliceEncodePlan{}, &w, true - } - } - } - - return nil, nil, false -} - -type wrapMultiDimSliceEncodePlan struct { - next EncodePlan -} - -func (plan *wrapMultiDimSliceEncodePlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapMultiDimSliceEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - w := anyMultiDimSliceArray{ - slice: reflect.ValueOf(value), - } - - return plan.next.Encode(&w, buf) -} - -func TryWrapArrayEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { - if _, ok := value.(driver.Valuer); ok { - return nil, nil, false - } - - if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Array { - w := anyArrayArrayReflect{ - array: reflect.ValueOf(value), - } - return &wrapArrayEncodeReflectPlan{}, w, true - } - - return nil, nil, false -} - -type wrapArrayEncodeReflectPlan struct { - next EncodePlan -} - -func (plan *wrapArrayEncodeReflectPlan) SetNext(next EncodePlan) { plan.next = next } - -func (plan *wrapArrayEncodeReflectPlan) Encode(value any, buf []byte) (newBuf []byte, err error) { - w := anyArrayArrayReflect{ - array: reflect.ValueOf(value), - } - - return plan.next.Encode(w, buf) -} - -func newEncodeError(value any, m *Map, oid uint32, formatCode int16, err error) error { - var format string - switch formatCode { - case TextFormatCode: - format = "text" - case BinaryFormatCode: - format = "binary" - default: - format = fmt.Sprintf("unknown (%d)", formatCode) - } - - var dataTypeName string - if t, ok := m.TypeForOID(oid); ok { - dataTypeName = t.Name - } else { - dataTypeName = "unknown type" - } - - return fmt.Errorf("unable to encode %#v into %s format for %s (OID %d): %w", value, format, dataTypeName, oid, err) -} - -// Encode appends the encoded bytes of value to buf. If value is the SQL value NULL then append nothing and return -// (nil, nil). The caller of Encode is responsible for writing the correct NULL value or the length of the data -// written. -func (m *Map) Encode(oid uint32, formatCode int16, value any, buf []byte) (newBuf []byte, err error) { - if isNil, callNilDriverValuer := isNilDriverValuer(value); isNil { - if callNilDriverValuer { - newBuf, err = (&encodePlanDriverValuer{m: m, oid: oid, formatCode: formatCode}).Encode(value, buf) - if err != nil { - return nil, newEncodeError(value, m, oid, formatCode, err) - } - - return newBuf, nil - } else { - return nil, nil - } - } - - plan := m.PlanEncode(oid, formatCode, value) - if plan == nil { - return nil, newEncodeError(value, m, oid, formatCode, errors.New("cannot find encode plan")) - } - - newBuf, err = plan.Encode(value, buf) - if err != nil { - return nil, newEncodeError(value, m, oid, formatCode, err) - } - - return newBuf, nil -} - -// SQLScanner returns a database/sql.Scanner for v. This is necessary for types like Array[T] and Range[T] where the -// type needs assistance from Map to implement the sql.Scanner interface. It is not necessary for types like Box that -// implement sql.Scanner directly. -// -// This uses the type of v to look up the PostgreSQL OID that v presumably came from. This means v must be registered -// with m by calling RegisterDefaultPgType. -func (m *Map) SQLScanner(v any) sql.Scanner { - if s, ok := v.(sql.Scanner); ok { - return s - } - - return &sqlScannerWrapper{m: m, v: v} -} - -type sqlScannerWrapper struct { - m *Map - v any -} - -func (w *sqlScannerWrapper) Scan(src any) error { - t, ok := w.m.TypeForValue(w.v) - if !ok { - return fmt.Errorf("cannot convert to sql.Scanner: cannot find registered type for %T", w.v) - } - - var bufSrc []byte - if src != nil { - switch src := src.(type) { - case string: - bufSrc = []byte(src) - case []byte: - bufSrc = src - default: - bufSrc = []byte(fmt.Sprint(bufSrc)) - } - } - - return w.m.Scan(t.OID, TextFormatCode, bufSrc, w.v) -} - -// canBeNil returns true if value can be nil. -func canBeNil(value any) bool { - refVal := reflect.ValueOf(value) - kind := refVal.Kind() - switch kind { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: - return true - default: - return false - } -} - -// valuerReflectType is a reflect.Type for driver.Valuer. It has confusing syntax because reflect.TypeOf returns nil -// when it's argument is a nil interface value. So we use a pointer to the interface and call Elem to get the actual -// type. Yuck. -// -// This can be simplified in Go 1.22 with reflect.TypeFor. -// -// var valuerReflectType = reflect.TypeFor[driver.Valuer]() -var valuerReflectType = reflect.TypeOf((*driver.Valuer)(nil)).Elem() - -// isNilDriverValuer returns true if value is any type of nil unless it implements driver.Valuer. *T is not considered to implement -// driver.Valuer if it is only implemented by T. -func isNilDriverValuer(value any) (isNil bool, callNilDriverValuer bool) { - if value == nil { - return true, false - } - - refVal := reflect.ValueOf(value) - kind := refVal.Kind() - switch kind { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: - if !refVal.IsNil() { - return false, false - } - - if _, ok := value.(driver.Valuer); ok { - if kind == reflect.Ptr { - // The type assertion will succeed if driver.Valuer is implemented on T or *T. Check if it is implemented on *T - // by checking if it is not implemented on *T. - return true, !refVal.Type().Elem().Implements(valuerReflectType) - } else { - return true, true - } - } - - return true, false - default: - return false, false - } -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go deleted file mode 100644 index 9496cb974..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go +++ /dev/null @@ -1,231 +0,0 @@ -package pgtype - -import ( - "encoding/json" - "encoding/xml" - "net" - "net/netip" - "reflect" - "sync" - "time" -) - -var ( - // defaultMap contains default mappings between PostgreSQL server types and Go type handling logic. - defaultMap *Map - defaultMapInitOnce = sync.Once{} -) - -func initDefaultMap() { - defaultMap = &Map{ - oidToType: make(map[uint32]*Type), - nameToType: make(map[string]*Type), - reflectTypeToName: make(map[reflect.Type]string), - oidToFormatCode: make(map[uint32]int16), - - memoizedScanPlans: make(map[uint32]map[reflect.Type][2]ScanPlan), - memoizedEncodePlans: make(map[uint32]map[reflect.Type][2]EncodePlan), - - TryWrapEncodePlanFuncs: []TryWrapEncodePlanFunc{ - TryWrapDerefPointerEncodePlan, - TryWrapBuiltinTypeEncodePlan, - TryWrapFindUnderlyingTypeEncodePlan, - TryWrapStructEncodePlan, - TryWrapSliceEncodePlan, - TryWrapMultiDimSliceEncodePlan, - TryWrapArrayEncodePlan, - }, - - TryWrapScanPlanFuncs: []TryWrapScanPlanFunc{ - TryPointerPointerScanPlan, - TryWrapBuiltinTypeScanPlan, - TryFindUnderlyingTypeScanPlan, - TryWrapStructScanPlan, - TryWrapPtrSliceScanPlan, - TryWrapPtrMultiDimSliceScanPlan, - TryWrapPtrArrayScanPlan, - }, - } - - // Base types - defaultMap.RegisterType(&Type{Name: "aclitem", OID: ACLItemOID, Codec: &TextFormatOnlyCodec{TextCodec{}}}) - defaultMap.RegisterType(&Type{Name: "bit", OID: BitOID, Codec: BitsCodec{}}) - defaultMap.RegisterType(&Type{Name: "bool", OID: BoolOID, Codec: BoolCodec{}}) - defaultMap.RegisterType(&Type{Name: "box", OID: BoxOID, Codec: BoxCodec{}}) - defaultMap.RegisterType(&Type{Name: "bpchar", OID: BPCharOID, Codec: TextCodec{}}) - defaultMap.RegisterType(&Type{Name: "bytea", OID: ByteaOID, Codec: ByteaCodec{}}) - defaultMap.RegisterType(&Type{Name: "char", OID: QCharOID, Codec: QCharCodec{}}) - defaultMap.RegisterType(&Type{Name: "cid", OID: CIDOID, Codec: Uint32Codec{}}) - defaultMap.RegisterType(&Type{Name: "cidr", OID: CIDROID, Codec: InetCodec{}}) - defaultMap.RegisterType(&Type{Name: "circle", OID: CircleOID, Codec: CircleCodec{}}) - defaultMap.RegisterType(&Type{Name: "date", OID: DateOID, Codec: DateCodec{}}) - defaultMap.RegisterType(&Type{Name: "float4", OID: Float4OID, Codec: Float4Codec{}}) - defaultMap.RegisterType(&Type{Name: "float8", OID: Float8OID, Codec: Float8Codec{}}) - defaultMap.RegisterType(&Type{Name: "inet", OID: InetOID, Codec: InetCodec{}}) - defaultMap.RegisterType(&Type{Name: "int2", OID: Int2OID, Codec: Int2Codec{}}) - defaultMap.RegisterType(&Type{Name: "int4", OID: Int4OID, Codec: Int4Codec{}}) - defaultMap.RegisterType(&Type{Name: "int8", OID: Int8OID, Codec: Int8Codec{}}) - defaultMap.RegisterType(&Type{Name: "interval", OID: IntervalOID, Codec: IntervalCodec{}}) - defaultMap.RegisterType(&Type{Name: "json", OID: JSONOID, Codec: &JSONCodec{Marshal: json.Marshal, Unmarshal: json.Unmarshal}}) - defaultMap.RegisterType(&Type{Name: "jsonb", OID: JSONBOID, Codec: &JSONBCodec{Marshal: json.Marshal, Unmarshal: json.Unmarshal}}) - defaultMap.RegisterType(&Type{Name: "jsonpath", OID: JSONPathOID, Codec: &TextFormatOnlyCodec{TextCodec{}}}) - defaultMap.RegisterType(&Type{Name: "line", OID: LineOID, Codec: LineCodec{}}) - defaultMap.RegisterType(&Type{Name: "lseg", OID: LsegOID, Codec: LsegCodec{}}) - defaultMap.RegisterType(&Type{Name: "macaddr8", OID: Macaddr8OID, Codec: MacaddrCodec{}}) - defaultMap.RegisterType(&Type{Name: "macaddr", OID: MacaddrOID, Codec: MacaddrCodec{}}) - defaultMap.RegisterType(&Type{Name: "name", OID: NameOID, Codec: TextCodec{}}) - defaultMap.RegisterType(&Type{Name: "numeric", OID: NumericOID, Codec: NumericCodec{}}) - defaultMap.RegisterType(&Type{Name: "oid", OID: OIDOID, Codec: Uint32Codec{}}) - defaultMap.RegisterType(&Type{Name: "path", OID: PathOID, Codec: PathCodec{}}) - defaultMap.RegisterType(&Type{Name: "point", OID: PointOID, Codec: PointCodec{}}) - defaultMap.RegisterType(&Type{Name: "polygon", OID: PolygonOID, Codec: PolygonCodec{}}) - defaultMap.RegisterType(&Type{Name: "record", OID: RecordOID, Codec: RecordCodec{}}) - defaultMap.RegisterType(&Type{Name: "text", OID: TextOID, Codec: TextCodec{}}) - defaultMap.RegisterType(&Type{Name: "tid", OID: TIDOID, Codec: TIDCodec{}}) - defaultMap.RegisterType(&Type{Name: "time", OID: TimeOID, Codec: TimeCodec{}}) - defaultMap.RegisterType(&Type{Name: "timestamp", OID: TimestampOID, Codec: &TimestampCodec{}}) - defaultMap.RegisterType(&Type{Name: "timestamptz", OID: TimestamptzOID, Codec: &TimestamptzCodec{}}) - defaultMap.RegisterType(&Type{Name: "unknown", OID: UnknownOID, Codec: TextCodec{}}) - defaultMap.RegisterType(&Type{Name: "uuid", OID: UUIDOID, Codec: UUIDCodec{}}) - defaultMap.RegisterType(&Type{Name: "varbit", OID: VarbitOID, Codec: BitsCodec{}}) - defaultMap.RegisterType(&Type{Name: "varchar", OID: VarcharOID, Codec: TextCodec{}}) - defaultMap.RegisterType(&Type{Name: "xid", OID: XIDOID, Codec: Uint32Codec{}}) - defaultMap.RegisterType(&Type{Name: "xid8", OID: XID8OID, Codec: Uint64Codec{}}) - defaultMap.RegisterType(&Type{Name: "xml", OID: XMLOID, Codec: &XMLCodec{Marshal: xml.Marshal, Unmarshal: xml.Unmarshal}}) - - // Range types - defaultMap.RegisterType(&Type{Name: "daterange", OID: DaterangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[DateOID]}}) - defaultMap.RegisterType(&Type{Name: "int4range", OID: Int4rangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[Int4OID]}}) - defaultMap.RegisterType(&Type{Name: "int8range", OID: Int8rangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[Int8OID]}}) - defaultMap.RegisterType(&Type{Name: "numrange", OID: NumrangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[NumericOID]}}) - defaultMap.RegisterType(&Type{Name: "tsrange", OID: TsrangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[TimestampOID]}}) - defaultMap.RegisterType(&Type{Name: "tstzrange", OID: TstzrangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[TimestamptzOID]}}) - - // Multirange types - defaultMap.RegisterType(&Type{Name: "datemultirange", OID: DatemultirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[DaterangeOID]}}) - defaultMap.RegisterType(&Type{Name: "int4multirange", OID: Int4multirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[Int4rangeOID]}}) - defaultMap.RegisterType(&Type{Name: "int8multirange", OID: Int8multirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[Int8rangeOID]}}) - defaultMap.RegisterType(&Type{Name: "nummultirange", OID: NummultirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[NumrangeOID]}}) - defaultMap.RegisterType(&Type{Name: "tsmultirange", OID: TsmultirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[TsrangeOID]}}) - defaultMap.RegisterType(&Type{Name: "tstzmultirange", OID: TstzmultirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[TstzrangeOID]}}) - - // Array types - defaultMap.RegisterType(&Type{Name: "_aclitem", OID: ACLItemArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[ACLItemOID]}}) - defaultMap.RegisterType(&Type{Name: "_bit", OID: BitArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BitOID]}}) - defaultMap.RegisterType(&Type{Name: "_bool", OID: BoolArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoolOID]}}) - defaultMap.RegisterType(&Type{Name: "_box", OID: BoxArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoxOID]}}) - defaultMap.RegisterType(&Type{Name: "_bpchar", OID: BPCharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BPCharOID]}}) - defaultMap.RegisterType(&Type{Name: "_bytea", OID: ByteaArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[ByteaOID]}}) - defaultMap.RegisterType(&Type{Name: "_char", OID: QCharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[QCharOID]}}) - defaultMap.RegisterType(&Type{Name: "_cid", OID: CIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[CIDOID]}}) - defaultMap.RegisterType(&Type{Name: "_cidr", OID: CIDRArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[CIDROID]}}) - defaultMap.RegisterType(&Type{Name: "_circle", OID: CircleArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[CircleOID]}}) - defaultMap.RegisterType(&Type{Name: "_date", OID: DateArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[DateOID]}}) - defaultMap.RegisterType(&Type{Name: "_daterange", OID: DaterangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[DaterangeOID]}}) - defaultMap.RegisterType(&Type{Name: "_float4", OID: Float4ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Float4OID]}}) - defaultMap.RegisterType(&Type{Name: "_float8", OID: Float8ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Float8OID]}}) - defaultMap.RegisterType(&Type{Name: "_inet", OID: InetArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[InetOID]}}) - defaultMap.RegisterType(&Type{Name: "_int2", OID: Int2ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int2OID]}}) - defaultMap.RegisterType(&Type{Name: "_int4", OID: Int4ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int4OID]}}) - defaultMap.RegisterType(&Type{Name: "_int4range", OID: Int4rangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int4rangeOID]}}) - defaultMap.RegisterType(&Type{Name: "_int8", OID: Int8ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int8OID]}}) - defaultMap.RegisterType(&Type{Name: "_int8range", OID: Int8rangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int8rangeOID]}}) - defaultMap.RegisterType(&Type{Name: "_interval", OID: IntervalArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[IntervalOID]}}) - defaultMap.RegisterType(&Type{Name: "_json", OID: JSONArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[JSONOID]}}) - defaultMap.RegisterType(&Type{Name: "_jsonb", OID: JSONBArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[JSONBOID]}}) - defaultMap.RegisterType(&Type{Name: "_jsonpath", OID: JSONPathArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[JSONPathOID]}}) - defaultMap.RegisterType(&Type{Name: "_line", OID: LineArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[LineOID]}}) - defaultMap.RegisterType(&Type{Name: "_lseg", OID: LsegArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[LsegOID]}}) - defaultMap.RegisterType(&Type{Name: "_macaddr", OID: MacaddrArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[MacaddrOID]}}) - defaultMap.RegisterType(&Type{Name: "_name", OID: NameArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[NameOID]}}) - defaultMap.RegisterType(&Type{Name: "_numeric", OID: NumericArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[NumericOID]}}) - defaultMap.RegisterType(&Type{Name: "_numrange", OID: NumrangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[NumrangeOID]}}) - defaultMap.RegisterType(&Type{Name: "_oid", OID: OIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[OIDOID]}}) - defaultMap.RegisterType(&Type{Name: "_path", OID: PathArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PathOID]}}) - defaultMap.RegisterType(&Type{Name: "_point", OID: PointArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PointOID]}}) - defaultMap.RegisterType(&Type{Name: "_polygon", OID: PolygonArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PolygonOID]}}) - defaultMap.RegisterType(&Type{Name: "_record", OID: RecordArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[RecordOID]}}) - defaultMap.RegisterType(&Type{Name: "_text", OID: TextArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TextOID]}}) - defaultMap.RegisterType(&Type{Name: "_tid", OID: TIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TIDOID]}}) - defaultMap.RegisterType(&Type{Name: "_time", OID: TimeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TimeOID]}}) - defaultMap.RegisterType(&Type{Name: "_timestamp", OID: TimestampArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TimestampOID]}}) - defaultMap.RegisterType(&Type{Name: "_timestamptz", OID: TimestamptzArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TimestamptzOID]}}) - defaultMap.RegisterType(&Type{Name: "_tsrange", OID: TsrangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TsrangeOID]}}) - defaultMap.RegisterType(&Type{Name: "_tstzrange", OID: TstzrangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TstzrangeOID]}}) - defaultMap.RegisterType(&Type{Name: "_uuid", OID: UUIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[UUIDOID]}}) - defaultMap.RegisterType(&Type{Name: "_varbit", OID: VarbitArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[VarbitOID]}}) - defaultMap.RegisterType(&Type{Name: "_varchar", OID: VarcharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[VarcharOID]}}) - defaultMap.RegisterType(&Type{Name: "_xid", OID: XIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[XIDOID]}}) - defaultMap.RegisterType(&Type{Name: "_xid8", OID: XID8ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[XID8OID]}}) - defaultMap.RegisterType(&Type{Name: "_xml", OID: XMLArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[XMLOID]}}) - - // Integer types that directly map to a PostgreSQL type - registerDefaultPgTypeVariants[int16](defaultMap, "int2") - registerDefaultPgTypeVariants[int32](defaultMap, "int4") - registerDefaultPgTypeVariants[int64](defaultMap, "int8") - - // Integer types that do not have a direct match to a PostgreSQL type - registerDefaultPgTypeVariants[int8](defaultMap, "int8") - registerDefaultPgTypeVariants[int](defaultMap, "int8") - registerDefaultPgTypeVariants[uint8](defaultMap, "int8") - registerDefaultPgTypeVariants[uint16](defaultMap, "int8") - registerDefaultPgTypeVariants[uint32](defaultMap, "int8") - registerDefaultPgTypeVariants[uint64](defaultMap, "numeric") - registerDefaultPgTypeVariants[uint](defaultMap, "numeric") - - registerDefaultPgTypeVariants[float32](defaultMap, "float4") - registerDefaultPgTypeVariants[float64](defaultMap, "float8") - - registerDefaultPgTypeVariants[bool](defaultMap, "bool") - registerDefaultPgTypeVariants[time.Time](defaultMap, "timestamptz") - registerDefaultPgTypeVariants[time.Duration](defaultMap, "interval") - registerDefaultPgTypeVariants[string](defaultMap, "text") - registerDefaultPgTypeVariants[json.RawMessage](defaultMap, "json") - registerDefaultPgTypeVariants[[]byte](defaultMap, "bytea") - - registerDefaultPgTypeVariants[net.IP](defaultMap, "inet") - registerDefaultPgTypeVariants[net.IPNet](defaultMap, "cidr") - registerDefaultPgTypeVariants[netip.Addr](defaultMap, "inet") - registerDefaultPgTypeVariants[netip.Prefix](defaultMap, "cidr") - - // pgtype provided structs - registerDefaultPgTypeVariants[Bits](defaultMap, "varbit") - registerDefaultPgTypeVariants[Bool](defaultMap, "bool") - registerDefaultPgTypeVariants[Box](defaultMap, "box") - registerDefaultPgTypeVariants[Circle](defaultMap, "circle") - registerDefaultPgTypeVariants[Date](defaultMap, "date") - registerDefaultPgTypeVariants[Range[Date]](defaultMap, "daterange") - registerDefaultPgTypeVariants[Multirange[Range[Date]]](defaultMap, "datemultirange") - registerDefaultPgTypeVariants[Float4](defaultMap, "float4") - registerDefaultPgTypeVariants[Float8](defaultMap, "float8") - registerDefaultPgTypeVariants[Range[Float8]](defaultMap, "numrange") // There is no PostgreSQL builtin float8range so map it to numrange. - registerDefaultPgTypeVariants[Multirange[Range[Float8]]](defaultMap, "nummultirange") // There is no PostgreSQL builtin float8multirange so map it to nummultirange. - registerDefaultPgTypeVariants[Int2](defaultMap, "int2") - registerDefaultPgTypeVariants[Int4](defaultMap, "int4") - registerDefaultPgTypeVariants[Range[Int4]](defaultMap, "int4range") - registerDefaultPgTypeVariants[Multirange[Range[Int4]]](defaultMap, "int4multirange") - registerDefaultPgTypeVariants[Int8](defaultMap, "int8") - registerDefaultPgTypeVariants[Range[Int8]](defaultMap, "int8range") - registerDefaultPgTypeVariants[Multirange[Range[Int8]]](defaultMap, "int8multirange") - registerDefaultPgTypeVariants[Interval](defaultMap, "interval") - registerDefaultPgTypeVariants[Line](defaultMap, "line") - registerDefaultPgTypeVariants[Lseg](defaultMap, "lseg") - registerDefaultPgTypeVariants[Numeric](defaultMap, "numeric") - registerDefaultPgTypeVariants[Range[Numeric]](defaultMap, "numrange") - registerDefaultPgTypeVariants[Multirange[Range[Numeric]]](defaultMap, "nummultirange") - registerDefaultPgTypeVariants[Path](defaultMap, "path") - registerDefaultPgTypeVariants[Point](defaultMap, "point") - registerDefaultPgTypeVariants[Polygon](defaultMap, "polygon") - registerDefaultPgTypeVariants[TID](defaultMap, "tid") - registerDefaultPgTypeVariants[Text](defaultMap, "text") - registerDefaultPgTypeVariants[Time](defaultMap, "time") - registerDefaultPgTypeVariants[Timestamp](defaultMap, "timestamp") - registerDefaultPgTypeVariants[Timestamptz](defaultMap, "timestamptz") - registerDefaultPgTypeVariants[Range[Timestamp]](defaultMap, "tsrange") - registerDefaultPgTypeVariants[Multirange[Range[Timestamp]]](defaultMap, "tsmultirange") - registerDefaultPgTypeVariants[Range[Timestamptz]](defaultMap, "tstzrange") - registerDefaultPgTypeVariants[Multirange[Range[Timestamptz]]](defaultMap, "tstzmultirange") - registerDefaultPgTypeVariants[UUID](defaultMap, "uuid") - - defaultMap.buildReflectTypeToType() -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/point.go b/vendor/github.com/jackc/pgx/v5/pgtype/point.go deleted file mode 100644 index 09b19bb53..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/point.go +++ /dev/null @@ -1,266 +0,0 @@ -package pgtype - -import ( - "bytes" - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Vec2 struct { - X float64 - Y float64 -} - -type PointScanner interface { - ScanPoint(v Point) error -} - -type PointValuer interface { - PointValue() (Point, error) -} - -type Point struct { - P Vec2 - Valid bool -} - -func (p *Point) ScanPoint(v Point) error { - *p = v - return nil -} - -func (p Point) PointValue() (Point, error) { - return p, nil -} - -func parsePoint(src []byte) (*Point, error) { - if src == nil || bytes.Equal(src, []byte("null")) { - return &Point{}, nil - } - - if len(src) < 5 { - return nil, fmt.Errorf("invalid length for point: %v", len(src)) - } - if src[0] == '"' && src[len(src)-1] == '"' { - src = src[1 : len(src)-1] - } - sx, sy, found := strings.Cut(string(src[1:len(src)-1]), ",") - if !found { - return nil, fmt.Errorf("invalid format for point") - } - - x, err := strconv.ParseFloat(sx, 64) - if err != nil { - return nil, err - } - - y, err := strconv.ParseFloat(sy, 64) - if err != nil { - return nil, err - } - - return &Point{P: Vec2{x, y}, Valid: true}, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Point) Scan(src any) error { - if src == nil { - *dst = Point{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToPointScanner{}.Scan([]byte(src), dst) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src Point) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - buf, err := PointCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -func (src Point) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - - var buff bytes.Buffer - buff.WriteByte('"') - buff.WriteString(fmt.Sprintf("(%g,%g)", src.P.X, src.P.Y)) - buff.WriteByte('"') - return buff.Bytes(), nil -} - -func (dst *Point) UnmarshalJSON(point []byte) error { - p, err := parsePoint(point) - if err != nil { - return err - } - *dst = *p - return nil -} - -type PointCodec struct{} - -func (PointCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (PointCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (PointCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(PointValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanPointCodecBinary{} - case TextFormatCode: - return encodePlanPointCodecText{} - } - - return nil -} - -type encodePlanPointCodecBinary struct{} - -func (encodePlanPointCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - point, err := value.(PointValuer).PointValue() - if err != nil { - return nil, err - } - - if !point.Valid { - return nil, nil - } - - buf = pgio.AppendUint64(buf, math.Float64bits(point.P.X)) - buf = pgio.AppendUint64(buf, math.Float64bits(point.P.Y)) - return buf, nil -} - -type encodePlanPointCodecText struct{} - -func (encodePlanPointCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - point, err := value.(PointValuer).PointValue() - if err != nil { - return nil, err - } - - if !point.Valid { - return nil, nil - } - - return append(buf, fmt.Sprintf(`(%s,%s)`, - strconv.FormatFloat(point.P.X, 'f', -1, 64), - strconv.FormatFloat(point.P.Y, 'f', -1, 64), - )...), nil -} - -func (PointCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case PointScanner: - return scanPlanBinaryPointToPointScanner{} - } - case TextFormatCode: - switch target.(type) { - case PointScanner: - return scanPlanTextAnyToPointScanner{} - } - } - - return nil -} - -func (c PointCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c PointCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var point Point - err := codecScan(c, m, oid, format, src, &point) - if err != nil { - return nil, err - } - return point, nil -} - -type scanPlanBinaryPointToPointScanner struct{} - -func (scanPlanBinaryPointToPointScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PointScanner) - - if src == nil { - return scanner.ScanPoint(Point{}) - } - - if len(src) != 16 { - return fmt.Errorf("invalid length for point: %v", len(src)) - } - - x := binary.BigEndian.Uint64(src) - y := binary.BigEndian.Uint64(src[8:]) - - return scanner.ScanPoint(Point{ - P: Vec2{math.Float64frombits(x), math.Float64frombits(y)}, - Valid: true, - }) -} - -type scanPlanTextAnyToPointScanner struct{} - -func (scanPlanTextAnyToPointScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PointScanner) - - if src == nil { - return scanner.ScanPoint(Point{}) - } - - if len(src) < 5 { - return fmt.Errorf("invalid length for point: %v", len(src)) - } - - sx, sy, found := strings.Cut(string(src[1:len(src)-1]), ",") - if !found { - return fmt.Errorf("invalid format for point") - } - - x, err := strconv.ParseFloat(sx, 64) - if err != nil { - return err - } - - y, err := strconv.ParseFloat(sy, 64) - if err != nil { - return err - } - - return scanner.ScanPoint(Point{P: Vec2{x, y}, Valid: true}) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go b/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go deleted file mode 100644 index 04b0ba6b0..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go +++ /dev/null @@ -1,253 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type PolygonScanner interface { - ScanPolygon(v Polygon) error -} - -type PolygonValuer interface { - PolygonValue() (Polygon, error) -} - -type Polygon struct { - P []Vec2 - Valid bool -} - -func (p *Polygon) ScanPolygon(v Polygon) error { - *p = v - return nil -} - -func (p Polygon) PolygonValue() (Polygon, error) { - return p, nil -} - -// Scan implements the database/sql Scanner interface. -func (p *Polygon) Scan(src any) error { - if src == nil { - *p = Polygon{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToPolygonScanner{}.Scan([]byte(src), p) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (p Polygon) Value() (driver.Value, error) { - if !p.Valid { - return nil, nil - } - - buf, err := PolygonCodec{}.PlanEncode(nil, 0, TextFormatCode, p).Encode(p, nil) - if err != nil { - return nil, err - } - - return string(buf), err -} - -type PolygonCodec struct{} - -func (PolygonCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (PolygonCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (PolygonCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(PolygonValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanPolygonCodecBinary{} - case TextFormatCode: - return encodePlanPolygonCodecText{} - } - - return nil -} - -type encodePlanPolygonCodecBinary struct{} - -func (encodePlanPolygonCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - polygon, err := value.(PolygonValuer).PolygonValue() - if err != nil { - return nil, err - } - - if !polygon.Valid { - return nil, nil - } - - buf = pgio.AppendInt32(buf, int32(len(polygon.P))) - - for _, p := range polygon.P { - buf = pgio.AppendUint64(buf, math.Float64bits(p.X)) - buf = pgio.AppendUint64(buf, math.Float64bits(p.Y)) - } - - return buf, nil -} - -type encodePlanPolygonCodecText struct{} - -func (encodePlanPolygonCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - polygon, err := value.(PolygonValuer).PolygonValue() - if err != nil { - return nil, err - } - - if !polygon.Valid { - return nil, nil - } - - buf = append(buf, '(') - - for i, p := range polygon.P { - if i > 0 { - buf = append(buf, ',') - } - buf = append(buf, fmt.Sprintf(`(%s,%s)`, - strconv.FormatFloat(p.X, 'f', -1, 64), - strconv.FormatFloat(p.Y, 'f', -1, 64), - )...) - } - - buf = append(buf, ')') - - return buf, nil -} - -func (PolygonCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case PolygonScanner: - return scanPlanBinaryPolygonToPolygonScanner{} - } - case TextFormatCode: - switch target.(type) { - case PolygonScanner: - return scanPlanTextAnyToPolygonScanner{} - } - } - - return nil -} - -type scanPlanBinaryPolygonToPolygonScanner struct{} - -func (scanPlanBinaryPolygonToPolygonScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PolygonScanner) - - if src == nil { - return scanner.ScanPolygon(Polygon{}) - } - - if len(src) < 5 { - return fmt.Errorf("invalid length for polygon: %v", len(src)) - } - - pointCount := int(binary.BigEndian.Uint32(src)) - rp := 4 - - if 4+pointCount*16 != len(src) { - return fmt.Errorf("invalid length for Polygon with %d points: %v", pointCount, len(src)) - } - - points := make([]Vec2, pointCount) - for i := 0; i < len(points); i++ { - x := binary.BigEndian.Uint64(src[rp:]) - rp += 8 - y := binary.BigEndian.Uint64(src[rp:]) - rp += 8 - points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)} - } - - return scanner.ScanPolygon(Polygon{ - P: points, - Valid: true, - }) -} - -type scanPlanTextAnyToPolygonScanner struct{} - -func (scanPlanTextAnyToPolygonScanner) Scan(src []byte, dst any) error { - scanner := (dst).(PolygonScanner) - - if src == nil { - return scanner.ScanPolygon(Polygon{}) - } - - if len(src) < 7 { - return fmt.Errorf("invalid length for Polygon: %v", len(src)) - } - - points := make([]Vec2, 0) - - str := string(src[2:]) - - for { - end := strings.IndexByte(str, ',') - x, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - str = str[end+1:] - end = strings.IndexByte(str, ')') - - y, err := strconv.ParseFloat(str[:end], 64) - if err != nil { - return err - } - - points = append(points, Vec2{x, y}) - - if end+3 < len(str) { - str = str[end+3:] - } else { - break - } - } - - return scanner.ScanPolygon(Polygon{P: points, Valid: true}) -} - -func (c PolygonCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c PolygonCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var polygon Polygon - err := codecScan(c, m, oid, format, src, &polygon) - if err != nil { - return nil, err - } - return polygon, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/qchar.go b/vendor/github.com/jackc/pgx/v5/pgtype/qchar.go deleted file mode 100644 index fc40a5b2c..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/qchar.go +++ /dev/null @@ -1,141 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "fmt" - "math" -) - -// QCharCodec is for PostgreSQL's special 8-bit-only "char" type more akin to the C -// language's char type, or Go's byte type. (Note that the name in PostgreSQL -// itself is "char", in double-quotes, and not char.) It gets used a lot in -// PostgreSQL's system tables to hold a single ASCII character value (eg -// pg_class.relkind). It is named Qchar for quoted char to disambiguate from SQL -// standard type char. -type QCharCodec struct{} - -func (QCharCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (QCharCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (QCharCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case TextFormatCode, BinaryFormatCode: - switch value.(type) { - case byte: - return encodePlanQcharCodecByte{} - case rune: - return encodePlanQcharCodecRune{} - } - } - - return nil -} - -type encodePlanQcharCodecByte struct{} - -func (encodePlanQcharCodecByte) Encode(value any, buf []byte) (newBuf []byte, err error) { - b := value.(byte) - buf = append(buf, b) - return buf, nil -} - -type encodePlanQcharCodecRune struct{} - -func (encodePlanQcharCodecRune) Encode(value any, buf []byte) (newBuf []byte, err error) { - r := value.(rune) - if r > math.MaxUint8 { - return nil, fmt.Errorf(`%v cannot be encoded to "char"`, r) - } - b := byte(r) - buf = append(buf, b) - return buf, nil -} - -func (QCharCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case TextFormatCode, BinaryFormatCode: - switch target.(type) { - case *byte: - return scanPlanQcharCodecByte{} - case *rune: - return scanPlanQcharCodecRune{} - } - } - - return nil -} - -type scanPlanQcharCodecByte struct{} - -func (scanPlanQcharCodecByte) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) > 1 { - return fmt.Errorf(`invalid length for "char": %v`, len(src)) - } - - b := dst.(*byte) - // In the text format the zero value is returned as a zero byte value instead of 0 - if len(src) == 0 { - *b = 0 - } else { - *b = src[0] - } - - return nil -} - -type scanPlanQcharCodecRune struct{} - -func (scanPlanQcharCodecRune) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) > 1 { - return fmt.Errorf(`invalid length for "char": %v`, len(src)) - } - - r := dst.(*rune) - // In the text format the zero value is returned as a zero byte value instead of 0 - if len(src) == 0 { - *r = 0 - } else { - *r = rune(src[0]) - } - - return nil -} - -func (c QCharCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var r rune - err := codecScan(c, m, oid, format, src, &r) - if err != nil { - return nil, err - } - return string(r), nil -} - -func (c QCharCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var r rune - err := codecScan(c, m, oid, format, src, &r) - if err != nil { - return nil, err - } - return r, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range.go b/vendor/github.com/jackc/pgx/v5/pgtype/range.go deleted file mode 100644 index 16427cccd..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/range.go +++ /dev/null @@ -1,322 +0,0 @@ -package pgtype - -import ( - "bytes" - "encoding/binary" - "fmt" -) - -type BoundType byte - -const ( - Inclusive = BoundType('i') - Exclusive = BoundType('e') - Unbounded = BoundType('U') - Empty = BoundType('E') -) - -func (bt BoundType) String() string { - return string(bt) -} - -type untypedTextRange struct { - Lower string - Upper string - LowerType BoundType - UpperType BoundType -} - -func parseUntypedTextRange(src string) (*untypedTextRange, error) { - utr := &untypedTextRange{} - if src == "empty" { - utr.LowerType = Empty - utr.UpperType = Empty - return utr, nil - } - - buf := bytes.NewBufferString(src) - - skipWhitespace(buf) - - r, _, err := buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid lower bound: %w", err) - } - switch r { - case '(': - utr.LowerType = Exclusive - case '[': - utr.LowerType = Inclusive - default: - return nil, fmt.Errorf("missing lower bound, instead got: %v", string(r)) - } - - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid lower value: %w", err) - } - buf.UnreadRune() - - if r == ',' { - utr.LowerType = Unbounded - } else { - utr.Lower, err = rangeParseValue(buf) - if err != nil { - return nil, fmt.Errorf("invalid lower value: %w", err) - } - } - - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("missing range separator: %w", err) - } - if r != ',' { - return nil, fmt.Errorf("missing range separator: %v", r) - } - - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("invalid upper value: %w", err) - } - - if r == ')' || r == ']' { - utr.UpperType = Unbounded - } else { - buf.UnreadRune() - utr.Upper, err = rangeParseValue(buf) - if err != nil { - return nil, fmt.Errorf("invalid upper value: %w", err) - } - - r, _, err = buf.ReadRune() - if err != nil { - return nil, fmt.Errorf("missing upper bound: %w", err) - } - switch r { - case ')': - utr.UpperType = Exclusive - case ']': - utr.UpperType = Inclusive - default: - return nil, fmt.Errorf("missing upper bound, instead got: %v", string(r)) - } - } - - skipWhitespace(buf) - - if buf.Len() > 0 { - return nil, fmt.Errorf("unexpected trailing data: %v", buf.String()) - } - - return utr, nil -} - -func rangeParseValue(buf *bytes.Buffer) (string, error) { - r, _, err := buf.ReadRune() - if err != nil { - return "", err - } - if r == '"' { - return rangeParseQuotedValue(buf) - } - buf.UnreadRune() - - s := &bytes.Buffer{} - - for { - r, _, err := buf.ReadRune() - if err != nil { - return "", err - } - - switch r { - case '\\': - r, _, err = buf.ReadRune() - if err != nil { - return "", err - } - case ',', '[', ']', '(', ')': - buf.UnreadRune() - return s.String(), nil - } - - s.WriteRune(r) - } -} - -func rangeParseQuotedValue(buf *bytes.Buffer) (string, error) { - s := &bytes.Buffer{} - - for { - r, _, err := buf.ReadRune() - if err != nil { - return "", err - } - - switch r { - case '\\': - r, _, err = buf.ReadRune() - if err != nil { - return "", err - } - case '"': - r, _, err = buf.ReadRune() - if err != nil { - return "", err - } - if r != '"' { - buf.UnreadRune() - return s.String(), nil - } - } - s.WriteRune(r) - } -} - -type untypedBinaryRange struct { - Lower []byte - Upper []byte - LowerType BoundType - UpperType BoundType -} - -// 0 = () = 00000 -// 1 = empty = 00001 -// 2 = [) = 00010 -// 4 = (] = 00100 -// 6 = [] = 00110 -// 8 = ) = 01000 -// 12 = ] = 01100 -// 16 = ( = 10000 -// 18 = [ = 10010 -// 24 = = 11000 - -const emptyMask = 1 -const lowerInclusiveMask = 2 -const upperInclusiveMask = 4 -const lowerUnboundedMask = 8 -const upperUnboundedMask = 16 - -func parseUntypedBinaryRange(src []byte) (*untypedBinaryRange, error) { - ubr := &untypedBinaryRange{} - - if len(src) == 0 { - return nil, fmt.Errorf("range too short: %v", len(src)) - } - - rangeType := src[0] - rp := 1 - - if rangeType&emptyMask > 0 { - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing empty range: %v", len(src[rp:])) - } - ubr.LowerType = Empty - ubr.UpperType = Empty - return ubr, nil - } - - if rangeType&lowerInclusiveMask > 0 { - ubr.LowerType = Inclusive - } else if rangeType&lowerUnboundedMask > 0 { - ubr.LowerType = Unbounded - } else { - ubr.LowerType = Exclusive - } - - if rangeType&upperInclusiveMask > 0 { - ubr.UpperType = Inclusive - } else if rangeType&upperUnboundedMask > 0 { - ubr.UpperType = Unbounded - } else { - ubr.UpperType = Exclusive - } - - if ubr.LowerType == Unbounded && ubr.UpperType == Unbounded { - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing unbounded range: %v", len(src[rp:])) - } - return ubr, nil - } - - if len(src[rp:]) < 4 { - return nil, fmt.Errorf("too few bytes for size: %v", src[rp:]) - } - valueLen := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - - val := src[rp : rp+valueLen] - rp += valueLen - - if ubr.LowerType != Unbounded { - ubr.Lower = val - } else { - ubr.Upper = val - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing range: %v", len(src[rp:])) - } - return ubr, nil - } - - if ubr.UpperType != Unbounded { - if len(src[rp:]) < 4 { - return nil, fmt.Errorf("too few bytes for size: %v", src[rp:]) - } - valueLen := int(binary.BigEndian.Uint32(src[rp:])) - rp += 4 - ubr.Upper = src[rp : rp+valueLen] - rp += valueLen - } - - if len(src[rp:]) > 0 { - return nil, fmt.Errorf("unexpected trailing bytes parsing range: %v", len(src[rp:])) - } - - return ubr, nil - -} - -// Range is a generic range type. -type Range[T any] struct { - Lower T - Upper T - LowerType BoundType - UpperType BoundType - Valid bool -} - -func (r Range[T]) IsNull() bool { - return !r.Valid -} - -func (r Range[T]) BoundTypes() (lower, upper BoundType) { - return r.LowerType, r.UpperType -} - -func (r Range[T]) Bounds() (lower, upper any) { - return &r.Lower, &r.Upper -} - -func (r *Range[T]) ScanNull() error { - *r = Range[T]{} - return nil -} - -func (r *Range[T]) ScanBounds() (lowerTarget, upperTarget any) { - return &r.Lower, &r.Upper -} - -func (r *Range[T]) SetBoundTypes(lower, upper BoundType) error { - if lower == Unbounded || lower == Empty { - var zero T - r.Lower = zero - } - if upper == Unbounded || upper == Empty { - var zero T - r.Upper = zero - } - r.LowerType = lower - r.UpperType = upper - r.Valid = true - return nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go deleted file mode 100644 index 684f1bf73..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go +++ /dev/null @@ -1,379 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "fmt" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -// RangeValuer is a type that can be converted into a PostgreSQL range. -type RangeValuer interface { - // IsNull returns true if the value is SQL NULL. - IsNull() bool - - // BoundTypes returns the lower and upper bound types. - BoundTypes() (lower, upper BoundType) - - // Bounds returns the lower and upper range values. - Bounds() (lower, upper any) -} - -// RangeScanner is a type can be scanned from a PostgreSQL range. -type RangeScanner interface { - // ScanNull sets the value to SQL NULL. - ScanNull() error - - // ScanBounds returns values usable as a scan target. The returned values may not be scanned if the range is empty or - // the bound type is unbounded. - ScanBounds() (lowerTarget, upperTarget any) - - // SetBoundTypes sets the lower and upper bound types. ScanBounds will be called and the returned values scanned - // (if appropriate) before SetBoundTypes is called. If the bound types are unbounded or empty this method must - // also set the bound values. - SetBoundTypes(lower, upper BoundType) error -} - -// RangeCodec is a codec for any range type. -type RangeCodec struct { - ElementType *Type -} - -func (c *RangeCodec) FormatSupported(format int16) bool { - return c.ElementType.Codec.FormatSupported(format) -} - -func (c *RangeCodec) PreferredFormat() int16 { - if c.FormatSupported(BinaryFormatCode) { - return BinaryFormatCode - } - return TextFormatCode -} - -func (c *RangeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(RangeValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return &encodePlanRangeCodecRangeValuerToBinary{rc: c, m: m} - case TextFormatCode: - return &encodePlanRangeCodecRangeValuerToText{rc: c, m: m} - } - - return nil -} - -type encodePlanRangeCodecRangeValuerToBinary struct { - rc *RangeCodec - m *Map -} - -func (plan *encodePlanRangeCodecRangeValuerToBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - getter := value.(RangeValuer) - - if getter.IsNull() { - return nil, nil - } - - lowerType, upperType := getter.BoundTypes() - lower, upper := getter.Bounds() - - var rangeType byte - switch lowerType { - case Inclusive: - rangeType |= lowerInclusiveMask - case Unbounded: - rangeType |= lowerUnboundedMask - case Exclusive: - case Empty: - return append(buf, emptyMask), nil - default: - return nil, fmt.Errorf("unknown LowerType: %v", lowerType) - } - - switch upperType { - case Inclusive: - rangeType |= upperInclusiveMask - case Unbounded: - rangeType |= upperUnboundedMask - case Exclusive: - default: - return nil, fmt.Errorf("unknown UpperType: %v", upperType) - } - - buf = append(buf, rangeType) - - if lowerType != Unbounded { - if lower == nil { - return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") - } - - sp := len(buf) - buf = pgio.AppendInt32(buf, -1) - - lowerPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, BinaryFormatCode, lower) - if lowerPlan == nil { - return nil, fmt.Errorf("cannot encode %v as element of range", lower) - } - - buf, err = lowerPlan.Encode(lower, buf) - if err != nil { - return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err) - } - if buf == nil { - return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") - } - - pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) - } - - if upperType != Unbounded { - if upper == nil { - return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") - } - - sp := len(buf) - buf = pgio.AppendInt32(buf, -1) - - upperPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, BinaryFormatCode, upper) - if upperPlan == nil { - return nil, fmt.Errorf("cannot encode %v as element of range", upper) - } - - buf, err = upperPlan.Encode(upper, buf) - if err != nil { - return nil, fmt.Errorf("failed to encode %v as element of range: %w", upper, err) - } - if buf == nil { - return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") - } - - pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) - } - - return buf, nil -} - -type encodePlanRangeCodecRangeValuerToText struct { - rc *RangeCodec - m *Map -} - -func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) (newBuf []byte, err error) { - getter := value.(RangeValuer) - - if getter.IsNull() { - return nil, nil - } - - lowerType, upperType := getter.BoundTypes() - lower, upper := getter.Bounds() - - switch lowerType { - case Exclusive, Unbounded: - buf = append(buf, '(') - case Inclusive: - buf = append(buf, '[') - case Empty: - return append(buf, "empty"...), nil - default: - return nil, fmt.Errorf("unknown lower bound type %v", lowerType) - } - - if lowerType != Unbounded { - if lower == nil { - return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") - } - - lowerPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, TextFormatCode, lower) - if lowerPlan == nil { - return nil, fmt.Errorf("cannot encode %v as element of range", lower) - } - - buf, err = lowerPlan.Encode(lower, buf) - if err != nil { - return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err) - } - if buf == nil { - return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") - } - } - - buf = append(buf, ',') - - if upperType != Unbounded { - if upper == nil { - return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") - } - - upperPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, TextFormatCode, upper) - if upperPlan == nil { - return nil, fmt.Errorf("cannot encode %v as element of range", upper) - } - - buf, err = upperPlan.Encode(upper, buf) - if err != nil { - return nil, fmt.Errorf("failed to encode %v as element of range: %w", upper, err) - } - if buf == nil { - return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") - } - } - - switch upperType { - case Exclusive, Unbounded: - buf = append(buf, ')') - case Inclusive: - buf = append(buf, ']') - default: - return nil, fmt.Errorf("unknown upper bound type %v", upperType) - } - - return buf, nil -} - -func (c *RangeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case BinaryFormatCode: - switch target.(type) { - case RangeScanner: - return &scanPlanBinaryRangeToRangeScanner{rc: c, m: m} - } - case TextFormatCode: - switch target.(type) { - case RangeScanner: - return &scanPlanTextRangeToRangeScanner{rc: c, m: m} - } - } - - return nil -} - -type scanPlanBinaryRangeToRangeScanner struct { - rc *RangeCodec - m *Map -} - -func (plan *scanPlanBinaryRangeToRangeScanner) Scan(src []byte, target any) error { - rangeScanner := (target).(RangeScanner) - - if src == nil { - return rangeScanner.ScanNull() - } - - ubr, err := parseUntypedBinaryRange(src) - if err != nil { - return err - } - - if ubr.LowerType == Empty { - return rangeScanner.SetBoundTypes(ubr.LowerType, ubr.UpperType) - } - - lowerTarget, upperTarget := rangeScanner.ScanBounds() - - if ubr.LowerType == Inclusive || ubr.LowerType == Exclusive { - lowerPlan := plan.m.PlanScan(plan.rc.ElementType.OID, BinaryFormatCode, lowerTarget) - if lowerPlan == nil { - return fmt.Errorf("cannot scan into %v from range element", lowerTarget) - } - - err = lowerPlan.Scan(ubr.Lower, lowerTarget) - if err != nil { - return fmt.Errorf("cannot scan into %v from range element: %w", lowerTarget, err) - } - } - - if ubr.UpperType == Inclusive || ubr.UpperType == Exclusive { - upperPlan := plan.m.PlanScan(plan.rc.ElementType.OID, BinaryFormatCode, upperTarget) - if upperPlan == nil { - return fmt.Errorf("cannot scan into %v from range element", upperTarget) - } - - err = upperPlan.Scan(ubr.Upper, upperTarget) - if err != nil { - return fmt.Errorf("cannot scan into %v from range element: %w", upperTarget, err) - } - } - - return rangeScanner.SetBoundTypes(ubr.LowerType, ubr.UpperType) -} - -type scanPlanTextRangeToRangeScanner struct { - rc *RangeCodec - m *Map -} - -func (plan *scanPlanTextRangeToRangeScanner) Scan(src []byte, target any) error { - rangeScanner := (target).(RangeScanner) - - if src == nil { - return rangeScanner.ScanNull() - } - - utr, err := parseUntypedTextRange(string(src)) - if err != nil { - return err - } - - if utr.LowerType == Empty { - return rangeScanner.SetBoundTypes(utr.LowerType, utr.UpperType) - } - - lowerTarget, upperTarget := rangeScanner.ScanBounds() - - if utr.LowerType == Inclusive || utr.LowerType == Exclusive { - lowerPlan := plan.m.PlanScan(plan.rc.ElementType.OID, TextFormatCode, lowerTarget) - if lowerPlan == nil { - return fmt.Errorf("cannot scan into %v from range element", lowerTarget) - } - - err = lowerPlan.Scan([]byte(utr.Lower), lowerTarget) - if err != nil { - return fmt.Errorf("cannot scan into %v from range element: %w", lowerTarget, err) - } - } - - if utr.UpperType == Inclusive || utr.UpperType == Exclusive { - upperPlan := plan.m.PlanScan(plan.rc.ElementType.OID, TextFormatCode, upperTarget) - if upperPlan == nil { - return fmt.Errorf("cannot scan into %v from range element", upperTarget) - } - - err = upperPlan.Scan([]byte(utr.Upper), upperTarget) - if err != nil { - return fmt.Errorf("cannot scan into %v from range element: %w", upperTarget, err) - } - } - - return rangeScanner.SetBoundTypes(utr.LowerType, utr.UpperType) -} - -func (c *RangeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - switch format { - case TextFormatCode: - return string(src), nil - case BinaryFormatCode: - buf := make([]byte, len(src)) - copy(buf, src) - return buf, nil - default: - return nil, fmt.Errorf("unknown format code %d", format) - } -} - -func (c *RangeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var r Range[any] - err := c.PlanScan(m, oid, format, &r).Scan(src, &r) - return r, err -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go deleted file mode 100644 index b3b166045..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go +++ /dev/null @@ -1,125 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "fmt" -) - -// ArrayGetter is a type that can be converted into a PostgreSQL array. - -// RecordCodec is a codec for the generic PostgreSQL record type such as is created with the "row" function. Record can -// only decode the binary format. The text format output format from PostgreSQL does not include type information and -// is therefore impossible to decode. Encoding is impossible because PostgreSQL does not support input of generic -// records. -type RecordCodec struct{} - -func (RecordCodec) FormatSupported(format int16) bool { - return format == BinaryFormatCode -} - -func (RecordCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (RecordCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - return nil -} - -func (RecordCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - if format == BinaryFormatCode { - switch target.(type) { - case CompositeIndexScanner: - return &scanPlanBinaryRecordToCompositeIndexScanner{m: m} - } - } - - return nil -} - -type scanPlanBinaryRecordToCompositeIndexScanner struct { - m *Map -} - -func (plan *scanPlanBinaryRecordToCompositeIndexScanner) Scan(src []byte, target any) error { - targetScanner := (target).(CompositeIndexScanner) - - if src == nil { - return targetScanner.ScanNull() - } - - scanner := NewCompositeBinaryScanner(plan.m, src) - for i := 0; scanner.Next(); i++ { - fieldTarget := targetScanner.ScanIndex(i) - if fieldTarget != nil { - fieldPlan := plan.m.PlanScan(scanner.OID(), BinaryFormatCode, fieldTarget) - if fieldPlan == nil { - return fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), fieldTarget) - } - - err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) - if err != nil { - return err - } - } - } - - if err := scanner.Err(); err != nil { - return err - } - - return nil -} - -func (RecordCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - switch format { - case TextFormatCode: - return string(src), nil - case BinaryFormatCode: - buf := make([]byte, len(src)) - copy(buf, src) - return buf, nil - default: - return nil, fmt.Errorf("unknown format code %d", format) - } -} - -func (RecordCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - switch format { - case TextFormatCode: - return string(src), nil - case BinaryFormatCode: - scanner := NewCompositeBinaryScanner(m, src) - values := make([]any, scanner.FieldCount()) - for i := 0; scanner.Next(); i++ { - var v any - fieldPlan := m.PlanScan(scanner.OID(), BinaryFormatCode, &v) - if fieldPlan == nil { - return nil, fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), v) - } - - err := fieldPlan.Scan(scanner.Bytes(), &v) - if err != nil { - return nil, err - } - - values[i] = v - } - - if err := scanner.Err(); err != nil { - return nil, err - } - - return values, nil - default: - return nil, fmt.Errorf("unknown format code %d", format) - } - -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types.go b/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types.go deleted file mode 100644 index be1ca4a18..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types.go +++ /dev/null @@ -1,35 +0,0 @@ -//go:build !nopgxregisterdefaulttypes - -package pgtype - -func registerDefaultPgTypeVariants[T any](m *Map, name string) { - arrayName := "_" + name - - var value T - m.RegisterDefaultPgType(value, name) // T - m.RegisterDefaultPgType(&value, name) // *T - - var sliceT []T - m.RegisterDefaultPgType(sliceT, arrayName) // []T - m.RegisterDefaultPgType(&sliceT, arrayName) // *[]T - - var slicePtrT []*T - m.RegisterDefaultPgType(slicePtrT, arrayName) // []*T - m.RegisterDefaultPgType(&slicePtrT, arrayName) // *[]*T - - var arrayOfT Array[T] - m.RegisterDefaultPgType(arrayOfT, arrayName) // Array[T] - m.RegisterDefaultPgType(&arrayOfT, arrayName) // *Array[T] - - var arrayOfPtrT Array[*T] - m.RegisterDefaultPgType(arrayOfPtrT, arrayName) // Array[*T] - m.RegisterDefaultPgType(&arrayOfPtrT, arrayName) // *Array[*T] - - var flatArrayOfT FlatArray[T] - m.RegisterDefaultPgType(flatArrayOfT, arrayName) // FlatArray[T] - m.RegisterDefaultPgType(&flatArrayOfT, arrayName) // *FlatArray[T] - - var flatArrayOfPtrT FlatArray[*T] - m.RegisterDefaultPgType(flatArrayOfPtrT, arrayName) // FlatArray[*T] - m.RegisterDefaultPgType(&flatArrayOfPtrT, arrayName) // *FlatArray[*T] -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types_disabled.go b/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types_disabled.go deleted file mode 100644 index 56fe7c226..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types_disabled.go +++ /dev/null @@ -1,6 +0,0 @@ -//go:build nopgxregisterdefaulttypes - -package pgtype - -func registerDefaultPgTypeVariants[T any](m *Map, name string) { -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/text.go b/vendor/github.com/jackc/pgx/v5/pgtype/text.go deleted file mode 100644 index 021ee331b..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/text.go +++ /dev/null @@ -1,223 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/json" - "fmt" -) - -type TextScanner interface { - ScanText(v Text) error -} - -type TextValuer interface { - TextValue() (Text, error) -} - -type Text struct { - String string - Valid bool -} - -func (t *Text) ScanText(v Text) error { - *t = v - return nil -} - -func (t Text) TextValue() (Text, error) { - return t, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Text) Scan(src any) error { - if src == nil { - *dst = Text{} - return nil - } - - switch src := src.(type) { - case string: - *dst = Text{String: src, Valid: true} - return nil - case []byte: - *dst = Text{String: string(src), Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src Text) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - return src.String, nil -} - -func (src Text) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - - return json.Marshal(src.String) -} - -func (dst *Text) UnmarshalJSON(b []byte) error { - var s *string - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - - if s == nil { - *dst = Text{} - } else { - *dst = Text{String: *s, Valid: true} - } - - return nil -} - -type TextCodec struct{} - -func (TextCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (TextCodec) PreferredFormat() int16 { - return TextFormatCode -} - -func (TextCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case TextFormatCode, BinaryFormatCode: - switch value.(type) { - case string: - return encodePlanTextCodecString{} - case []byte: - return encodePlanTextCodecByteSlice{} - case TextValuer: - return encodePlanTextCodecTextValuer{} - } - } - - return nil -} - -type encodePlanTextCodecString struct{} - -func (encodePlanTextCodecString) Encode(value any, buf []byte) (newBuf []byte, err error) { - s := value.(string) - buf = append(buf, s...) - return buf, nil -} - -type encodePlanTextCodecByteSlice struct{} - -func (encodePlanTextCodecByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { - s := value.([]byte) - buf = append(buf, s...) - return buf, nil -} - -type encodePlanTextCodecStringer struct{} - -func (encodePlanTextCodecStringer) Encode(value any, buf []byte) (newBuf []byte, err error) { - s := value.(fmt.Stringer) - buf = append(buf, s.String()...) - return buf, nil -} - -type encodePlanTextCodecTextValuer struct{} - -func (encodePlanTextCodecTextValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - text, err := value.(TextValuer).TextValue() - if err != nil { - return nil, err - } - - if !text.Valid { - return nil, nil - } - - buf = append(buf, text.String...) - return buf, nil -} - -func (TextCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case TextFormatCode, BinaryFormatCode: - switch target.(type) { - case *string: - return scanPlanTextAnyToString{} - case *[]byte: - return scanPlanAnyToNewByteSlice{} - case BytesScanner: - return scanPlanAnyToByteScanner{} - case TextScanner: - return scanPlanTextAnyToTextScanner{} - } - } - - return nil -} - -func (c TextCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return c.DecodeValue(m, oid, format, src) -} - -func (c TextCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - return string(src), nil -} - -type scanPlanTextAnyToString struct{} - -func (scanPlanTextAnyToString) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - p := (dst).(*string) - *p = string(src) - - return nil -} - -type scanPlanAnyToNewByteSlice struct{} - -func (scanPlanAnyToNewByteSlice) Scan(src []byte, dst any) error { - p := (dst).(*[]byte) - if src == nil { - *p = nil - } else { - *p = make([]byte, len(src)) - copy(*p, src) - } - - return nil -} - -type scanPlanAnyToByteScanner struct{} - -func (scanPlanAnyToByteScanner) Scan(src []byte, dst any) error { - p := (dst).(BytesScanner) - return p.ScanBytes(src) -} - -type scanPlanTextAnyToTextScanner struct{} - -func (scanPlanTextAnyToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) - - if src == nil { - return scanner.ScanText(Text{}) - } - - return scanner.ScanText(Text{String: string(src), Valid: true}) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/text_format_only_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/text_format_only_codec.go deleted file mode 100644 index d5e4cdb38..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/text_format_only_codec.go +++ /dev/null @@ -1,13 +0,0 @@ -package pgtype - -type TextFormatOnlyCodec struct { - Codec -} - -func (c *TextFormatOnlyCodec) FormatSupported(format int16) bool { - return format == TextFormatCode && c.Codec.FormatSupported(format) -} - -func (TextFormatOnlyCodec) PreferredFormat() int16 { - return TextFormatCode -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/tid.go b/vendor/github.com/jackc/pgx/v5/pgtype/tid.go deleted file mode 100644 index 9bc2c2a14..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/tid.go +++ /dev/null @@ -1,241 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type TIDScanner interface { - ScanTID(v TID) error -} - -type TIDValuer interface { - TIDValue() (TID, error) -} - -// TID is PostgreSQL's Tuple Identifier type. -// -// When one does -// -// select ctid, * from some_table; -// -// it is the data type of the ctid hidden system column. -// -// It is currently implemented as a pair unsigned two byte integers. -// Its conversion functions can be found in src/backend/utils/adt/tid.c -// in the PostgreSQL sources. -type TID struct { - BlockNumber uint32 - OffsetNumber uint16 - Valid bool -} - -func (b *TID) ScanTID(v TID) error { - *b = v - return nil -} - -func (b TID) TIDValue() (TID, error) { - return b, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *TID) Scan(src any) error { - if src == nil { - *dst = TID{} - return nil - } - - switch src := src.(type) { - case string: - return scanPlanTextAnyToTIDScanner{}.Scan([]byte(src), dst) - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src TID) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - buf, err := TIDCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type TIDCodec struct{} - -func (TIDCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (TIDCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (TIDCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(TIDValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanTIDCodecBinary{} - case TextFormatCode: - return encodePlanTIDCodecText{} - } - - return nil -} - -type encodePlanTIDCodecBinary struct{} - -func (encodePlanTIDCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - tid, err := value.(TIDValuer).TIDValue() - if err != nil { - return nil, err - } - - if !tid.Valid { - return nil, nil - } - - buf = pgio.AppendUint32(buf, tid.BlockNumber) - buf = pgio.AppendUint16(buf, tid.OffsetNumber) - return buf, nil -} - -type encodePlanTIDCodecText struct{} - -func (encodePlanTIDCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - tid, err := value.(TIDValuer).TIDValue() - if err != nil { - return nil, err - } - - if !tid.Valid { - return nil, nil - } - - buf = append(buf, fmt.Sprintf(`(%d,%d)`, tid.BlockNumber, tid.OffsetNumber)...) - return buf, nil -} - -func (TIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case TIDScanner: - return scanPlanBinaryTIDToTIDScanner{} - case TextScanner: - return scanPlanBinaryTIDToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case TIDScanner: - return scanPlanTextAnyToTIDScanner{} - } - } - - return nil -} - -type scanPlanBinaryTIDToTIDScanner struct{} - -func (scanPlanBinaryTIDToTIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TIDScanner) - - if src == nil { - return scanner.ScanTID(TID{}) - } - - if len(src) != 6 { - return fmt.Errorf("invalid length for tid: %v", len(src)) - } - - return scanner.ScanTID(TID{ - BlockNumber: binary.BigEndian.Uint32(src), - OffsetNumber: binary.BigEndian.Uint16(src[4:]), - Valid: true, - }) -} - -type scanPlanBinaryTIDToTextScanner struct{} - -func (scanPlanBinaryTIDToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) - - if src == nil { - return scanner.ScanText(Text{}) - } - - if len(src) != 6 { - return fmt.Errorf("invalid length for tid: %v", len(src)) - } - - blockNumber := binary.BigEndian.Uint32(src) - offsetNumber := binary.BigEndian.Uint16(src[4:]) - - return scanner.ScanText(Text{ - String: fmt.Sprintf(`(%d,%d)`, blockNumber, offsetNumber), - Valid: true, - }) -} - -type scanPlanTextAnyToTIDScanner struct{} - -func (scanPlanTextAnyToTIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TIDScanner) - - if src == nil { - return scanner.ScanTID(TID{}) - } - - if len(src) < 5 { - return fmt.Errorf("invalid length for tid: %v", len(src)) - } - - block, offset, found := strings.Cut(string(src[1:len(src)-1]), ",") - if !found { - return fmt.Errorf("invalid format for tid") - } - - blockNumber, err := strconv.ParseUint(block, 10, 32) - if err != nil { - return err - } - - offsetNumber, err := strconv.ParseUint(offset, 10, 16) - if err != nil { - return err - } - - return scanner.ScanTID(TID{BlockNumber: uint32(blockNumber), OffsetNumber: uint16(offsetNumber), Valid: true}) -} - -func (c TIDCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c TIDCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var tid TID - err := codecScan(c, m, oid, format, src, &tid) - if err != nil { - return nil, err - } - return tid, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/time.go b/vendor/github.com/jackc/pgx/v5/pgtype/time.go deleted file mode 100644 index f8fd94891..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/time.go +++ /dev/null @@ -1,274 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "strconv" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type TimeScanner interface { - ScanTime(v Time) error -} - -type TimeValuer interface { - TimeValue() (Time, error) -} - -// Time represents the PostgreSQL time type. The PostgreSQL time is a time of day without time zone. -// -// Time is represented as the number of microseconds since midnight in the same way that PostgreSQL does. Other time and -// date types in pgtype can use time.Time as the underlying representation. However, pgtype.Time type cannot due to -// needing to handle 24:00:00. time.Time converts that to 00:00:00 on the following day. -// -// The time with time zone type is not supported. Use of time with time zone is discouraged by the PostgreSQL documentation. -type Time struct { - Microseconds int64 // Number of microseconds since midnight - Valid bool -} - -func (t *Time) ScanTime(v Time) error { - *t = v - return nil -} - -func (t Time) TimeValue() (Time, error) { - return t, nil -} - -// Scan implements the database/sql Scanner interface. -func (t *Time) Scan(src any) error { - if src == nil { - *t = Time{} - return nil - } - - switch src := src.(type) { - case string: - err := scanPlanTextAnyToTimeScanner{}.Scan([]byte(src), t) - if err != nil { - t.Microseconds = 0 - t.Valid = false - } - return err - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (t Time) Value() (driver.Value, error) { - if !t.Valid { - return nil, nil - } - - buf, err := TimeCodec{}.PlanEncode(nil, 0, TextFormatCode, t).Encode(t, nil) - if err != nil { - return nil, err - } - return string(buf), err -} - -type TimeCodec struct{} - -func (TimeCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (TimeCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (TimeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(TimeValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanTimeCodecBinary{} - case TextFormatCode: - return encodePlanTimeCodecText{} - } - - return nil -} - -type encodePlanTimeCodecBinary struct{} - -func (encodePlanTimeCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - t, err := value.(TimeValuer).TimeValue() - if err != nil { - return nil, err - } - - if !t.Valid { - return nil, nil - } - - return pgio.AppendInt64(buf, t.Microseconds), nil -} - -type encodePlanTimeCodecText struct{} - -func (encodePlanTimeCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - t, err := value.(TimeValuer).TimeValue() - if err != nil { - return nil, err - } - - if !t.Valid { - return nil, nil - } - - usec := t.Microseconds - hours := usec / microsecondsPerHour - usec -= hours * microsecondsPerHour - minutes := usec / microsecondsPerMinute - usec -= minutes * microsecondsPerMinute - seconds := usec / microsecondsPerSecond - usec -= seconds * microsecondsPerSecond - - s := fmt.Sprintf("%02d:%02d:%02d.%06d", hours, minutes, seconds, usec) - - return append(buf, s...), nil -} - -func (TimeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case TimeScanner: - return scanPlanBinaryTimeToTimeScanner{} - case TextScanner: - return scanPlanBinaryTimeToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case TimeScanner: - return scanPlanTextAnyToTimeScanner{} - } - } - - return nil -} - -type scanPlanBinaryTimeToTimeScanner struct{} - -func (scanPlanBinaryTimeToTimeScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimeScanner) - - if src == nil { - return scanner.ScanTime(Time{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for time: %v", len(src)) - } - - usec := int64(binary.BigEndian.Uint64(src)) - - return scanner.ScanTime(Time{Microseconds: usec, Valid: true}) -} - -type scanPlanBinaryTimeToTextScanner struct{} - -func (scanPlanBinaryTimeToTextScanner) Scan(src []byte, dst any) error { - ts, ok := (dst).(TextScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return ts.ScanText(Text{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for time: %v", len(src)) - } - - usec := int64(binary.BigEndian.Uint64(src)) - - tim := Time{Microseconds: usec, Valid: true} - - buf, err := TimeCodec{}.PlanEncode(nil, 0, TextFormatCode, tim).Encode(tim, nil) - if err != nil { - return err - } - - return ts.ScanText(Text{String: string(buf), Valid: true}) -} - -type scanPlanTextAnyToTimeScanner struct{} - -func (scanPlanTextAnyToTimeScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimeScanner) - - if src == nil { - return scanner.ScanTime(Time{}) - } - - s := string(src) - - if len(s) < 8 || s[2] != ':' || s[5] != ':' { - return fmt.Errorf("cannot decode %v into Time", s) - } - - hours, err := strconv.ParseInt(s[0:2], 10, 64) - if err != nil { - return fmt.Errorf("cannot decode %v into Time", s) - } - usec := hours * microsecondsPerHour - - minutes, err := strconv.ParseInt(s[3:5], 10, 64) - if err != nil { - return fmt.Errorf("cannot decode %v into Time", s) - } - usec += minutes * microsecondsPerMinute - - seconds, err := strconv.ParseInt(s[6:8], 10, 64) - if err != nil { - return fmt.Errorf("cannot decode %v into Time", s) - } - usec += seconds * microsecondsPerSecond - - if len(s) > 9 { - if s[8] != '.' || len(s) > 15 { - return fmt.Errorf("cannot decode %v into Time", s) - } - - fraction := s[9:] - n, err := strconv.ParseInt(fraction, 10, 64) - if err != nil { - return fmt.Errorf("cannot decode %v into Time", s) - } - - for i := len(fraction); i < 6; i++ { - n *= 10 - } - - usec += n - } - - return scanner.ScanTime(Time{Microseconds: usec, Valid: true}) -} - -func (c TimeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - return codecDecodeToTextFormat(c, m, oid, format, src) -} - -func (c TimeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var t Time - err := codecScan(c, m, oid, format, src, &t) - if err != nil { - return nil, err - } - return t, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go b/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go deleted file mode 100644 index ff2739d6b..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go +++ /dev/null @@ -1,355 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -const pgTimestampFormat = "2006-01-02 15:04:05.999999999" - -type TimestampScanner interface { - ScanTimestamp(v Timestamp) error -} - -type TimestampValuer interface { - TimestampValue() (Timestamp, error) -} - -// Timestamp represents the PostgreSQL timestamp type. -type Timestamp struct { - Time time.Time // Time zone will be ignored when encoding to PostgreSQL. - InfinityModifier InfinityModifier - Valid bool -} - -func (ts *Timestamp) ScanTimestamp(v Timestamp) error { - *ts = v - return nil -} - -func (ts Timestamp) TimestampValue() (Timestamp, error) { - return ts, nil -} - -// Scan implements the database/sql Scanner interface. -func (ts *Timestamp) Scan(src any) error { - if src == nil { - *ts = Timestamp{} - return nil - } - - switch src := src.(type) { - case string: - return (&scanPlanTextTimestampToTimestampScanner{}).Scan([]byte(src), ts) - case time.Time: - *ts = Timestamp{Time: src, Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (ts Timestamp) Value() (driver.Value, error) { - if !ts.Valid { - return nil, nil - } - - if ts.InfinityModifier != Finite { - return ts.InfinityModifier.String(), nil - } - return ts.Time, nil -} - -func (ts Timestamp) MarshalJSON() ([]byte, error) { - if !ts.Valid { - return []byte("null"), nil - } - - var s string - - switch ts.InfinityModifier { - case Finite: - s = ts.Time.Format(time.RFC3339Nano) - case Infinity: - s = "infinity" - case NegativeInfinity: - s = "-infinity" - } - - return json.Marshal(s) -} - -func (ts *Timestamp) UnmarshalJSON(b []byte) error { - var s *string - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - - if s == nil { - *ts = Timestamp{} - return nil - } - - switch *s { - case "infinity": - *ts = Timestamp{Valid: true, InfinityModifier: Infinity} - case "-infinity": - *ts = Timestamp{Valid: true, InfinityModifier: -Infinity} - default: - // PostgreSQL uses ISO 8601 wihout timezone for to_json function and casting from a string to timestampt - tim, err := time.Parse(time.RFC3339Nano, *s+"Z") - if err != nil { - return err - } - - *ts = Timestamp{Time: tim, Valid: true} - } - - return nil -} - -type TimestampCodec struct { - // ScanLocation is the location that the time is assumed to be in for scanning. This is different from - // TimestamptzCodec.ScanLocation in that this setting does change the instant in time that the timestamp represents. - ScanLocation *time.Location -} - -func (*TimestampCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (*TimestampCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (*TimestampCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(TimestampValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanTimestampCodecBinary{} - case TextFormatCode: - return encodePlanTimestampCodecText{} - } - - return nil -} - -type encodePlanTimestampCodecBinary struct{} - -func (encodePlanTimestampCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - ts, err := value.(TimestampValuer).TimestampValue() - if err != nil { - return nil, err - } - - if !ts.Valid { - return nil, nil - } - - var microsecSinceY2K int64 - switch ts.InfinityModifier { - case Finite: - t := discardTimeZone(ts.Time) - microsecSinceUnixEpoch := t.Unix()*1000000 + int64(t.Nanosecond())/1000 - microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K - case Infinity: - microsecSinceY2K = infinityMicrosecondOffset - case NegativeInfinity: - microsecSinceY2K = negativeInfinityMicrosecondOffset - } - - buf = pgio.AppendInt64(buf, microsecSinceY2K) - - return buf, nil -} - -type encodePlanTimestampCodecText struct{} - -func (encodePlanTimestampCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - ts, err := value.(TimestampValuer).TimestampValue() - if err != nil { - return nil, err - } - - if !ts.Valid { - return nil, nil - } - - var s string - - switch ts.InfinityModifier { - case Finite: - t := discardTimeZone(ts.Time) - - // Year 0000 is 1 BC - bc := false - if year := t.Year(); year <= 0 { - year = -year + 1 - t = time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) - bc = true - } - - s = t.Truncate(time.Microsecond).Format(pgTimestampFormat) - - if bc { - s = s + " BC" - } - case Infinity: - s = "infinity" - case NegativeInfinity: - s = "-infinity" - } - - buf = append(buf, s...) - - return buf, nil -} - -func discardTimeZone(t time.Time) time.Time { - if t.Location() != time.UTC { - return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) - } - - return t -} - -func (c *TimestampCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case BinaryFormatCode: - switch target.(type) { - case TimestampScanner: - return &scanPlanBinaryTimestampToTimestampScanner{location: c.ScanLocation} - } - case TextFormatCode: - switch target.(type) { - case TimestampScanner: - return &scanPlanTextTimestampToTimestampScanner{location: c.ScanLocation} - } - } - - return nil -} - -type scanPlanBinaryTimestampToTimestampScanner struct{ location *time.Location } - -func (plan *scanPlanBinaryTimestampToTimestampScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestampScanner) - - if src == nil { - return scanner.ScanTimestamp(Timestamp{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for timestamp: %v", len(src)) - } - - var ts Timestamp - microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) - - switch microsecSinceY2K { - case infinityMicrosecondOffset: - ts = Timestamp{Valid: true, InfinityModifier: Infinity} - case negativeInfinityMicrosecondOffset: - ts = Timestamp{Valid: true, InfinityModifier: -Infinity} - default: - tim := time.Unix( - microsecFromUnixEpochToY2K/1000000+microsecSinceY2K/1000000, - (microsecFromUnixEpochToY2K%1000000*1000)+(microsecSinceY2K%1000000*1000), - ).UTC() - if plan.location != nil { - tim = time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), plan.location) - } - ts = Timestamp{Time: tim, Valid: true} - } - - return scanner.ScanTimestamp(ts) -} - -type scanPlanTextTimestampToTimestampScanner struct{ location *time.Location } - -func (plan *scanPlanTextTimestampToTimestampScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestampScanner) - - if src == nil { - return scanner.ScanTimestamp(Timestamp{}) - } - - var ts Timestamp - sbuf := string(src) - switch sbuf { - case "infinity": - ts = Timestamp{Valid: true, InfinityModifier: Infinity} - case "-infinity": - ts = Timestamp{Valid: true, InfinityModifier: -Infinity} - default: - bc := false - if strings.HasSuffix(sbuf, " BC") { - sbuf = sbuf[:len(sbuf)-3] - bc = true - } - tim, err := time.Parse(pgTimestampFormat, sbuf) - if err != nil { - return err - } - - if bc { - year := -tim.Year() + 1 - tim = time.Date(year, tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), tim.Location()) - } - - if plan.location != nil { - tim = time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), plan.location) - } - - ts = Timestamp{Time: tim, Valid: true} - } - - return scanner.ScanTimestamp(ts) -} - -func (c *TimestampCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var ts Timestamp - err := codecScan(c, m, oid, format, src, &ts) - if err != nil { - return nil, err - } - - if ts.InfinityModifier != Finite { - return ts.InfinityModifier.String(), nil - } - - return ts.Time, nil -} - -func (c *TimestampCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var ts Timestamp - err := codecScan(c, m, oid, format, src, &ts) - if err != nil { - return nil, err - } - - if ts.InfinityModifier != Finite { - return ts.InfinityModifier, nil - } - - return ts.Time, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go b/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go deleted file mode 100644 index 7efbcffd2..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go +++ /dev/null @@ -1,366 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -const pgTimestamptzHourFormat = "2006-01-02 15:04:05.999999999Z07" -const pgTimestamptzMinuteFormat = "2006-01-02 15:04:05.999999999Z07:00" -const pgTimestamptzSecondFormat = "2006-01-02 15:04:05.999999999Z07:00:00" -const microsecFromUnixEpochToY2K = 946684800 * 1000000 - -const ( - negativeInfinityMicrosecondOffset = -9223372036854775808 - infinityMicrosecondOffset = 9223372036854775807 -) - -type TimestamptzScanner interface { - ScanTimestamptz(v Timestamptz) error -} - -type TimestamptzValuer interface { - TimestamptzValue() (Timestamptz, error) -} - -// Timestamptz represents the PostgreSQL timestamptz type. -type Timestamptz struct { - Time time.Time - InfinityModifier InfinityModifier - Valid bool -} - -func (tstz *Timestamptz) ScanTimestamptz(v Timestamptz) error { - *tstz = v - return nil -} - -func (tstz Timestamptz) TimestamptzValue() (Timestamptz, error) { - return tstz, nil -} - -// Scan implements the database/sql Scanner interface. -func (tstz *Timestamptz) Scan(src any) error { - if src == nil { - *tstz = Timestamptz{} - return nil - } - - switch src := src.(type) { - case string: - return (&scanPlanTextTimestamptzToTimestamptzScanner{}).Scan([]byte(src), tstz) - case time.Time: - *tstz = Timestamptz{Time: src, Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (tstz Timestamptz) Value() (driver.Value, error) { - if !tstz.Valid { - return nil, nil - } - - if tstz.InfinityModifier != Finite { - return tstz.InfinityModifier.String(), nil - } - return tstz.Time, nil -} - -func (tstz Timestamptz) MarshalJSON() ([]byte, error) { - if !tstz.Valid { - return []byte("null"), nil - } - - var s string - - switch tstz.InfinityModifier { - case Finite: - s = tstz.Time.Format(time.RFC3339Nano) - case Infinity: - s = "infinity" - case NegativeInfinity: - s = "-infinity" - } - - return json.Marshal(s) -} - -func (tstz *Timestamptz) UnmarshalJSON(b []byte) error { - var s *string - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - - if s == nil { - *tstz = Timestamptz{} - return nil - } - - switch *s { - case "infinity": - *tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} - case "-infinity": - *tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} - default: - // PostgreSQL uses ISO 8601 for to_json function and casting from a string to timestamptz - tim, err := time.Parse(time.RFC3339Nano, *s) - if err != nil { - return err - } - - *tstz = Timestamptz{Time: tim, Valid: true} - } - - return nil -} - -type TimestamptzCodec struct { - // ScanLocation is the location to return scanned timestamptz values in. This does not change the instant in time that - // the timestamptz represents. - ScanLocation *time.Location -} - -func (*TimestamptzCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (*TimestamptzCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (*TimestamptzCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(TimestamptzValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanTimestamptzCodecBinary{} - case TextFormatCode: - return encodePlanTimestamptzCodecText{} - } - - return nil -} - -type encodePlanTimestamptzCodecBinary struct{} - -func (encodePlanTimestamptzCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { - ts, err := value.(TimestamptzValuer).TimestamptzValue() - if err != nil { - return nil, err - } - - if !ts.Valid { - return nil, nil - } - - var microsecSinceY2K int64 - switch ts.InfinityModifier { - case Finite: - microsecSinceUnixEpoch := ts.Time.Unix()*1000000 + int64(ts.Time.Nanosecond())/1000 - microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K - case Infinity: - microsecSinceY2K = infinityMicrosecondOffset - case NegativeInfinity: - microsecSinceY2K = negativeInfinityMicrosecondOffset - } - - buf = pgio.AppendInt64(buf, microsecSinceY2K) - - return buf, nil -} - -type encodePlanTimestamptzCodecText struct{} - -func (encodePlanTimestamptzCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { - ts, err := value.(TimestamptzValuer).TimestamptzValue() - if err != nil { - return nil, err - } - - if !ts.Valid { - return nil, nil - } - - var s string - - switch ts.InfinityModifier { - case Finite: - - t := ts.Time.UTC().Truncate(time.Microsecond) - - // Year 0000 is 1 BC - bc := false - if year := t.Year(); year <= 0 { - year = -year + 1 - t = time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) - bc = true - } - - s = t.Format(pgTimestamptzSecondFormat) - - if bc { - s = s + " BC" - } - case Infinity: - s = "infinity" - case NegativeInfinity: - s = "-infinity" - } - - buf = append(buf, s...) - - return buf, nil -} - -func (c *TimestamptzCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case TimestamptzScanner: - return &scanPlanBinaryTimestamptzToTimestamptzScanner{location: c.ScanLocation} - } - case TextFormatCode: - switch target.(type) { - case TimestamptzScanner: - return &scanPlanTextTimestamptzToTimestamptzScanner{location: c.ScanLocation} - } - } - - return nil -} - -type scanPlanBinaryTimestamptzToTimestamptzScanner struct{ location *time.Location } - -func (plan *scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestamptzScanner) - - if src == nil { - return scanner.ScanTimestamptz(Timestamptz{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for timestamptz: %v", len(src)) - } - - var tstz Timestamptz - microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) - - switch microsecSinceY2K { - case infinityMicrosecondOffset: - tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} - case negativeInfinityMicrosecondOffset: - tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} - default: - tim := time.Unix( - microsecFromUnixEpochToY2K/1000000+microsecSinceY2K/1000000, - (microsecFromUnixEpochToY2K%1000000*1000)+(microsecSinceY2K%1000000*1000), - ) - if plan.location != nil { - tim = tim.In(plan.location) - } - tstz = Timestamptz{Time: tim, Valid: true} - } - - return scanner.ScanTimestamptz(tstz) -} - -type scanPlanTextTimestamptzToTimestamptzScanner struct{ location *time.Location } - -func (plan *scanPlanTextTimestamptzToTimestamptzScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TimestamptzScanner) - - if src == nil { - return scanner.ScanTimestamptz(Timestamptz{}) - } - - var tstz Timestamptz - sbuf := string(src) - switch sbuf { - case "infinity": - tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} - case "-infinity": - tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} - default: - bc := false - if strings.HasSuffix(sbuf, " BC") { - sbuf = sbuf[:len(sbuf)-3] - bc = true - } - - var format string - if len(sbuf) >= 9 && (sbuf[len(sbuf)-9] == '-' || sbuf[len(sbuf)-9] == '+') { - format = pgTimestamptzSecondFormat - } else if len(sbuf) >= 6 && (sbuf[len(sbuf)-6] == '-' || sbuf[len(sbuf)-6] == '+') { - format = pgTimestamptzMinuteFormat - } else { - format = pgTimestamptzHourFormat - } - - tim, err := time.Parse(format, sbuf) - if err != nil { - return err - } - - if bc { - year := -tim.Year() + 1 - tim = time.Date(year, tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), tim.Location()) - } - - if plan.location != nil { - tim = tim.In(plan.location) - } - - tstz = Timestamptz{Time: tim, Valid: true} - } - - return scanner.ScanTimestamptz(tstz) -} - -func (c *TimestamptzCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var tstz Timestamptz - err := codecScan(c, m, oid, format, src, &tstz) - if err != nil { - return nil, err - } - - if tstz.InfinityModifier != Finite { - return tstz.InfinityModifier.String(), nil - } - - return tstz.Time, nil -} - -func (c *TimestamptzCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var tstz Timestamptz - err := codecScan(c, m, oid, format, src, &tstz) - if err != nil { - return nil, err - } - - if tstz.InfinityModifier != Finite { - return tstz.InfinityModifier, nil - } - - return tstz.Time, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go b/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go deleted file mode 100644 index f2b2fa6d4..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go +++ /dev/null @@ -1,325 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Uint32Scanner interface { - ScanUint32(v Uint32) error -} - -type Uint32Valuer interface { - Uint32Value() (Uint32, error) -} - -// Uint32 is the core type that is used to represent PostgreSQL types such as OID, CID, and XID. -type Uint32 struct { - Uint32 uint32 - Valid bool -} - -func (n *Uint32) ScanUint32(v Uint32) error { - *n = v - return nil -} - -func (n Uint32) Uint32Value() (Uint32, error) { - return n, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Uint32) Scan(src any) error { - if src == nil { - *dst = Uint32{} - return nil - } - - var n int64 - - switch src := src.(type) { - case int64: - n = src - case string: - un, err := strconv.ParseUint(src, 10, 32) - if err != nil { - return err - } - n = int64(un) - default: - return fmt.Errorf("cannot scan %T", src) - } - - if n < 0 { - return fmt.Errorf("%d is less than the minimum value for Uint32", n) - } - if n > math.MaxUint32 { - return fmt.Errorf("%d is greater than maximum value for Uint32", n) - } - - *dst = Uint32{Uint32: uint32(n), Valid: true} - - return nil -} - -// Value implements the database/sql/driver Valuer interface. -func (src Uint32) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - return int64(src.Uint32), nil -} - -type Uint32Codec struct{} - -func (Uint32Codec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (Uint32Codec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (Uint32Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case uint32: - return encodePlanUint32CodecBinaryUint32{} - case Uint32Valuer: - return encodePlanUint32CodecBinaryUint32Valuer{} - case Int64Valuer: - return encodePlanUint32CodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case uint32: - return encodePlanUint32CodecTextUint32{} - case Int64Valuer: - return encodePlanUint32CodecTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanUint32CodecBinaryUint32 struct{} - -func (encodePlanUint32CodecBinaryUint32) Encode(value any, buf []byte) (newBuf []byte, err error) { - v := value.(uint32) - return pgio.AppendUint32(buf, v), nil -} - -type encodePlanUint32CodecBinaryUint32Valuer struct{} - -func (encodePlanUint32CodecBinaryUint32Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - v, err := value.(Uint32Valuer).Uint32Value() - if err != nil { - return nil, err - } - - if !v.Valid { - return nil, nil - } - - return pgio.AppendUint32(buf, v.Uint32), nil -} - -type encodePlanUint32CodecBinaryInt64Valuer struct{} - -func (encodePlanUint32CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - v, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !v.Valid { - return nil, nil - } - - if v.Int64 < 0 { - return nil, fmt.Errorf("%d is less than minimum value for uint32", v.Int64) - } - if v.Int64 > math.MaxUint32 { - return nil, fmt.Errorf("%d is greater than maximum value for uint32", v.Int64) - } - - return pgio.AppendUint32(buf, uint32(v.Int64)), nil -} - -type encodePlanUint32CodecTextUint32 struct{} - -func (encodePlanUint32CodecTextUint32) Encode(value any, buf []byte) (newBuf []byte, err error) { - v := value.(uint32) - return append(buf, strconv.FormatUint(uint64(v), 10)...), nil -} - -type encodePlanUint32CodecTextUint32Valuer struct{} - -func (encodePlanUint32CodecTextUint32Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - v, err := value.(Uint32Valuer).Uint32Value() - if err != nil { - return nil, err - } - - if !v.Valid { - return nil, nil - } - - return append(buf, strconv.FormatUint(uint64(v.Uint32), 10)...), nil -} - -type encodePlanUint32CodecTextInt64Valuer struct{} - -func (encodePlanUint32CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - v, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !v.Valid { - return nil, nil - } - - if v.Int64 < 0 { - return nil, fmt.Errorf("%d is less than minimum value for uint32", v.Int64) - } - if v.Int64 > math.MaxUint32 { - return nil, fmt.Errorf("%d is greater than maximum value for uint32", v.Int64) - } - - return append(buf, strconv.FormatInt(v.Int64, 10)...), nil -} - -func (Uint32Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *uint32: - return scanPlanBinaryUint32ToUint32{} - case Uint32Scanner: - return scanPlanBinaryUint32ToUint32Scanner{} - case TextScanner: - return scanPlanBinaryUint32ToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *uint32: - return scanPlanTextAnyToUint32{} - case Uint32Scanner: - return scanPlanTextAnyToUint32Scanner{} - } - } - - return nil -} - -func (c Uint32Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var n uint32 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return int64(n), nil -} - -func (c Uint32Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n uint32 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -type scanPlanBinaryUint32ToUint32 struct{} - -func (scanPlanBinaryUint32ToUint32) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) - } - - p := (dst).(*uint32) - *p = binary.BigEndian.Uint32(src) - - return nil -} - -type scanPlanBinaryUint32ToUint32Scanner struct{} - -func (scanPlanBinaryUint32ToUint32Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint32Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanUint32(Uint32{}) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) - } - - n := binary.BigEndian.Uint32(src) - - return s.ScanUint32(Uint32{Uint32: n, Valid: true}) -} - -type scanPlanBinaryUint32ToTextScanner struct{} - -func (scanPlanBinaryUint32ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanText(Text{}) - } - - if len(src) != 4 { - return fmt.Errorf("invalid length for uint32: %v", len(src)) - } - - n := uint64(binary.BigEndian.Uint32(src)) - return s.ScanText(Text{String: strconv.FormatUint(n, 10), Valid: true}) -} - -type scanPlanTextAnyToUint32Scanner struct{} - -func (scanPlanTextAnyToUint32Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint32Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanUint32(Uint32{}) - } - - n, err := strconv.ParseUint(string(src), 10, 32) - if err != nil { - return err - } - - return s.ScanUint32(Uint32{Uint32: uint32(n), Valid: true}) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go b/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go deleted file mode 100644 index dd2130ebc..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go +++ /dev/null @@ -1,322 +0,0 @@ -package pgtype - -import ( - "database/sql/driver" - "encoding/binary" - "fmt" - "math" - "strconv" - - "github.com/jackc/pgx/v5/internal/pgio" -) - -type Uint64Scanner interface { - ScanUint64(v Uint64) error -} - -type Uint64Valuer interface { - Uint64Value() (Uint64, error) -} - -// Uint64 is the core type that is used to represent PostgreSQL types such as XID8. -type Uint64 struct { - Uint64 uint64 - Valid bool -} - -func (n *Uint64) ScanUint64(v Uint64) error { - *n = v - return nil -} - -func (n Uint64) Uint64Value() (Uint64, error) { - return n, nil -} - -// Scan implements the database/sql Scanner interface. -func (dst *Uint64) Scan(src any) error { - if src == nil { - *dst = Uint64{} - return nil - } - - var n uint64 - - switch src := src.(type) { - case int64: - if src < 0 { - return fmt.Errorf("%d is less than the minimum value for Uint64", src) - } - n = uint64(src) - case string: - un, err := strconv.ParseUint(src, 10, 64) - if err != nil { - return err - } - n = un - default: - return fmt.Errorf("cannot scan %T", src) - } - - *dst = Uint64{Uint64: n, Valid: true} - - return nil -} - -// Value implements the database/sql/driver Valuer interface. -func (src Uint64) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - // If the value is greater than the maximum value for int64, return it as a string instead of losing data or returning - // an error. - if src.Uint64 > math.MaxInt64 { - return strconv.FormatUint(src.Uint64, 10), nil - } - - return int64(src.Uint64), nil -} - -type Uint64Codec struct{} - -func (Uint64Codec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (Uint64Codec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (Uint64Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch format { - case BinaryFormatCode: - switch value.(type) { - case uint64: - return encodePlanUint64CodecBinaryUint64{} - case Uint64Valuer: - return encodePlanUint64CodecBinaryUint64Valuer{} - case Int64Valuer: - return encodePlanUint64CodecBinaryInt64Valuer{} - } - case TextFormatCode: - switch value.(type) { - case uint64: - return encodePlanUint64CodecTextUint64{} - case Int64Valuer: - return encodePlanUint64CodecTextInt64Valuer{} - } - } - - return nil -} - -type encodePlanUint64CodecBinaryUint64 struct{} - -func (encodePlanUint64CodecBinaryUint64) Encode(value any, buf []byte) (newBuf []byte, err error) { - v := value.(uint64) - return pgio.AppendUint64(buf, v), nil -} - -type encodePlanUint64CodecBinaryUint64Valuer struct{} - -func (encodePlanUint64CodecBinaryUint64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - v, err := value.(Uint64Valuer).Uint64Value() - if err != nil { - return nil, err - } - - if !v.Valid { - return nil, nil - } - - return pgio.AppendUint64(buf, v.Uint64), nil -} - -type encodePlanUint64CodecBinaryInt64Valuer struct{} - -func (encodePlanUint64CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - v, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !v.Valid { - return nil, nil - } - - if v.Int64 < 0 { - return nil, fmt.Errorf("%d is less than minimum value for uint64", v.Int64) - } - - return pgio.AppendUint64(buf, uint64(v.Int64)), nil -} - -type encodePlanUint64CodecTextUint64 struct{} - -func (encodePlanUint64CodecTextUint64) Encode(value any, buf []byte) (newBuf []byte, err error) { - v := value.(uint64) - return append(buf, strconv.FormatUint(uint64(v), 10)...), nil -} - -type encodePlanUint64CodecTextUint64Valuer struct{} - -func (encodePlanUint64CodecTextUint64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - v, err := value.(Uint64Valuer).Uint64Value() - if err != nil { - return nil, err - } - - if !v.Valid { - return nil, nil - } - - return append(buf, strconv.FormatUint(v.Uint64, 10)...), nil -} - -type encodePlanUint64CodecTextInt64Valuer struct{} - -func (encodePlanUint64CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - v, err := value.(Int64Valuer).Int64Value() - if err != nil { - return nil, err - } - - if !v.Valid { - return nil, nil - } - - if v.Int64 < 0 { - return nil, fmt.Errorf("%d is less than minimum value for uint64", v.Int64) - } - - return append(buf, strconv.FormatInt(v.Int64, 10)...), nil -} - -func (Uint64Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - - switch format { - case BinaryFormatCode: - switch target.(type) { - case *uint64: - return scanPlanBinaryUint64ToUint64{} - case Uint64Scanner: - return scanPlanBinaryUint64ToUint64Scanner{} - case TextScanner: - return scanPlanBinaryUint64ToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case *uint64: - return scanPlanTextAnyToUint64{} - case Uint64Scanner: - return scanPlanTextAnyToUint64Scanner{} - } - } - - return nil -} - -func (c Uint64Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var n uint64 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return int64(n), nil -} - -func (c Uint64Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var n uint64 - err := codecScan(c, m, oid, format, src, &n) - if err != nil { - return nil, err - } - return n, nil -} - -type scanPlanBinaryUint64ToUint64 struct{} - -func (scanPlanBinaryUint64ToUint64) Scan(src []byte, dst any) error { - if src == nil { - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) - } - - p := (dst).(*uint64) - *p = binary.BigEndian.Uint64(src) - - return nil -} - -type scanPlanBinaryUint64ToUint64Scanner struct{} - -func (scanPlanBinaryUint64ToUint64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint64Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanUint64(Uint64{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) - } - - n := binary.BigEndian.Uint64(src) - - return s.ScanUint64(Uint64{Uint64: n, Valid: true}) -} - -type scanPlanBinaryUint64ToTextScanner struct{} - -func (scanPlanBinaryUint64ToTextScanner) Scan(src []byte, dst any) error { - s, ok := (dst).(TextScanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanText(Text{}) - } - - if len(src) != 8 { - return fmt.Errorf("invalid length for uint64: %v", len(src)) - } - - n := uint64(binary.BigEndian.Uint64(src)) - return s.ScanText(Text{String: strconv.FormatUint(n, 10), Valid: true}) -} - -type scanPlanTextAnyToUint64Scanner struct{} - -func (scanPlanTextAnyToUint64Scanner) Scan(src []byte, dst any) error { - s, ok := (dst).(Uint64Scanner) - if !ok { - return ErrScanTargetTypeChanged - } - - if src == nil { - return s.ScanUint64(Uint64{}) - } - - n, err := strconv.ParseUint(string(src), 10, 64) - if err != nil { - return err - } - - return s.ScanUint64(Uint64{Uint64: n, Valid: true}) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go deleted file mode 100644 index 0628f193f..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go +++ /dev/null @@ -1,289 +0,0 @@ -package pgtype - -import ( - "bytes" - "database/sql/driver" - "encoding/hex" - "fmt" -) - -type UUIDScanner interface { - ScanUUID(v UUID) error -} - -type UUIDValuer interface { - UUIDValue() (UUID, error) -} - -type UUID struct { - Bytes [16]byte - Valid bool -} - -func (b *UUID) ScanUUID(v UUID) error { - *b = v - return nil -} - -func (b UUID) UUIDValue() (UUID, error) { - return b, nil -} - -// parseUUID converts a string UUID in standard form to a byte array. -func parseUUID(src string) (dst [16]byte, err error) { - switch len(src) { - case 36: - src = src[0:8] + src[9:13] + src[14:18] + src[19:23] + src[24:] - case 32: - // dashes already stripped, assume valid - default: - // assume invalid. - return dst, fmt.Errorf("cannot parse UUID %v", src) - } - - buf, err := hex.DecodeString(src) - if err != nil { - return dst, err - } - - copy(dst[:], buf) - return dst, err -} - -// encodeUUID converts a uuid byte array to UUID standard string form. -func encodeUUID(src [16]byte) string { - var buf [36]byte - - hex.Encode(buf[0:8], src[:4]) - buf[8] = '-' - hex.Encode(buf[9:13], src[4:6]) - buf[13] = '-' - hex.Encode(buf[14:18], src[6:8]) - buf[18] = '-' - hex.Encode(buf[19:23], src[8:10]) - buf[23] = '-' - hex.Encode(buf[24:], src[10:]) - - return string(buf[:]) -} - -// Scan implements the database/sql Scanner interface. -func (dst *UUID) Scan(src any) error { - if src == nil { - *dst = UUID{} - return nil - } - - switch src := src.(type) { - case string: - buf, err := parseUUID(src) - if err != nil { - return err - } - *dst = UUID{Bytes: buf, Valid: true} - return nil - } - - return fmt.Errorf("cannot scan %T", src) -} - -// Value implements the database/sql/driver Valuer interface. -func (src UUID) Value() (driver.Value, error) { - if !src.Valid { - return nil, nil - } - - return encodeUUID(src.Bytes), nil -} - -func (src UUID) String() string { - if !src.Valid { - return "" - } - - return encodeUUID(src.Bytes) -} - -func (src UUID) MarshalJSON() ([]byte, error) { - if !src.Valid { - return []byte("null"), nil - } - - var buff bytes.Buffer - buff.WriteByte('"') - buff.WriteString(encodeUUID(src.Bytes)) - buff.WriteByte('"') - return buff.Bytes(), nil -} - -func (dst *UUID) UnmarshalJSON(src []byte) error { - if bytes.Equal(src, []byte("null")) { - *dst = UUID{} - return nil - } - if len(src) != 38 { - return fmt.Errorf("invalid length for UUID: %v", len(src)) - } - buf, err := parseUUID(string(src[1 : len(src)-1])) - if err != nil { - return err - } - *dst = UUID{Bytes: buf, Valid: true} - return nil -} - -type UUIDCodec struct{} - -func (UUIDCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (UUIDCodec) PreferredFormat() int16 { - return BinaryFormatCode -} - -func (UUIDCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - if _, ok := value.(UUIDValuer); !ok { - return nil - } - - switch format { - case BinaryFormatCode: - return encodePlanUUIDCodecBinaryUUIDValuer{} - case TextFormatCode: - return encodePlanUUIDCodecTextUUIDValuer{} - } - - return nil -} - -type encodePlanUUIDCodecBinaryUUIDValuer struct{} - -func (encodePlanUUIDCodecBinaryUUIDValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - uuid, err := value.(UUIDValuer).UUIDValue() - if err != nil { - return nil, err - } - - if !uuid.Valid { - return nil, nil - } - - return append(buf, uuid.Bytes[:]...), nil -} - -type encodePlanUUIDCodecTextUUIDValuer struct{} - -func (encodePlanUUIDCodecTextUUIDValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { - uuid, err := value.(UUIDValuer).UUIDValue() - if err != nil { - return nil, err - } - - if !uuid.Valid { - return nil, nil - } - - return append(buf, encodeUUID(uuid.Bytes)...), nil -} - -func (UUIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch format { - case BinaryFormatCode: - switch target.(type) { - case UUIDScanner: - return scanPlanBinaryUUIDToUUIDScanner{} - case TextScanner: - return scanPlanBinaryUUIDToTextScanner{} - } - case TextFormatCode: - switch target.(type) { - case UUIDScanner: - return scanPlanTextAnyToUUIDScanner{} - } - } - - return nil -} - -type scanPlanBinaryUUIDToUUIDScanner struct{} - -func (scanPlanBinaryUUIDToUUIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(UUIDScanner) - - if src == nil { - return scanner.ScanUUID(UUID{}) - } - - if len(src) != 16 { - return fmt.Errorf("invalid length for UUID: %v", len(src)) - } - - uuid := UUID{Valid: true} - copy(uuid.Bytes[:], src) - - return scanner.ScanUUID(uuid) -} - -type scanPlanBinaryUUIDToTextScanner struct{} - -func (scanPlanBinaryUUIDToTextScanner) Scan(src []byte, dst any) error { - scanner := (dst).(TextScanner) - - if src == nil { - return scanner.ScanText(Text{}) - } - - if len(src) != 16 { - return fmt.Errorf("invalid length for UUID: %v", len(src)) - } - - var buf [16]byte - copy(buf[:], src) - - return scanner.ScanText(Text{String: encodeUUID(buf), Valid: true}) -} - -type scanPlanTextAnyToUUIDScanner struct{} - -func (scanPlanTextAnyToUUIDScanner) Scan(src []byte, dst any) error { - scanner := (dst).(UUIDScanner) - - if src == nil { - return scanner.ScanUUID(UUID{}) - } - - buf, err := parseUUID(string(src)) - if err != nil { - return err - } - - return scanner.ScanUUID(UUID{Bytes: buf, Valid: true}) -} - -func (c UUIDCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - var uuid UUID - err := codecScan(c, m, oid, format, src, &uuid) - if err != nil { - return nil, err - } - - return encodeUUID(uuid.Bytes), nil -} - -func (c UUIDCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var uuid UUID - err := codecScan(c, m, oid, format, src, &uuid) - if err != nil { - return nil, err - } - return uuid.Bytes, nil -} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/xml.go b/vendor/github.com/jackc/pgx/v5/pgtype/xml.go deleted file mode 100644 index 79e3698a4..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgtype/xml.go +++ /dev/null @@ -1,198 +0,0 @@ -package pgtype - -import ( - "database/sql" - "database/sql/driver" - "encoding/xml" - "fmt" - "reflect" -) - -type XMLCodec struct { - Marshal func(v any) ([]byte, error) - Unmarshal func(data []byte, v any) error -} - -func (*XMLCodec) FormatSupported(format int16) bool { - return format == TextFormatCode || format == BinaryFormatCode -} - -func (*XMLCodec) PreferredFormat() int16 { - return TextFormatCode -} - -func (c *XMLCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { - switch value.(type) { - case string: - return encodePlanXMLCodecEitherFormatString{} - case []byte: - return encodePlanXMLCodecEitherFormatByteSlice{} - - // Cannot rely on driver.Valuer being handled later because anything can be marshalled. - // - // https://github.com/jackc/pgx/issues/1430 - // - // Check for driver.Valuer must come before xml.Marshaler so that it is guaranteed to be used - // when both are implemented https://github.com/jackc/pgx/issues/1805 - case driver.Valuer: - return &encodePlanDriverValuer{m: m, oid: oid, formatCode: format} - - // Must come before trying wrap encode plans because a pointer to a struct may be unwrapped to a struct that can be - // marshalled. - // - // https://github.com/jackc/pgx/issues/1681 - case xml.Marshaler: - return &encodePlanXMLCodecEitherFormatMarshal{ - marshal: c.Marshal, - } - } - - // Because anything can be marshalled the normal wrapping in Map.PlanScan doesn't get a chance to run. So try the - // appropriate wrappers here. - for _, f := range []TryWrapEncodePlanFunc{ - TryWrapDerefPointerEncodePlan, - TryWrapFindUnderlyingTypeEncodePlan, - } { - if wrapperPlan, nextValue, ok := f(value); ok { - if nextPlan := c.PlanEncode(m, oid, format, nextValue); nextPlan != nil { - wrapperPlan.SetNext(nextPlan) - return wrapperPlan - } - } - } - - return &encodePlanXMLCodecEitherFormatMarshal{ - marshal: c.Marshal, - } -} - -type encodePlanXMLCodecEitherFormatString struct{} - -func (encodePlanXMLCodecEitherFormatString) Encode(value any, buf []byte) (newBuf []byte, err error) { - xmlString := value.(string) - buf = append(buf, xmlString...) - return buf, nil -} - -type encodePlanXMLCodecEitherFormatByteSlice struct{} - -func (encodePlanXMLCodecEitherFormatByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { - xmlBytes := value.([]byte) - if xmlBytes == nil { - return nil, nil - } - - buf = append(buf, xmlBytes...) - return buf, nil -} - -type encodePlanXMLCodecEitherFormatMarshal struct { - marshal func(v any) ([]byte, error) -} - -func (e *encodePlanXMLCodecEitherFormatMarshal) Encode(value any, buf []byte) (newBuf []byte, err error) { - xmlBytes, err := e.marshal(value) - if err != nil { - return nil, err - } - - buf = append(buf, xmlBytes...) - return buf, nil -} - -func (c *XMLCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { - switch target.(type) { - case *string: - return scanPlanAnyToString{} - - case **string: - // This is to fix **string scanning. It seems wrong to special case **string, but it's not clear what a better - // solution would be. - // - // https://github.com/jackc/pgx/issues/1470 -- **string - // https://github.com/jackc/pgx/issues/1691 -- ** anything else - - if wrapperPlan, nextDst, ok := TryPointerPointerScanPlan(target); ok { - if nextPlan := m.planScan(oid, format, nextDst, 0); nextPlan != nil { - if _, failed := nextPlan.(*scanPlanFail); !failed { - wrapperPlan.SetNext(nextPlan) - return wrapperPlan - } - } - } - - case *[]byte: - return scanPlanXMLToByteSlice{} - case BytesScanner: - return scanPlanBinaryBytesToBytesScanner{} - - // Cannot rely on sql.Scanner being handled later because scanPlanXMLToXMLUnmarshal will take precedence. - // - // https://github.com/jackc/pgx/issues/1418 - case sql.Scanner: - return &scanPlanSQLScanner{formatCode: format} - } - - return &scanPlanXMLToXMLUnmarshal{ - unmarshal: c.Unmarshal, - } -} - -type scanPlanXMLToByteSlice struct{} - -func (scanPlanXMLToByteSlice) Scan(src []byte, dst any) error { - dstBuf := dst.(*[]byte) - if src == nil { - *dstBuf = nil - return nil - } - - *dstBuf = make([]byte, len(src)) - copy(*dstBuf, src) - return nil -} - -type scanPlanXMLToXMLUnmarshal struct { - unmarshal func(data []byte, v any) error -} - -func (s *scanPlanXMLToXMLUnmarshal) Scan(src []byte, dst any) error { - if src == nil { - dstValue := reflect.ValueOf(dst) - if dstValue.Kind() == reflect.Ptr { - el := dstValue.Elem() - switch el.Kind() { - case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface, reflect.Struct: - el.Set(reflect.Zero(el.Type())) - return nil - } - } - - return fmt.Errorf("cannot scan NULL into %T", dst) - } - - elem := reflect.ValueOf(dst).Elem() - elem.Set(reflect.Zero(elem.Type())) - - return s.unmarshal(src, dst) -} - -func (c *XMLCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { - if src == nil { - return nil, nil - } - - dstBuf := make([]byte, len(src)) - copy(dstBuf, src) - return dstBuf, nil -} - -func (c *XMLCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { - if src == nil { - return nil, nil - } - - var dst any - err := c.Unmarshal(src, &dst) - return dst, err -} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go b/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go deleted file mode 100644 index 5d5c681d5..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go +++ /dev/null @@ -1,52 +0,0 @@ -package pgxpool - -import ( - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" -) - -type errBatchResults struct { - err error -} - -func (br errBatchResults) Exec() (pgconn.CommandTag, error) { - return pgconn.CommandTag{}, br.err -} - -func (br errBatchResults) Query() (pgx.Rows, error) { - return errRows{err: br.err}, br.err -} - -func (br errBatchResults) QueryRow() pgx.Row { - return errRow{err: br.err} -} - -func (br errBatchResults) Close() error { - return br.err -} - -type poolBatchResults struct { - br pgx.BatchResults - c *Conn -} - -func (br *poolBatchResults) Exec() (pgconn.CommandTag, error) { - return br.br.Exec() -} - -func (br *poolBatchResults) Query() (pgx.Rows, error) { - return br.br.Query() -} - -func (br *poolBatchResults) QueryRow() pgx.Row { - return br.br.QueryRow() -} - -func (br *poolBatchResults) Close() error { - err := br.br.Close() - if br.c != nil { - br.c.Release() - br.c = nil - } - return err -} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/conn.go b/vendor/github.com/jackc/pgx/v5/pgxpool/conn.go deleted file mode 100644 index 38c90f3da..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/conn.go +++ /dev/null @@ -1,134 +0,0 @@ -package pgxpool - -import ( - "context" - "sync/atomic" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" - "github.com/jackc/puddle/v2" -) - -// Conn is an acquired *pgx.Conn from a Pool. -type Conn struct { - res *puddle.Resource[*connResource] - p *Pool -} - -// Release returns c to the pool it was acquired from. Once Release has been called, other methods must not be called. -// However, it is safe to call Release multiple times. Subsequent calls after the first will be ignored. -func (c *Conn) Release() { - if c.res == nil { - return - } - - conn := c.Conn() - res := c.res - c.res = nil - - if c.p.releaseTracer != nil { - c.p.releaseTracer.TraceRelease(c.p, TraceReleaseData{Conn: conn}) - } - - if conn.IsClosed() || conn.PgConn().IsBusy() || conn.PgConn().TxStatus() != 'I' { - res.Destroy() - // Signal to the health check to run since we just destroyed a connections - // and we might be below minConns now - c.p.triggerHealthCheck() - return - } - - // If the pool is consistently being used, we might never get to check the - // lifetime of a connection since we only check idle connections in checkConnsHealth - // so we also check the lifetime here and force a health check - if c.p.isExpired(res) { - atomic.AddInt64(&c.p.lifetimeDestroyCount, 1) - res.Destroy() - // Signal to the health check to run since we just destroyed a connections - // and we might be below minConns now - c.p.triggerHealthCheck() - return - } - - if c.p.afterRelease == nil { - res.Release() - return - } - - go func() { - if c.p.afterRelease(conn) { - res.Release() - } else { - res.Destroy() - // Signal to the health check to run since we just destroyed a connections - // and we might be below minConns now - c.p.triggerHealthCheck() - } - }() -} - -// Hijack assumes ownership of the connection from the pool. Caller is responsible for closing the connection. Hijack -// will panic if called on an already released or hijacked connection. -func (c *Conn) Hijack() *pgx.Conn { - if c.res == nil { - panic("cannot hijack already released or hijacked connection") - } - - conn := c.Conn() - res := c.res - c.res = nil - - res.Hijack() - - return conn -} - -func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { - return c.Conn().Exec(ctx, sql, arguments...) -} - -func (c *Conn) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) { - return c.Conn().Query(ctx, sql, args...) -} - -func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { - return c.Conn().QueryRow(ctx, sql, args...) -} - -func (c *Conn) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { - return c.Conn().SendBatch(ctx, b) -} - -func (c *Conn) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) { - return c.Conn().CopyFrom(ctx, tableName, columnNames, rowSrc) -} - -// Begin starts a transaction block from the *Conn without explicitly setting a transaction mode (see BeginTx with TxOptions if transaction mode is required). -func (c *Conn) Begin(ctx context.Context) (pgx.Tx, error) { - return c.Conn().Begin(ctx) -} - -// BeginTx starts a transaction block from the *Conn with txOptions determining the transaction mode. -func (c *Conn) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) { - return c.Conn().BeginTx(ctx, txOptions) -} - -func (c *Conn) Ping(ctx context.Context) error { - return c.Conn().Ping(ctx) -} - -func (c *Conn) Conn() *pgx.Conn { - return c.connResource().conn -} - -func (c *Conn) connResource() *connResource { - return c.res.Value() -} - -func (c *Conn) getPoolRow(r pgx.Row) *poolRow { - return c.connResource().getPoolRow(c, r) -} - -func (c *Conn) getPoolRows(r pgx.Rows) *poolRows { - return c.connResource().getPoolRows(c, r) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/doc.go b/vendor/github.com/jackc/pgx/v5/pgxpool/doc.go deleted file mode 100644 index 099443bca..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/doc.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package pgxpool is a concurrency-safe connection pool for pgx. -/* -pgxpool implements a nearly identical interface to pgx connections. - -Creating a Pool - -The primary way of creating a pool is with [pgxpool.New]: - - pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL")) - -The database connection string can be in URL or keyword/value format. PostgreSQL settings, pgx settings, and pool settings can be -specified here. In addition, a config struct can be created by [ParseConfig]. - - config, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL")) - if err != nil { - // ... - } - config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error { - // do something with every new connection - } - - pool, err := pgxpool.NewWithConfig(context.Background(), config) - -A pool returns without waiting for any connections to be established. Acquire a connection immediately after creating -the pool to check if a connection can successfully be established. -*/ -package pgxpool diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go b/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go deleted file mode 100644 index 270b7617a..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go +++ /dev/null @@ -1,717 +0,0 @@ -package pgxpool - -import ( - "context" - "fmt" - "math/rand" - "runtime" - "strconv" - "sync" - "sync/atomic" - "time" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" - "github.com/jackc/puddle/v2" -) - -var defaultMaxConns = int32(4) -var defaultMinConns = int32(0) -var defaultMaxConnLifetime = time.Hour -var defaultMaxConnIdleTime = time.Minute * 30 -var defaultHealthCheckPeriod = time.Minute - -type connResource struct { - conn *pgx.Conn - conns []Conn - poolRows []poolRow - poolRowss []poolRows - maxAgeTime time.Time -} - -func (cr *connResource) getConn(p *Pool, res *puddle.Resource[*connResource]) *Conn { - if len(cr.conns) == 0 { - cr.conns = make([]Conn, 128) - } - - c := &cr.conns[len(cr.conns)-1] - cr.conns = cr.conns[0 : len(cr.conns)-1] - - c.res = res - c.p = p - - return c -} - -func (cr *connResource) getPoolRow(c *Conn, r pgx.Row) *poolRow { - if len(cr.poolRows) == 0 { - cr.poolRows = make([]poolRow, 128) - } - - pr := &cr.poolRows[len(cr.poolRows)-1] - cr.poolRows = cr.poolRows[0 : len(cr.poolRows)-1] - - pr.c = c - pr.r = r - - return pr -} - -func (cr *connResource) getPoolRows(c *Conn, r pgx.Rows) *poolRows { - if len(cr.poolRowss) == 0 { - cr.poolRowss = make([]poolRows, 128) - } - - pr := &cr.poolRowss[len(cr.poolRowss)-1] - cr.poolRowss = cr.poolRowss[0 : len(cr.poolRowss)-1] - - pr.c = c - pr.r = r - - return pr -} - -// Pool allows for connection reuse. -type Pool struct { - // 64 bit fields accessed with atomics must be at beginning of struct to guarantee alignment for certain 32-bit - // architectures. See BUGS section of https://pkg.go.dev/sync/atomic and https://github.com/jackc/pgx/issues/1288. - newConnsCount int64 - lifetimeDestroyCount int64 - idleDestroyCount int64 - - p *puddle.Pool[*connResource] - config *Config - beforeConnect func(context.Context, *pgx.ConnConfig) error - afterConnect func(context.Context, *pgx.Conn) error - beforeAcquire func(context.Context, *pgx.Conn) bool - afterRelease func(*pgx.Conn) bool - beforeClose func(*pgx.Conn) - minConns int32 - maxConns int32 - maxConnLifetime time.Duration - maxConnLifetimeJitter time.Duration - maxConnIdleTime time.Duration - healthCheckPeriod time.Duration - - healthCheckChan chan struct{} - - acquireTracer AcquireTracer - releaseTracer ReleaseTracer - - closeOnce sync.Once - closeChan chan struct{} -} - -// Config is the configuration struct for creating a pool. It must be created by [ParseConfig] and then it can be -// modified. -type Config struct { - ConnConfig *pgx.ConnConfig - - // BeforeConnect is called before a new connection is made. It is passed a copy of the underlying pgx.ConnConfig and - // will not impact any existing open connections. - BeforeConnect func(context.Context, *pgx.ConnConfig) error - - // AfterConnect is called after a connection is established, but before it is added to the pool. - AfterConnect func(context.Context, *pgx.Conn) error - - // BeforeAcquire is called before a connection is acquired from the pool. It must return true to allow the - // acquisition or false to indicate that the connection should be destroyed and a different connection should be - // acquired. - BeforeAcquire func(context.Context, *pgx.Conn) bool - - // AfterRelease is called after a connection is released, but before it is returned to the pool. It must return true to - // return the connection to the pool or false to destroy the connection. - AfterRelease func(*pgx.Conn) bool - - // BeforeClose is called right before a connection is closed and removed from the pool. - BeforeClose func(*pgx.Conn) - - // MaxConnLifetime is the duration since creation after which a connection will be automatically closed. - MaxConnLifetime time.Duration - - // MaxConnLifetimeJitter is the duration after MaxConnLifetime to randomly decide to close a connection. - // This helps prevent all connections from being closed at the exact same time, starving the pool. - MaxConnLifetimeJitter time.Duration - - // MaxConnIdleTime is the duration after which an idle connection will be automatically closed by the health check. - MaxConnIdleTime time.Duration - - // MaxConns is the maximum size of the pool. The default is the greater of 4 or runtime.NumCPU(). - MaxConns int32 - - // MinConns is the minimum size of the pool. After connection closes, the pool might dip below MinConns. A low - // number of MinConns might mean the pool is empty after MaxConnLifetime until the health check has a chance - // to create new connections. - MinConns int32 - - // HealthCheckPeriod is the duration between checks of the health of idle connections. - HealthCheckPeriod time.Duration - - createdByParseConfig bool // Used to enforce created by ParseConfig rule. -} - -// Copy returns a deep copy of the config that is safe to use and modify. -// The only exception is the tls.Config: -// according to the tls.Config docs it must not be modified after creation. -func (c *Config) Copy() *Config { - newConfig := new(Config) - *newConfig = *c - newConfig.ConnConfig = c.ConnConfig.Copy() - return newConfig -} - -// ConnString returns the connection string as parsed by pgxpool.ParseConfig into pgxpool.Config. -func (c *Config) ConnString() string { return c.ConnConfig.ConnString() } - -// New creates a new Pool. See [ParseConfig] for information on connString format. -func New(ctx context.Context, connString string) (*Pool, error) { - config, err := ParseConfig(connString) - if err != nil { - return nil, err - } - - return NewWithConfig(ctx, config) -} - -// NewWithConfig creates a new Pool. config must have been created by [ParseConfig]. -func NewWithConfig(ctx context.Context, config *Config) (*Pool, error) { - // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from - // zero values. - if !config.createdByParseConfig { - panic("config must be created by ParseConfig") - } - - p := &Pool{ - config: config, - beforeConnect: config.BeforeConnect, - afterConnect: config.AfterConnect, - beforeAcquire: config.BeforeAcquire, - afterRelease: config.AfterRelease, - beforeClose: config.BeforeClose, - minConns: config.MinConns, - maxConns: config.MaxConns, - maxConnLifetime: config.MaxConnLifetime, - maxConnLifetimeJitter: config.MaxConnLifetimeJitter, - maxConnIdleTime: config.MaxConnIdleTime, - healthCheckPeriod: config.HealthCheckPeriod, - healthCheckChan: make(chan struct{}, 1), - closeChan: make(chan struct{}), - } - - if t, ok := config.ConnConfig.Tracer.(AcquireTracer); ok { - p.acquireTracer = t - } - - if t, ok := config.ConnConfig.Tracer.(ReleaseTracer); ok { - p.releaseTracer = t - } - - var err error - p.p, err = puddle.NewPool( - &puddle.Config[*connResource]{ - Constructor: func(ctx context.Context) (*connResource, error) { - atomic.AddInt64(&p.newConnsCount, 1) - connConfig := p.config.ConnConfig.Copy() - - // Connection will continue in background even if Acquire is canceled. Ensure that a connect won't hang forever. - if connConfig.ConnectTimeout <= 0 { - connConfig.ConnectTimeout = 2 * time.Minute - } - - if p.beforeConnect != nil { - if err := p.beforeConnect(ctx, connConfig); err != nil { - return nil, err - } - } - - conn, err := pgx.ConnectConfig(ctx, connConfig) - if err != nil { - return nil, err - } - - if p.afterConnect != nil { - err = p.afterConnect(ctx, conn) - if err != nil { - conn.Close(ctx) - return nil, err - } - } - - jitterSecs := rand.Float64() * config.MaxConnLifetimeJitter.Seconds() - maxAgeTime := time.Now().Add(config.MaxConnLifetime).Add(time.Duration(jitterSecs) * time.Second) - - cr := &connResource{ - conn: conn, - conns: make([]Conn, 64), - poolRows: make([]poolRow, 64), - poolRowss: make([]poolRows, 64), - maxAgeTime: maxAgeTime, - } - - return cr, nil - }, - Destructor: func(value *connResource) { - ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) - conn := value.conn - if p.beforeClose != nil { - p.beforeClose(conn) - } - conn.Close(ctx) - select { - case <-conn.PgConn().CleanupDone(): - case <-ctx.Done(): - } - cancel() - }, - MaxSize: config.MaxConns, - }, - ) - if err != nil { - return nil, err - } - - go func() { - p.createIdleResources(ctx, int(p.minConns)) - p.backgroundHealthCheck() - }() - - return p, nil -} - -// ParseConfig builds a Config from connString. It parses connString with the same behavior as [pgx.ParseConfig] with the -// addition of the following variables: -// -// - pool_max_conns: integer greater than 0 (default 4) -// - pool_min_conns: integer 0 or greater (default 0) -// - pool_max_conn_lifetime: duration string (default 1 hour) -// - pool_max_conn_idle_time: duration string (default 30 minutes) -// - pool_health_check_period: duration string (default 1 minute) -// - pool_max_conn_lifetime_jitter: duration string (default 0) -// -// See Config for definitions of these arguments. -// -// # Example Keyword/Value -// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca pool_max_conns=10 pool_max_conn_lifetime=1h30m -// -// # Example URL -// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca&pool_max_conns=10&pool_max_conn_lifetime=1h30m -func ParseConfig(connString string) (*Config, error) { - connConfig, err := pgx.ParseConfig(connString) - if err != nil { - return nil, err - } - - config := &Config{ - ConnConfig: connConfig, - createdByParseConfig: true, - } - - if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conns"]; ok { - delete(connConfig.Config.RuntimeParams, "pool_max_conns") - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - return nil, fmt.Errorf("cannot parse pool_max_conns: %w", err) - } - if n < 1 { - return nil, fmt.Errorf("pool_max_conns too small: %d", n) - } - config.MaxConns = int32(n) - } else { - config.MaxConns = defaultMaxConns - if numCPU := int32(runtime.NumCPU()); numCPU > config.MaxConns { - config.MaxConns = numCPU - } - } - - if s, ok := config.ConnConfig.Config.RuntimeParams["pool_min_conns"]; ok { - delete(connConfig.Config.RuntimeParams, "pool_min_conns") - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - return nil, fmt.Errorf("cannot parse pool_min_conns: %w", err) - } - config.MinConns = int32(n) - } else { - config.MinConns = defaultMinConns - } - - if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_lifetime"]; ok { - delete(connConfig.Config.RuntimeParams, "pool_max_conn_lifetime") - d, err := time.ParseDuration(s) - if err != nil { - return nil, fmt.Errorf("invalid pool_max_conn_lifetime: %w", err) - } - config.MaxConnLifetime = d - } else { - config.MaxConnLifetime = defaultMaxConnLifetime - } - - if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_idle_time"]; ok { - delete(connConfig.Config.RuntimeParams, "pool_max_conn_idle_time") - d, err := time.ParseDuration(s) - if err != nil { - return nil, fmt.Errorf("invalid pool_max_conn_idle_time: %w", err) - } - config.MaxConnIdleTime = d - } else { - config.MaxConnIdleTime = defaultMaxConnIdleTime - } - - if s, ok := config.ConnConfig.Config.RuntimeParams["pool_health_check_period"]; ok { - delete(connConfig.Config.RuntimeParams, "pool_health_check_period") - d, err := time.ParseDuration(s) - if err != nil { - return nil, fmt.Errorf("invalid pool_health_check_period: %w", err) - } - config.HealthCheckPeriod = d - } else { - config.HealthCheckPeriod = defaultHealthCheckPeriod - } - - if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_lifetime_jitter"]; ok { - delete(connConfig.Config.RuntimeParams, "pool_max_conn_lifetime_jitter") - d, err := time.ParseDuration(s) - if err != nil { - return nil, fmt.Errorf("invalid pool_max_conn_lifetime_jitter: %w", err) - } - config.MaxConnLifetimeJitter = d - } - - return config, nil -} - -// Close closes all connections in the pool and rejects future Acquire calls. Blocks until all connections are returned -// to pool and closed. -func (p *Pool) Close() { - p.closeOnce.Do(func() { - close(p.closeChan) - p.p.Close() - }) -} - -func (p *Pool) isExpired(res *puddle.Resource[*connResource]) bool { - return time.Now().After(res.Value().maxAgeTime) -} - -func (p *Pool) triggerHealthCheck() { - go func() { - // Destroy is asynchronous so we give it time to actually remove itself from - // the pool otherwise we might try to check the pool size too soon - time.Sleep(500 * time.Millisecond) - select { - case p.healthCheckChan <- struct{}{}: - default: - } - }() -} - -func (p *Pool) backgroundHealthCheck() { - ticker := time.NewTicker(p.healthCheckPeriod) - defer ticker.Stop() - for { - select { - case <-p.closeChan: - return - case <-p.healthCheckChan: - p.checkHealth() - case <-ticker.C: - p.checkHealth() - } - } -} - -func (p *Pool) checkHealth() { - for { - // If checkMinConns failed we don't destroy any connections since we couldn't - // even get to minConns - if err := p.checkMinConns(); err != nil { - // Should we log this error somewhere? - break - } - if !p.checkConnsHealth() { - // Since we didn't destroy any connections we can stop looping - break - } - // Technically Destroy is asynchronous but 500ms should be enough for it to - // remove it from the underlying pool - select { - case <-p.closeChan: - return - case <-time.After(500 * time.Millisecond): - } - } -} - -// checkConnsHealth will check all idle connections, destroy a connection if -// it's idle or too old, and returns true if any were destroyed -func (p *Pool) checkConnsHealth() bool { - var destroyed bool - totalConns := p.Stat().TotalConns() - resources := p.p.AcquireAllIdle() - for _, res := range resources { - // We're okay going under minConns if the lifetime is up - if p.isExpired(res) && totalConns >= p.minConns { - atomic.AddInt64(&p.lifetimeDestroyCount, 1) - res.Destroy() - destroyed = true - // Since Destroy is async we manually decrement totalConns. - totalConns-- - } else if res.IdleDuration() > p.maxConnIdleTime && totalConns > p.minConns { - atomic.AddInt64(&p.idleDestroyCount, 1) - res.Destroy() - destroyed = true - // Since Destroy is async we manually decrement totalConns. - totalConns-- - } else { - res.ReleaseUnused() - } - } - return destroyed -} - -func (p *Pool) checkMinConns() error { - // TotalConns can include ones that are being destroyed but we should have - // sleep(500ms) around all of the destroys to help prevent that from throwing - // off this check - toCreate := p.minConns - p.Stat().TotalConns() - if toCreate > 0 { - return p.createIdleResources(context.Background(), int(toCreate)) - } - return nil -} - -func (p *Pool) createIdleResources(parentCtx context.Context, targetResources int) error { - ctx, cancel := context.WithCancel(parentCtx) - defer cancel() - - errs := make(chan error, targetResources) - - for i := 0; i < targetResources; i++ { - go func() { - err := p.p.CreateResource(ctx) - // Ignore ErrNotAvailable since it means that the pool has become full since we started creating resource. - if err == puddle.ErrNotAvailable { - err = nil - } - errs <- err - }() - } - - var firstError error - for i := 0; i < targetResources; i++ { - err := <-errs - if err != nil && firstError == nil { - cancel() - firstError = err - } - } - - return firstError -} - -// Acquire returns a connection (*Conn) from the Pool -func (p *Pool) Acquire(ctx context.Context) (c *Conn, err error) { - if p.acquireTracer != nil { - ctx = p.acquireTracer.TraceAcquireStart(ctx, p, TraceAcquireStartData{}) - defer func() { - var conn *pgx.Conn - if c != nil { - conn = c.Conn() - } - p.acquireTracer.TraceAcquireEnd(ctx, p, TraceAcquireEndData{Conn: conn, Err: err}) - }() - } - - for { - res, err := p.p.Acquire(ctx) - if err != nil { - return nil, err - } - - cr := res.Value() - - if res.IdleDuration() > time.Second { - err := cr.conn.Ping(ctx) - if err != nil { - res.Destroy() - continue - } - } - - if p.beforeAcquire == nil || p.beforeAcquire(ctx, cr.conn) { - return cr.getConn(p, res), nil - } - - res.Destroy() - } -} - -// AcquireFunc acquires a *Conn and calls f with that *Conn. ctx will only affect the Acquire. It has no effect on the -// call of f. The return value is either an error acquiring the *Conn or the return value of f. The *Conn is -// automatically released after the call of f. -func (p *Pool) AcquireFunc(ctx context.Context, f func(*Conn) error) error { - conn, err := p.Acquire(ctx) - if err != nil { - return err - } - defer conn.Release() - - return f(conn) -} - -// AcquireAllIdle atomically acquires all currently idle connections. Its intended use is for health check and -// keep-alive functionality. It does not update pool statistics. -func (p *Pool) AcquireAllIdle(ctx context.Context) []*Conn { - resources := p.p.AcquireAllIdle() - conns := make([]*Conn, 0, len(resources)) - for _, res := range resources { - cr := res.Value() - if p.beforeAcquire == nil || p.beforeAcquire(ctx, cr.conn) { - conns = append(conns, cr.getConn(p, res)) - } else { - res.Destroy() - } - } - - return conns -} - -// Reset closes all connections, but leaves the pool open. It is intended for use when an error is detected that would -// disrupt all connections (such as a network interruption or a server state change). -// -// It is safe to reset a pool while connections are checked out. Those connections will be closed when they are returned -// to the pool. -func (p *Pool) Reset() { - p.p.Reset() -} - -// Config returns a copy of config that was used to initialize this pool. -func (p *Pool) Config() *Config { return p.config.Copy() } - -// Stat returns a pgxpool.Stat struct with a snapshot of Pool statistics. -func (p *Pool) Stat() *Stat { - return &Stat{ - s: p.p.Stat(), - newConnsCount: atomic.LoadInt64(&p.newConnsCount), - lifetimeDestroyCount: atomic.LoadInt64(&p.lifetimeDestroyCount), - idleDestroyCount: atomic.LoadInt64(&p.idleDestroyCount), - } -} - -// Exec acquires a connection from the Pool and executes the given SQL. -// SQL can be either a prepared statement name or an SQL string. -// Arguments should be referenced positionally from the SQL string as $1, $2, etc. -// The acquired connection is returned to the pool when the Exec function returns. -func (p *Pool) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { - c, err := p.Acquire(ctx) - if err != nil { - return pgconn.CommandTag{}, err - } - defer c.Release() - - return c.Exec(ctx, sql, arguments...) -} - -// Query acquires a connection and executes a query that returns pgx.Rows. -// Arguments should be referenced positionally from the SQL string as $1, $2, etc. -// See pgx.Rows documentation to close the returned Rows and return the acquired connection to the Pool. -// -// If there is an error, the returned pgx.Rows will be returned in an error state. -// If preferred, ignore the error returned from Query and handle errors using the returned pgx.Rows. -// -// For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and -// QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely -// needed. See the documentation for those types for details. -func (p *Pool) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) { - c, err := p.Acquire(ctx) - if err != nil { - return errRows{err: err}, err - } - - rows, err := c.Query(ctx, sql, args...) - if err != nil { - c.Release() - return errRows{err: err}, err - } - - return c.getPoolRows(rows), nil -} - -// QueryRow acquires a connection and executes a query that is expected -// to return at most one row (pgx.Row). Errors are deferred until pgx.Row's -// Scan method is called. If the query selects no rows, pgx.Row's Scan will -// return ErrNoRows. Otherwise, pgx.Row's Scan scans the first selected row -// and discards the rest. The acquired connection is returned to the Pool when -// pgx.Row's Scan method is called. -// -// Arguments should be referenced positionally from the SQL string as $1, $2, etc. -// -// For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and -// QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely -// needed. See the documentation for those types for details. -func (p *Pool) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { - c, err := p.Acquire(ctx) - if err != nil { - return errRow{err: err} - } - - row := c.QueryRow(ctx, sql, args...) - return c.getPoolRow(row) -} - -func (p *Pool) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { - c, err := p.Acquire(ctx) - if err != nil { - return errBatchResults{err: err} - } - - br := c.SendBatch(ctx, b) - return &poolBatchResults{br: br, c: c} -} - -// Begin acquires a connection from the Pool and starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no -// auto-rollback on context cancellation. Begin initiates a transaction block without explicitly setting a transaction mode for the block (see BeginTx with TxOptions if transaction mode is required). -// *pgxpool.Tx is returned, which implements the pgx.Tx interface. -// Commit or Rollback must be called on the returned transaction to finalize the transaction block. -func (p *Pool) Begin(ctx context.Context) (pgx.Tx, error) { - return p.BeginTx(ctx, pgx.TxOptions{}) -} - -// BeginTx acquires a connection from the Pool and starts a transaction with pgx.TxOptions determining the transaction mode. -// Unlike database/sql, the context only affects the begin command. i.e. there is no auto-rollback on context cancellation. -// *pgxpool.Tx is returned, which implements the pgx.Tx interface. -// Commit or Rollback must be called on the returned transaction to finalize the transaction block. -func (p *Pool) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) { - c, err := p.Acquire(ctx) - if err != nil { - return nil, err - } - - t, err := c.BeginTx(ctx, txOptions) - if err != nil { - c.Release() - return nil, err - } - - return &Tx{t: t, c: c}, nil -} - -func (p *Pool) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) { - c, err := p.Acquire(ctx) - if err != nil { - return 0, err - } - defer c.Release() - - return c.Conn().CopyFrom(ctx, tableName, columnNames, rowSrc) -} - -// Ping acquires a connection from the Pool and executes an empty sql statement against it. -// If the sql returns without error, the database Ping is considered successful, otherwise, the error is returned. -func (p *Pool) Ping(ctx context.Context) error { - c, err := p.Acquire(ctx) - if err != nil { - return err - } - defer c.Release() - return c.Ping(ctx) -} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go b/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go deleted file mode 100644 index f834b7ec3..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go +++ /dev/null @@ -1,116 +0,0 @@ -package pgxpool - -import ( - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" -) - -type errRows struct { - err error -} - -func (errRows) Close() {} -func (e errRows) Err() error { return e.err } -func (errRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} } -func (errRows) FieldDescriptions() []pgconn.FieldDescription { return nil } -func (errRows) Next() bool { return false } -func (e errRows) Scan(dest ...any) error { return e.err } -func (e errRows) Values() ([]any, error) { return nil, e.err } -func (e errRows) RawValues() [][]byte { return nil } -func (e errRows) Conn() *pgx.Conn { return nil } - -type errRow struct { - err error -} - -func (e errRow) Scan(dest ...any) error { return e.err } - -type poolRows struct { - r pgx.Rows - c *Conn - err error -} - -func (rows *poolRows) Close() { - rows.r.Close() - if rows.c != nil { - rows.c.Release() - rows.c = nil - } -} - -func (rows *poolRows) Err() error { - if rows.err != nil { - return rows.err - } - return rows.r.Err() -} - -func (rows *poolRows) CommandTag() pgconn.CommandTag { - return rows.r.CommandTag() -} - -func (rows *poolRows) FieldDescriptions() []pgconn.FieldDescription { - return rows.r.FieldDescriptions() -} - -func (rows *poolRows) Next() bool { - if rows.err != nil { - return false - } - - n := rows.r.Next() - if !n { - rows.Close() - } - return n -} - -func (rows *poolRows) Scan(dest ...any) error { - err := rows.r.Scan(dest...) - if err != nil { - rows.Close() - } - return err -} - -func (rows *poolRows) Values() ([]any, error) { - values, err := rows.r.Values() - if err != nil { - rows.Close() - } - return values, err -} - -func (rows *poolRows) RawValues() [][]byte { - return rows.r.RawValues() -} - -func (rows *poolRows) Conn() *pgx.Conn { - return rows.r.Conn() -} - -type poolRow struct { - r pgx.Row - c *Conn - err error -} - -func (row *poolRow) Scan(dest ...any) error { - if row.err != nil { - return row.err - } - - panicked := true - defer func() { - if panicked && row.c != nil { - row.c.Release() - } - }() - err := row.r.Scan(dest...) - panicked = false - if row.c != nil { - row.c.Release() - } - return err -} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/stat.go b/vendor/github.com/jackc/pgx/v5/pgxpool/stat.go deleted file mode 100644 index cfa0c4c56..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/stat.go +++ /dev/null @@ -1,84 +0,0 @@ -package pgxpool - -import ( - "time" - - "github.com/jackc/puddle/v2" -) - -// Stat is a snapshot of Pool statistics. -type Stat struct { - s *puddle.Stat - newConnsCount int64 - lifetimeDestroyCount int64 - idleDestroyCount int64 -} - -// AcquireCount returns the cumulative count of successful acquires from the pool. -func (s *Stat) AcquireCount() int64 { - return s.s.AcquireCount() -} - -// AcquireDuration returns the total duration of all successful acquires from -// the pool. -func (s *Stat) AcquireDuration() time.Duration { - return s.s.AcquireDuration() -} - -// AcquiredConns returns the number of currently acquired connections in the pool. -func (s *Stat) AcquiredConns() int32 { - return s.s.AcquiredResources() -} - -// CanceledAcquireCount returns the cumulative count of acquires from the pool -// that were canceled by a context. -func (s *Stat) CanceledAcquireCount() int64 { - return s.s.CanceledAcquireCount() -} - -// ConstructingConns returns the number of conns with construction in progress in -// the pool. -func (s *Stat) ConstructingConns() int32 { - return s.s.ConstructingResources() -} - -// EmptyAcquireCount returns the cumulative count of successful acquires from the pool -// that waited for a resource to be released or constructed because the pool was -// empty. -func (s *Stat) EmptyAcquireCount() int64 { - return s.s.EmptyAcquireCount() -} - -// IdleConns returns the number of currently idle conns in the pool. -func (s *Stat) IdleConns() int32 { - return s.s.IdleResources() -} - -// MaxConns returns the maximum size of the pool. -func (s *Stat) MaxConns() int32 { - return s.s.MaxResources() -} - -// TotalConns returns the total number of resources currently in the pool. -// The value is the sum of ConstructingConns, AcquiredConns, and -// IdleConns. -func (s *Stat) TotalConns() int32 { - return s.s.TotalResources() -} - -// NewConnsCount returns the cumulative count of new connections opened. -func (s *Stat) NewConnsCount() int64 { - return s.newConnsCount -} - -// MaxLifetimeDestroyCount returns the cumulative count of connections destroyed -// because they exceeded MaxConnLifetime. -func (s *Stat) MaxLifetimeDestroyCount() int64 { - return s.lifetimeDestroyCount -} - -// MaxIdleDestroyCount returns the cumulative count of connections destroyed because -// they exceeded MaxConnIdleTime. -func (s *Stat) MaxIdleDestroyCount() int64 { - return s.idleDestroyCount -} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/tracer.go b/vendor/github.com/jackc/pgx/v5/pgxpool/tracer.go deleted file mode 100644 index 78b9d15a2..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/tracer.go +++ /dev/null @@ -1,33 +0,0 @@ -package pgxpool - -import ( - "context" - - "github.com/jackc/pgx/v5" -) - -// AcquireTracer traces Acquire. -type AcquireTracer interface { - // TraceAcquireStart is called at the beginning of Acquire. - // The returned context is used for the rest of the call and will be passed to the TraceAcquireEnd. - TraceAcquireStart(ctx context.Context, pool *Pool, data TraceAcquireStartData) context.Context - // TraceAcquireEnd is called when a connection has been acquired. - TraceAcquireEnd(ctx context.Context, pool *Pool, data TraceAcquireEndData) -} - -type TraceAcquireStartData struct{} - -type TraceAcquireEndData struct { - Conn *pgx.Conn - Err error -} - -// ReleaseTracer traces Release. -type ReleaseTracer interface { - // TraceRelease is called at the beginning of Release. - TraceRelease(pool *Pool, data TraceReleaseData) -} - -type TraceReleaseData struct { - Conn *pgx.Conn -} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/tx.go b/vendor/github.com/jackc/pgx/v5/pgxpool/tx.go deleted file mode 100644 index b49e7f4d9..000000000 --- a/vendor/github.com/jackc/pgx/v5/pgxpool/tx.go +++ /dev/null @@ -1,83 +0,0 @@ -package pgxpool - -import ( - "context" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" -) - -// Tx represents a database transaction acquired from a Pool. -type Tx struct { - t pgx.Tx - c *Conn -} - -// Begin starts a pseudo nested transaction implemented with a savepoint. -func (tx *Tx) Begin(ctx context.Context) (pgx.Tx, error) { - return tx.t.Begin(ctx) -} - -// Commit commits the transaction and returns the associated connection back to the Pool. Commit will return an error -// where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is otherwise safe to call multiple times. If -// the commit fails with a rollback status (e.g. the transaction was already in a broken state) then ErrTxCommitRollback -// will be returned. -func (tx *Tx) Commit(ctx context.Context) error { - err := tx.t.Commit(ctx) - if tx.c != nil { - tx.c.Release() - tx.c = nil - } - return err -} - -// Rollback rolls back the transaction and returns the associated connection back to the Pool. Rollback will return -// where an error where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is otherwise safe to call -// multiple times. Hence, defer tx.Rollback() is safe even if tx.Commit() will be called first in a non-error condition. -func (tx *Tx) Rollback(ctx context.Context) error { - err := tx.t.Rollback(ctx) - if tx.c != nil { - tx.c.Release() - tx.c = nil - } - return err -} - -func (tx *Tx) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) { - return tx.t.CopyFrom(ctx, tableName, columnNames, rowSrc) -} - -func (tx *Tx) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { - return tx.t.SendBatch(ctx, b) -} - -func (tx *Tx) LargeObjects() pgx.LargeObjects { - return tx.t.LargeObjects() -} - -// Prepare creates a prepared statement with name and sql. If the name is empty, -// an anonymous prepared statement will be used. sql can contain placeholders -// for bound parameters. These placeholders are referenced positionally as $1, $2, etc. -// -// Prepare is idempotent; i.e. it is safe to call Prepare multiple times with the same -// name and sql arguments. This allows a code path to Prepare and Query/Exec without -// needing to first check whether the statement has already been prepared. -func (tx *Tx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) { - return tx.t.Prepare(ctx, name, sql) -} - -func (tx *Tx) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { - return tx.t.Exec(ctx, sql, arguments...) -} - -func (tx *Tx) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) { - return tx.t.Query(ctx, sql, args...) -} - -func (tx *Tx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { - return tx.t.QueryRow(ctx, sql, args...) -} - -func (tx *Tx) Conn() *pgx.Conn { - return tx.t.Conn() -} diff --git a/vendor/github.com/jackc/pgx/v5/rows.go b/vendor/github.com/jackc/pgx/v5/rows.go deleted file mode 100644 index f23625d4c..000000000 --- a/vendor/github.com/jackc/pgx/v5/rows.go +++ /dev/null @@ -1,856 +0,0 @@ -package pgx - -import ( - "context" - "errors" - "fmt" - "reflect" - "strings" - "sync" - "time" - - "github.com/jackc/pgx/v5/pgconn" - "github.com/jackc/pgx/v5/pgtype" -) - -// Rows is the result set returned from *Conn.Query. Rows must be closed before -// the *Conn can be used again. Rows are closed by explicitly calling Close(), -// calling Next() until it returns false, or when a fatal error occurs. -// -// Once a Rows is closed the only methods that may be called are Close(), Err(), -// and CommandTag(). -// -// Rows is an interface instead of a struct to allow tests to mock Query. However, -// adding a method to an interface is technically a breaking change. Because of this -// the Rows interface is partially excluded from semantic version requirements. -// Methods will not be removed or changed, but new methods may be added. -type Rows interface { - // Close closes the rows, making the connection ready for use again. It is safe - // to call Close after rows is already closed. - Close() - - // Err returns any error that occurred while reading. Err must only be called after the Rows is closed (either by - // calling Close or by Next returning false). If it is called early it may return nil even if there was an error - // executing the query. - Err() error - - // CommandTag returns the command tag from this query. It is only available after Rows is closed. - CommandTag() pgconn.CommandTag - - // FieldDescriptions returns the field descriptions of the columns. It may return nil. In particular this can occur - // when there was an error executing the query. - FieldDescriptions() []pgconn.FieldDescription - - // Next prepares the next row for reading. It returns true if there is another - // row and false if no more rows are available or a fatal error has occurred. - // It automatically closes rows when all rows are read. - // - // Callers should check rows.Err() after rows.Next() returns false to detect - // whether result-set reading ended prematurely due to an error. See - // Conn.Query for details. - // - // For simpler error handling, consider using the higher-level pgx v5 - // CollectRows() and ForEachRow() helpers instead. - Next() bool - - // Scan reads the values from the current row into dest values positionally. - // dest can include pointers to core types, values implementing the Scanner - // interface, and nil. nil will skip the value entirely. It is an error to - // call Scan without first calling Next() and checking that it returned true. - Scan(dest ...any) error - - // Values returns the decoded row values. As with Scan(), it is an error to - // call Values without first calling Next() and checking that it returned - // true. - Values() ([]any, error) - - // RawValues returns the unparsed bytes of the row values. The returned data is only valid until the next Next - // call or the Rows is closed. - RawValues() [][]byte - - // Conn returns the underlying *Conn on which the query was executed. This may return nil if Rows did not come from a - // *Conn (e.g. if it was created by RowsFromResultReader) - Conn() *Conn -} - -// Row is a convenience wrapper over Rows that is returned by QueryRow. -// -// Row is an interface instead of a struct to allow tests to mock QueryRow. However, -// adding a method to an interface is technically a breaking change. Because of this -// the Row interface is partially excluded from semantic version requirements. -// Methods will not be removed or changed, but new methods may be added. -type Row interface { - // Scan works the same as Rows. with the following exceptions. If no - // rows were found it returns ErrNoRows. If multiple rows are returned it - // ignores all but the first. - Scan(dest ...any) error -} - -// RowScanner scans an entire row at a time into the RowScanner. -type RowScanner interface { - // ScanRows scans the row. - ScanRow(rows Rows) error -} - -// connRow implements the Row interface for Conn.QueryRow. -type connRow baseRows - -func (r *connRow) Scan(dest ...any) (err error) { - rows := (*baseRows)(r) - - if rows.Err() != nil { - return rows.Err() - } - - for _, d := range dest { - if _, ok := d.(*pgtype.DriverBytes); ok { - rows.Close() - return fmt.Errorf("cannot scan into *pgtype.DriverBytes from QueryRow") - } - } - - if !rows.Next() { - if rows.Err() == nil { - return ErrNoRows - } - return rows.Err() - } - - rows.Scan(dest...) - rows.Close() - return rows.Err() -} - -// baseRows implements the Rows interface for Conn.Query. -type baseRows struct { - typeMap *pgtype.Map - resultReader *pgconn.ResultReader - - values [][]byte - - commandTag pgconn.CommandTag - err error - closed bool - - scanPlans []pgtype.ScanPlan - scanTypes []reflect.Type - - conn *Conn - multiResultReader *pgconn.MultiResultReader - - queryTracer QueryTracer - batchTracer BatchTracer - ctx context.Context - startTime time.Time - sql string - args []any - rowCount int -} - -func (rows *baseRows) FieldDescriptions() []pgconn.FieldDescription { - return rows.resultReader.FieldDescriptions() -} - -func (rows *baseRows) Close() { - if rows.closed { - return - } - - rows.closed = true - - if rows.resultReader != nil { - var closeErr error - rows.commandTag, closeErr = rows.resultReader.Close() - if rows.err == nil { - rows.err = closeErr - } - } - - if rows.multiResultReader != nil { - closeErr := rows.multiResultReader.Close() - if rows.err == nil { - rows.err = closeErr - } - } - - if rows.err != nil && rows.conn != nil && rows.sql != "" { - if sc := rows.conn.statementCache; sc != nil { - sc.Invalidate(rows.sql) - } - - if sc := rows.conn.descriptionCache; sc != nil { - sc.Invalidate(rows.sql) - } - } - - if rows.batchTracer != nil { - rows.batchTracer.TraceBatchQuery(rows.ctx, rows.conn, TraceBatchQueryData{SQL: rows.sql, Args: rows.args, CommandTag: rows.commandTag, Err: rows.err}) - } else if rows.queryTracer != nil { - rows.queryTracer.TraceQueryEnd(rows.ctx, rows.conn, TraceQueryEndData{rows.commandTag, rows.err}) - } -} - -func (rows *baseRows) CommandTag() pgconn.CommandTag { - return rows.commandTag -} - -func (rows *baseRows) Err() error { - return rows.err -} - -// fatal signals an error occurred after the query was sent to the server. It -// closes the rows automatically. -func (rows *baseRows) fatal(err error) { - if rows.err != nil { - return - } - - rows.err = err - rows.Close() -} - -func (rows *baseRows) Next() bool { - if rows.closed { - return false - } - - if rows.resultReader.NextRow() { - rows.rowCount++ - rows.values = rows.resultReader.Values() - return true - } else { - rows.Close() - return false - } -} - -func (rows *baseRows) Scan(dest ...any) error { - m := rows.typeMap - fieldDescriptions := rows.FieldDescriptions() - values := rows.values - - if len(fieldDescriptions) != len(values) { - err := fmt.Errorf("number of field descriptions must equal number of values, got %d and %d", len(fieldDescriptions), len(values)) - rows.fatal(err) - return err - } - - if len(dest) == 1 { - if rc, ok := dest[0].(RowScanner); ok { - err := rc.ScanRow(rows) - if err != nil { - rows.fatal(err) - } - return err - } - } - - if len(fieldDescriptions) != len(dest) { - err := fmt.Errorf("number of field descriptions must equal number of destinations, got %d and %d", len(fieldDescriptions), len(dest)) - rows.fatal(err) - return err - } - - if rows.scanPlans == nil { - rows.scanPlans = make([]pgtype.ScanPlan, len(values)) - rows.scanTypes = make([]reflect.Type, len(values)) - for i := range dest { - rows.scanPlans[i] = m.PlanScan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, dest[i]) - rows.scanTypes[i] = reflect.TypeOf(dest[i]) - } - } - - for i, dst := range dest { - if dst == nil { - continue - } - - if rows.scanTypes[i] != reflect.TypeOf(dst) { - rows.scanPlans[i] = m.PlanScan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, dest[i]) - rows.scanTypes[i] = reflect.TypeOf(dest[i]) - } - - err := rows.scanPlans[i].Scan(values[i], dst) - if err != nil { - err = ScanArgError{ColumnIndex: i, Err: err} - rows.fatal(err) - return err - } - } - - return nil -} - -func (rows *baseRows) Values() ([]any, error) { - if rows.closed { - return nil, errors.New("rows is closed") - } - - values := make([]any, 0, len(rows.FieldDescriptions())) - - for i := range rows.FieldDescriptions() { - buf := rows.values[i] - fd := &rows.FieldDescriptions()[i] - - if buf == nil { - values = append(values, nil) - continue - } - - if dt, ok := rows.typeMap.TypeForOID(fd.DataTypeOID); ok { - value, err := dt.Codec.DecodeValue(rows.typeMap, fd.DataTypeOID, fd.Format, buf) - if err != nil { - rows.fatal(err) - } - values = append(values, value) - } else { - switch fd.Format { - case TextFormatCode: - values = append(values, string(buf)) - case BinaryFormatCode: - newBuf := make([]byte, len(buf)) - copy(newBuf, buf) - values = append(values, newBuf) - default: - rows.fatal(errors.New("unknown format code")) - } - } - - if rows.Err() != nil { - return nil, rows.Err() - } - } - - return values, rows.Err() -} - -func (rows *baseRows) RawValues() [][]byte { - return rows.values -} - -func (rows *baseRows) Conn() *Conn { - return rows.conn -} - -type ScanArgError struct { - ColumnIndex int - Err error -} - -func (e ScanArgError) Error() string { - return fmt.Sprintf("can't scan into dest[%d]: %v", e.ColumnIndex, e.Err) -} - -func (e ScanArgError) Unwrap() error { - return e.Err -} - -// ScanRow decodes raw row data into dest. It can be used to scan rows read from the lower level pgconn interface. -// -// typeMap - OID to Go type mapping. -// fieldDescriptions - OID and format of values -// values - the raw data as returned from the PostgreSQL server -// dest - the destination that values will be decoded into -func ScanRow(typeMap *pgtype.Map, fieldDescriptions []pgconn.FieldDescription, values [][]byte, dest ...any) error { - if len(fieldDescriptions) != len(values) { - return fmt.Errorf("number of field descriptions must equal number of values, got %d and %d", len(fieldDescriptions), len(values)) - } - if len(fieldDescriptions) != len(dest) { - return fmt.Errorf("number of field descriptions must equal number of destinations, got %d and %d", len(fieldDescriptions), len(dest)) - } - - for i, d := range dest { - if d == nil { - continue - } - - err := typeMap.Scan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, values[i], d) - if err != nil { - return ScanArgError{ColumnIndex: i, Err: err} - } - } - - return nil -} - -// RowsFromResultReader returns a Rows that will read from values resultReader and decode with typeMap. It can be used -// to read from the lower level pgconn interface. -func RowsFromResultReader(typeMap *pgtype.Map, resultReader *pgconn.ResultReader) Rows { - return &baseRows{ - typeMap: typeMap, - resultReader: resultReader, - } -} - -// ForEachRow iterates through rows. For each row it scans into the elements of scans and calls fn. If any row -// fails to scan or fn returns an error the query will be aborted and the error will be returned. Rows will be closed -// when ForEachRow returns. -func ForEachRow(rows Rows, scans []any, fn func() error) (pgconn.CommandTag, error) { - defer rows.Close() - - for rows.Next() { - err := rows.Scan(scans...) - if err != nil { - return pgconn.CommandTag{}, err - } - - err = fn() - if err != nil { - return pgconn.CommandTag{}, err - } - } - - if err := rows.Err(); err != nil { - return pgconn.CommandTag{}, err - } - - return rows.CommandTag(), nil -} - -// CollectableRow is the subset of Rows methods that a RowToFunc is allowed to call. -type CollectableRow interface { - FieldDescriptions() []pgconn.FieldDescription - Scan(dest ...any) error - Values() ([]any, error) - RawValues() [][]byte -} - -// RowToFunc is a function that scans or otherwise converts row to a T. -type RowToFunc[T any] func(row CollectableRow) (T, error) - -// AppendRows iterates through rows, calling fn for each row, and appending the results into a slice of T. -// -// This function closes the rows automatically on return. -func AppendRows[T any, S ~[]T](slice S, rows Rows, fn RowToFunc[T]) (S, error) { - defer rows.Close() - - for rows.Next() { - value, err := fn(rows) - if err != nil { - return nil, err - } - slice = append(slice, value) - } - - if err := rows.Err(); err != nil { - return nil, err - } - - return slice, nil -} - -// CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T. -// -// This function closes the rows automatically on return. -func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) { - return AppendRows([]T{}, rows, fn) -} - -// CollectOneRow calls fn for the first row in rows and returns the result. If no rows are found returns an error where errors.Is(ErrNoRows) is true. -// CollectOneRow is to CollectRows as QueryRow is to Query. -// -// This function closes the rows automatically on return. -func CollectOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) { - defer rows.Close() - - var value T - var err error - - if !rows.Next() { - if err = rows.Err(); err != nil { - return value, err - } - return value, ErrNoRows - } - - value, err = fn(rows) - if err != nil { - return value, err - } - - rows.Close() - return value, rows.Err() -} - -// CollectExactlyOneRow calls fn for the first row in rows and returns the result. -// - If no rows are found returns an error where errors.Is(ErrNoRows) is true. -// - If more than 1 row is found returns an error where errors.Is(ErrTooManyRows) is true. -// -// This function closes the rows automatically on return. -func CollectExactlyOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) { - defer rows.Close() - - var ( - err error - value T - ) - - if !rows.Next() { - if err = rows.Err(); err != nil { - return value, err - } - - return value, ErrNoRows - } - - value, err = fn(rows) - if err != nil { - return value, err - } - - if rows.Next() { - var zero T - - return zero, ErrTooManyRows - } - - return value, rows.Err() -} - -// RowTo returns a T scanned from row. -func RowTo[T any](row CollectableRow) (T, error) { - var value T - err := row.Scan(&value) - return value, err -} - -// RowTo returns a the address of a T scanned from row. -func RowToAddrOf[T any](row CollectableRow) (*T, error) { - var value T - err := row.Scan(&value) - return &value, err -} - -// RowToMap returns a map scanned from row. -func RowToMap(row CollectableRow) (map[string]any, error) { - var value map[string]any - err := row.Scan((*mapRowScanner)(&value)) - return value, err -} - -type mapRowScanner map[string]any - -func (rs *mapRowScanner) ScanRow(rows Rows) error { - values, err := rows.Values() - if err != nil { - return err - } - - *rs = make(mapRowScanner, len(values)) - - for i := range values { - (*rs)[string(rows.FieldDescriptions()[i].Name)] = values[i] - } - - return nil -} - -// RowToStructByPos returns a T scanned from row. T must be a struct. T must have the same number a public fields as row -// has fields. The row and T fields will be matched by position. If the "db" struct tag is "-" then the field will be -// ignored. -func RowToStructByPos[T any](row CollectableRow) (T, error) { - var value T - err := (&positionalStructRowScanner{ptrToStruct: &value}).ScanRow(row) - return value, err -} - -// RowToAddrOfStructByPos returns the address of a T scanned from row. T must be a struct. T must have the same number a -// public fields as row has fields. The row and T fields will be matched by position. If the "db" struct tag is "-" then -// the field will be ignored. -func RowToAddrOfStructByPos[T any](row CollectableRow) (*T, error) { - var value T - err := (&positionalStructRowScanner{ptrToStruct: &value}).ScanRow(row) - return &value, err -} - -type positionalStructRowScanner struct { - ptrToStruct any -} - -func (rs *positionalStructRowScanner) ScanRow(rows CollectableRow) error { - typ := reflect.TypeOf(rs.ptrToStruct).Elem() - fields := lookupStructFields(typ) - if len(rows.RawValues()) > len(fields) { - return fmt.Errorf( - "got %d values, but dst struct has only %d fields", - len(rows.RawValues()), - len(fields), - ) - } - scanTargets := setupStructScanTargets(rs.ptrToStruct, fields) - return rows.Scan(scanTargets...) -} - -// Map from reflect.Type -> []structRowField -var positionalStructFieldMap sync.Map - -func lookupStructFields(t reflect.Type) []structRowField { - if cached, ok := positionalStructFieldMap.Load(t); ok { - return cached.([]structRowField) - } - - fieldStack := make([]int, 0, 1) - fields := computeStructFields(t, make([]structRowField, 0, t.NumField()), &fieldStack) - fieldsIface, _ := positionalStructFieldMap.LoadOrStore(t, fields) - return fieldsIface.([]structRowField) -} - -func computeStructFields( - t reflect.Type, - fields []structRowField, - fieldStack *[]int, -) []structRowField { - tail := len(*fieldStack) - *fieldStack = append(*fieldStack, 0) - for i := 0; i < t.NumField(); i++ { - sf := t.Field(i) - (*fieldStack)[tail] = i - // Handle anonymous struct embedding, but do not try to handle embedded pointers. - if sf.Anonymous && sf.Type.Kind() == reflect.Struct { - fields = computeStructFields(sf.Type, fields, fieldStack) - } else if sf.PkgPath == "" { - dbTag, _ := sf.Tag.Lookup(structTagKey) - if dbTag == "-" { - // Field is ignored, skip it. - continue - } - fields = append(fields, structRowField{ - path: append([]int(nil), *fieldStack...), - }) - } - } - *fieldStack = (*fieldStack)[:tail] - return fields -} - -// RowToStructByName returns a T scanned from row. T must be a struct. T must have the same number of named public -// fields as row has fields. The row and T fields will be matched by name. The match is case-insensitive. The database -// column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" then the field will be ignored. -func RowToStructByName[T any](row CollectableRow) (T, error) { - var value T - err := (&namedStructRowScanner{ptrToStruct: &value}).ScanRow(row) - return value, err -} - -// RowToAddrOfStructByName returns the address of a T scanned from row. T must be a struct. T must have the same number -// of named public fields as row has fields. The row and T fields will be matched by name. The match is -// case-insensitive. The database column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" -// then the field will be ignored. -func RowToAddrOfStructByName[T any](row CollectableRow) (*T, error) { - var value T - err := (&namedStructRowScanner{ptrToStruct: &value}).ScanRow(row) - return &value, err -} - -// RowToStructByNameLax returns a T scanned from row. T must be a struct. T must have greater than or equal number of named public -// fields as row has fields. The row and T fields will be matched by name. The match is case-insensitive. The database -// column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" then the field will be ignored. -func RowToStructByNameLax[T any](row CollectableRow) (T, error) { - var value T - err := (&namedStructRowScanner{ptrToStruct: &value, lax: true}).ScanRow(row) - return value, err -} - -// RowToAddrOfStructByNameLax returns the address of a T scanned from row. T must be a struct. T must have greater than or -// equal number of named public fields as row has fields. The row and T fields will be matched by name. The match is -// case-insensitive. The database column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" -// then the field will be ignored. -func RowToAddrOfStructByNameLax[T any](row CollectableRow) (*T, error) { - var value T - err := (&namedStructRowScanner{ptrToStruct: &value, lax: true}).ScanRow(row) - return &value, err -} - -type namedStructRowScanner struct { - ptrToStruct any - lax bool -} - -func (rs *namedStructRowScanner) ScanRow(rows CollectableRow) error { - typ := reflect.TypeOf(rs.ptrToStruct).Elem() - fldDescs := rows.FieldDescriptions() - namedStructFields, err := lookupNamedStructFields(typ, fldDescs) - if err != nil { - return err - } - if !rs.lax && namedStructFields.missingField != "" { - return fmt.Errorf("cannot find field %s in returned row", namedStructFields.missingField) - } - fields := namedStructFields.fields - scanTargets := setupStructScanTargets(rs.ptrToStruct, fields) - return rows.Scan(scanTargets...) -} - -// Map from namedStructFieldMap -> *namedStructFields -var namedStructFieldMap sync.Map - -type namedStructFieldsKey struct { - t reflect.Type - colNames string -} - -type namedStructFields struct { - fields []structRowField - // missingField is the first field from the struct without a corresponding row field. - // This is used to construct the correct error message for non-lax queries. - missingField string -} - -func lookupNamedStructFields( - t reflect.Type, - fldDescs []pgconn.FieldDescription, -) (*namedStructFields, error) { - key := namedStructFieldsKey{ - t: t, - colNames: joinFieldNames(fldDescs), - } - if cached, ok := namedStructFieldMap.Load(key); ok { - return cached.(*namedStructFields), nil - } - - // We could probably do two-levels of caching, where we compute the key -> fields mapping - // for a type only once, cache it by type, then use that to compute the column -> fields - // mapping for a given set of columns. - fieldStack := make([]int, 0, 1) - fields, missingField := computeNamedStructFields( - fldDescs, - t, - make([]structRowField, len(fldDescs)), - &fieldStack, - ) - for i, f := range fields { - if f.path == nil { - return nil, fmt.Errorf( - "struct doesn't have corresponding row field %s", - fldDescs[i].Name, - ) - } - } - - fieldsIface, _ := namedStructFieldMap.LoadOrStore( - key, - &namedStructFields{fields: fields, missingField: missingField}, - ) - return fieldsIface.(*namedStructFields), nil -} - -func joinFieldNames(fldDescs []pgconn.FieldDescription) string { - switch len(fldDescs) { - case 0: - return "" - case 1: - return fldDescs[0].Name - } - - totalSize := len(fldDescs) - 1 // Space for separator bytes. - for _, d := range fldDescs { - totalSize += len(d.Name) - } - var b strings.Builder - b.Grow(totalSize) - b.WriteString(fldDescs[0].Name) - for _, d := range fldDescs[1:] { - b.WriteByte(0) // Join with NUL byte as it's (presumably) not a valid column character. - b.WriteString(d.Name) - } - return b.String() -} - -func computeNamedStructFields( - fldDescs []pgconn.FieldDescription, - t reflect.Type, - fields []structRowField, - fieldStack *[]int, -) ([]structRowField, string) { - var missingField string - tail := len(*fieldStack) - *fieldStack = append(*fieldStack, 0) - for i := 0; i < t.NumField(); i++ { - sf := t.Field(i) - (*fieldStack)[tail] = i - if sf.PkgPath != "" && !sf.Anonymous { - // Field is unexported, skip it. - continue - } - // Handle anonymous struct embedding, but do not try to handle embedded pointers. - if sf.Anonymous && sf.Type.Kind() == reflect.Struct { - var missingSubField string - fields, missingSubField = computeNamedStructFields( - fldDescs, - sf.Type, - fields, - fieldStack, - ) - if missingField == "" { - missingField = missingSubField - } - } else { - dbTag, dbTagPresent := sf.Tag.Lookup(structTagKey) - if dbTagPresent { - dbTag, _, _ = strings.Cut(dbTag, ",") - } - if dbTag == "-" { - // Field is ignored, skip it. - continue - } - colName := dbTag - if !dbTagPresent { - colName = sf.Name - } - fpos := fieldPosByName(fldDescs, colName, !dbTagPresent) - if fpos == -1 { - if missingField == "" { - missingField = colName - } - continue - } - fields[fpos] = structRowField{ - path: append([]int(nil), *fieldStack...), - } - } - } - *fieldStack = (*fieldStack)[:tail] - - return fields, missingField -} - -const structTagKey = "db" - -func fieldPosByName(fldDescs []pgconn.FieldDescription, field string, normalize bool) (i int) { - i = -1 - - if normalize { - field = strings.ReplaceAll(field, "_", "") - } - for i, desc := range fldDescs { - if normalize { - if strings.EqualFold(strings.ReplaceAll(desc.Name, "_", ""), field) { - return i - } - } else { - if desc.Name == field { - return i - } - } - } - return -} - -// structRowField describes a field of a struct. -// -// TODO: It would be a bit more efficient to track the path using the pointer -// offset within the (outermost) struct and use unsafe.Pointer arithmetic to -// construct references when scanning rows. However, it's not clear it's worth -// using unsafe for this. -type structRowField struct { - path []int -} - -func setupStructScanTargets(receiver any, fields []structRowField) []any { - scanTargets := make([]any, len(fields)) - v := reflect.ValueOf(receiver).Elem() - for i, f := range fields { - scanTargets[i] = v.FieldByIndex(f.path).Addr().Interface() - } - return scanTargets -} diff --git a/vendor/github.com/jackc/pgx/v5/tracer.go b/vendor/github.com/jackc/pgx/v5/tracer.go deleted file mode 100644 index 58ca99f7e..000000000 --- a/vendor/github.com/jackc/pgx/v5/tracer.go +++ /dev/null @@ -1,107 +0,0 @@ -package pgx - -import ( - "context" - - "github.com/jackc/pgx/v5/pgconn" -) - -// QueryTracer traces Query, QueryRow, and Exec. -type QueryTracer interface { - // TraceQueryStart is called at the beginning of Query, QueryRow, and Exec calls. The returned context is used for the - // rest of the call and will be passed to TraceQueryEnd. - TraceQueryStart(ctx context.Context, conn *Conn, data TraceQueryStartData) context.Context - - TraceQueryEnd(ctx context.Context, conn *Conn, data TraceQueryEndData) -} - -type TraceQueryStartData struct { - SQL string - Args []any -} - -type TraceQueryEndData struct { - CommandTag pgconn.CommandTag - Err error -} - -// BatchTracer traces SendBatch. -type BatchTracer interface { - // TraceBatchStart is called at the beginning of SendBatch calls. The returned context is used for the - // rest of the call and will be passed to TraceBatchQuery and TraceBatchEnd. - TraceBatchStart(ctx context.Context, conn *Conn, data TraceBatchStartData) context.Context - - TraceBatchQuery(ctx context.Context, conn *Conn, data TraceBatchQueryData) - TraceBatchEnd(ctx context.Context, conn *Conn, data TraceBatchEndData) -} - -type TraceBatchStartData struct { - Batch *Batch -} - -type TraceBatchQueryData struct { - SQL string - Args []any - CommandTag pgconn.CommandTag - Err error -} - -type TraceBatchEndData struct { - Err error -} - -// CopyFromTracer traces CopyFrom. -type CopyFromTracer interface { - // TraceCopyFromStart is called at the beginning of CopyFrom calls. The returned context is used for the - // rest of the call and will be passed to TraceCopyFromEnd. - TraceCopyFromStart(ctx context.Context, conn *Conn, data TraceCopyFromStartData) context.Context - - TraceCopyFromEnd(ctx context.Context, conn *Conn, data TraceCopyFromEndData) -} - -type TraceCopyFromStartData struct { - TableName Identifier - ColumnNames []string -} - -type TraceCopyFromEndData struct { - CommandTag pgconn.CommandTag - Err error -} - -// PrepareTracer traces Prepare. -type PrepareTracer interface { - // TracePrepareStart is called at the beginning of Prepare calls. The returned context is used for the - // rest of the call and will be passed to TracePrepareEnd. - TracePrepareStart(ctx context.Context, conn *Conn, data TracePrepareStartData) context.Context - - TracePrepareEnd(ctx context.Context, conn *Conn, data TracePrepareEndData) -} - -type TracePrepareStartData struct { - Name string - SQL string -} - -type TracePrepareEndData struct { - AlreadyPrepared bool - Err error -} - -// ConnectTracer traces Connect and ConnectConfig. -type ConnectTracer interface { - // TraceConnectStart is called at the beginning of Connect and ConnectConfig calls. The returned context is used for - // the rest of the call and will be passed to TraceConnectEnd. - TraceConnectStart(ctx context.Context, data TraceConnectStartData) context.Context - - TraceConnectEnd(ctx context.Context, data TraceConnectEndData) -} - -type TraceConnectStartData struct { - ConnConfig *ConnConfig -} - -type TraceConnectEndData struct { - Conn *Conn - Err error -} diff --git a/vendor/github.com/jackc/pgx/v5/tx.go b/vendor/github.com/jackc/pgx/v5/tx.go deleted file mode 100644 index 168d7ba6c..000000000 --- a/vendor/github.com/jackc/pgx/v5/tx.go +++ /dev/null @@ -1,443 +0,0 @@ -package pgx - -import ( - "context" - "errors" - "fmt" - "strconv" - "strings" - - "github.com/jackc/pgx/v5/pgconn" -) - -// TxIsoLevel is the transaction isolation level (serializable, repeatable read, read committed or read uncommitted) -type TxIsoLevel string - -// Transaction isolation levels -const ( - Serializable TxIsoLevel = "serializable" - RepeatableRead TxIsoLevel = "repeatable read" - ReadCommitted TxIsoLevel = "read committed" - ReadUncommitted TxIsoLevel = "read uncommitted" -) - -// TxAccessMode is the transaction access mode (read write or read only) -type TxAccessMode string - -// Transaction access modes -const ( - ReadWrite TxAccessMode = "read write" - ReadOnly TxAccessMode = "read only" -) - -// TxDeferrableMode is the transaction deferrable mode (deferrable or not deferrable) -type TxDeferrableMode string - -// Transaction deferrable modes -const ( - Deferrable TxDeferrableMode = "deferrable" - NotDeferrable TxDeferrableMode = "not deferrable" -) - -// TxOptions are transaction modes within a transaction block -type TxOptions struct { - IsoLevel TxIsoLevel - AccessMode TxAccessMode - DeferrableMode TxDeferrableMode - - // BeginQuery is the SQL query that will be executed to begin the transaction. This allows using non-standard syntax - // such as BEGIN PRIORITY HIGH with CockroachDB. If set this will override the other settings. - BeginQuery string - // CommitQuery is the SQL query that will be executed to commit the transaction. - CommitQuery string -} - -var emptyTxOptions TxOptions - -func (txOptions TxOptions) beginSQL() string { - if txOptions == emptyTxOptions { - return "begin" - } - - if txOptions.BeginQuery != "" { - return txOptions.BeginQuery - } - - var buf strings.Builder - buf.Grow(64) // 64 - maximum length of string with available options - buf.WriteString("begin") - - if txOptions.IsoLevel != "" { - buf.WriteString(" isolation level ") - buf.WriteString(string(txOptions.IsoLevel)) - } - if txOptions.AccessMode != "" { - buf.WriteByte(' ') - buf.WriteString(string(txOptions.AccessMode)) - } - if txOptions.DeferrableMode != "" { - buf.WriteByte(' ') - buf.WriteString(string(txOptions.DeferrableMode)) - } - - return buf.String() -} - -var ErrTxClosed = errors.New("tx is closed") - -// ErrTxCommitRollback occurs when an error has occurred in a transaction and -// Commit() is called. PostgreSQL accepts COMMIT on aborted transactions, but -// it is treated as ROLLBACK. -var ErrTxCommitRollback = errors.New("commit unexpectedly resulted in rollback") - -// Begin starts a transaction. Unlike database/sql, the context only affects the begin command. i.e. there is no -// auto-rollback on context cancellation. -func (c *Conn) Begin(ctx context.Context) (Tx, error) { - return c.BeginTx(ctx, TxOptions{}) -} - -// BeginTx starts a transaction with txOptions determining the transaction mode. Unlike database/sql, the context only -// affects the begin command. i.e. there is no auto-rollback on context cancellation. -func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) { - _, err := c.Exec(ctx, txOptions.beginSQL()) - if err != nil { - // begin should never fail unless there is an underlying connection issue or - // a context timeout. In either case, the connection is possibly broken. - c.die(errors.New("failed to begin transaction")) - return nil, err - } - - return &dbTx{ - conn: c, - commitQuery: txOptions.CommitQuery, - }, nil -} - -// Tx represents a database transaction. -// -// Tx is an interface instead of a struct to enable connection pools to be implemented without relying on internal pgx -// state, to support pseudo-nested transactions with savepoints, and to allow tests to mock transactions. However, -// adding a method to an interface is technically a breaking change. If new methods are added to Conn it may be -// desirable to add them to Tx as well. Because of this the Tx interface is partially excluded from semantic version -// requirements. Methods will not be removed or changed, but new methods may be added. -type Tx interface { - // Begin starts a pseudo nested transaction. - Begin(ctx context.Context) (Tx, error) - - // Commit commits the transaction if this is a real transaction or releases the savepoint if this is a pseudo nested - // transaction. Commit will return an error where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is - // otherwise safe to call multiple times. If the commit fails with a rollback status (e.g. the transaction was already - // in a broken state) then an error where errors.Is(ErrTxCommitRollback) is true will be returned. - Commit(ctx context.Context) error - - // Rollback rolls back the transaction if this is a real transaction or rolls back to the savepoint if this is a - // pseudo nested transaction. Rollback will return an error where errors.Is(ErrTxClosed) is true if the Tx is already - // closed, but is otherwise safe to call multiple times. Hence, a defer tx.Rollback() is safe even if tx.Commit() will - // be called first in a non-error condition. Any other failure of a real transaction will result in the connection - // being closed. - Rollback(ctx context.Context) error - - CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) - SendBatch(ctx context.Context, b *Batch) BatchResults - LargeObjects() LargeObjects - - Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) - - Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) - Query(ctx context.Context, sql string, args ...any) (Rows, error) - QueryRow(ctx context.Context, sql string, args ...any) Row - - // Conn returns the underlying *Conn that on which this transaction is executing. - Conn() *Conn -} - -// dbTx represents a database transaction. -// -// All dbTx methods return ErrTxClosed if Commit or Rollback has already been -// called on the dbTx. -type dbTx struct { - conn *Conn - savepointNum int64 - closed bool - commitQuery string -} - -// Begin starts a pseudo nested transaction implemented with a savepoint. -func (tx *dbTx) Begin(ctx context.Context) (Tx, error) { - if tx.closed { - return nil, ErrTxClosed - } - - tx.savepointNum++ - _, err := tx.conn.Exec(ctx, "savepoint sp_"+strconv.FormatInt(tx.savepointNum, 10)) - if err != nil { - return nil, err - } - - return &dbSimulatedNestedTx{tx: tx, savepointNum: tx.savepointNum}, nil -} - -// Commit commits the transaction. -func (tx *dbTx) Commit(ctx context.Context) error { - if tx.closed { - return ErrTxClosed - } - - commandSQL := "commit" - if tx.commitQuery != "" { - commandSQL = tx.commitQuery - } - - commandTag, err := tx.conn.Exec(ctx, commandSQL) - tx.closed = true - if err != nil { - if tx.conn.PgConn().TxStatus() != 'I' { - _ = tx.conn.Close(ctx) // already have error to return - } - return err - } - if commandTag.String() == "ROLLBACK" { - return ErrTxCommitRollback - } - - return nil -} - -// Rollback rolls back the transaction. Rollback will return ErrTxClosed if the -// Tx is already closed, but is otherwise safe to call multiple times. Hence, a -// defer tx.Rollback() is safe even if tx.Commit() will be called first in a -// non-error condition. -func (tx *dbTx) Rollback(ctx context.Context) error { - if tx.closed { - return ErrTxClosed - } - - _, err := tx.conn.Exec(ctx, "rollback") - tx.closed = true - if err != nil { - // A rollback failure leaves the connection in an undefined state - tx.conn.die(fmt.Errorf("rollback failed: %w", err)) - return err - } - - return nil -} - -// Exec delegates to the underlying *Conn -func (tx *dbTx) Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) { - if tx.closed { - return pgconn.CommandTag{}, ErrTxClosed - } - - return tx.conn.Exec(ctx, sql, arguments...) -} - -// Prepare delegates to the underlying *Conn -func (tx *dbTx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) { - if tx.closed { - return nil, ErrTxClosed - } - - return tx.conn.Prepare(ctx, name, sql) -} - -// Query delegates to the underlying *Conn -func (tx *dbTx) Query(ctx context.Context, sql string, args ...any) (Rows, error) { - if tx.closed { - // Because checking for errors can be deferred to the *Rows, build one with the error - err := ErrTxClosed - return &baseRows{closed: true, err: err}, err - } - - return tx.conn.Query(ctx, sql, args...) -} - -// QueryRow delegates to the underlying *Conn -func (tx *dbTx) QueryRow(ctx context.Context, sql string, args ...any) Row { - rows, _ := tx.Query(ctx, sql, args...) - return (*connRow)(rows.(*baseRows)) -} - -// CopyFrom delegates to the underlying *Conn -func (tx *dbTx) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) { - if tx.closed { - return 0, ErrTxClosed - } - - return tx.conn.CopyFrom(ctx, tableName, columnNames, rowSrc) -} - -// SendBatch delegates to the underlying *Conn -func (tx *dbTx) SendBatch(ctx context.Context, b *Batch) BatchResults { - if tx.closed { - return &batchResults{err: ErrTxClosed} - } - - return tx.conn.SendBatch(ctx, b) -} - -// LargeObjects returns a LargeObjects instance for the transaction. -func (tx *dbTx) LargeObjects() LargeObjects { - return LargeObjects{tx: tx} -} - -func (tx *dbTx) Conn() *Conn { - return tx.conn -} - -// dbSimulatedNestedTx represents a simulated nested transaction implemented by a savepoint. -type dbSimulatedNestedTx struct { - tx Tx - savepointNum int64 - closed bool -} - -// Begin starts a pseudo nested transaction implemented with a savepoint. -func (sp *dbSimulatedNestedTx) Begin(ctx context.Context) (Tx, error) { - if sp.closed { - return nil, ErrTxClosed - } - - return sp.tx.Begin(ctx) -} - -// Commit releases the savepoint essentially committing the pseudo nested transaction. -func (sp *dbSimulatedNestedTx) Commit(ctx context.Context) error { - if sp.closed { - return ErrTxClosed - } - - _, err := sp.Exec(ctx, "release savepoint sp_"+strconv.FormatInt(sp.savepointNum, 10)) - sp.closed = true - return err -} - -// Rollback rolls back to the savepoint essentially rolling back the pseudo nested transaction. Rollback will return -// ErrTxClosed if the dbSavepoint is already closed, but is otherwise safe to call multiple times. Hence, a defer sp.Rollback() -// is safe even if sp.Commit() will be called first in a non-error condition. -func (sp *dbSimulatedNestedTx) Rollback(ctx context.Context) error { - if sp.closed { - return ErrTxClosed - } - - _, err := sp.Exec(ctx, "rollback to savepoint sp_"+strconv.FormatInt(sp.savepointNum, 10)) - sp.closed = true - return err -} - -// Exec delegates to the underlying Tx -func (sp *dbSimulatedNestedTx) Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) { - if sp.closed { - return pgconn.CommandTag{}, ErrTxClosed - } - - return sp.tx.Exec(ctx, sql, arguments...) -} - -// Prepare delegates to the underlying Tx -func (sp *dbSimulatedNestedTx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) { - if sp.closed { - return nil, ErrTxClosed - } - - return sp.tx.Prepare(ctx, name, sql) -} - -// Query delegates to the underlying Tx -func (sp *dbSimulatedNestedTx) Query(ctx context.Context, sql string, args ...any) (Rows, error) { - if sp.closed { - // Because checking for errors can be deferred to the *Rows, build one with the error - err := ErrTxClosed - return &baseRows{closed: true, err: err}, err - } - - return sp.tx.Query(ctx, sql, args...) -} - -// QueryRow delegates to the underlying Tx -func (sp *dbSimulatedNestedTx) QueryRow(ctx context.Context, sql string, args ...any) Row { - rows, _ := sp.Query(ctx, sql, args...) - return (*connRow)(rows.(*baseRows)) -} - -// CopyFrom delegates to the underlying *Conn -func (sp *dbSimulatedNestedTx) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) { - if sp.closed { - return 0, ErrTxClosed - } - - return sp.tx.CopyFrom(ctx, tableName, columnNames, rowSrc) -} - -// SendBatch delegates to the underlying *Conn -func (sp *dbSimulatedNestedTx) SendBatch(ctx context.Context, b *Batch) BatchResults { - if sp.closed { - return &batchResults{err: ErrTxClosed} - } - - return sp.tx.SendBatch(ctx, b) -} - -func (sp *dbSimulatedNestedTx) LargeObjects() LargeObjects { - return LargeObjects{tx: sp} -} - -func (sp *dbSimulatedNestedTx) Conn() *Conn { - return sp.tx.Conn() -} - -// BeginFunc calls Begin on db and then calls fn. If fn does not return an error then it calls Commit on db. If fn -// returns an error it calls Rollback on db. The context will be used when executing the transaction control statements -// (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn. -func BeginFunc( - ctx context.Context, - db interface { - Begin(ctx context.Context) (Tx, error) - }, - fn func(Tx) error, -) (err error) { - var tx Tx - tx, err = db.Begin(ctx) - if err != nil { - return err - } - - return beginFuncExec(ctx, tx, fn) -} - -// BeginTxFunc calls BeginTx on db and then calls fn. If fn does not return an error then it calls Commit on db. If fn -// returns an error it calls Rollback on db. The context will be used when executing the transaction control statements -// (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn. -func BeginTxFunc( - ctx context.Context, - db interface { - BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) - }, - txOptions TxOptions, - fn func(Tx) error, -) (err error) { - var tx Tx - tx, err = db.BeginTx(ctx, txOptions) - if err != nil { - return err - } - - return beginFuncExec(ctx, tx, fn) -} - -func beginFuncExec(ctx context.Context, tx Tx, fn func(Tx) error) (err error) { - defer func() { - rollbackErr := tx.Rollback(ctx) - if rollbackErr != nil && !errors.Is(rollbackErr, ErrTxClosed) { - err = rollbackErr - } - }() - - fErr := fn(tx) - if fErr != nil { - _ = tx.Rollback(ctx) // ignore rollback error as there is already an error to return - return fErr - } - - return tx.Commit(ctx) -} diff --git a/vendor/github.com/jackc/pgx/v5/values.go b/vendor/github.com/jackc/pgx/v5/values.go deleted file mode 100644 index 6e2ff3003..000000000 --- a/vendor/github.com/jackc/pgx/v5/values.go +++ /dev/null @@ -1,63 +0,0 @@ -package pgx - -import ( - "errors" - - "github.com/jackc/pgx/v5/internal/pgio" - "github.com/jackc/pgx/v5/pgtype" -) - -// PostgreSQL format codes -const ( - TextFormatCode = 0 - BinaryFormatCode = 1 -) - -func convertSimpleArgument(m *pgtype.Map, arg any) (any, error) { - buf, err := m.Encode(0, TextFormatCode, arg, []byte{}) - if err != nil { - return nil, err - } - if buf == nil { - return nil, nil - } - return string(buf), nil -} - -func encodeCopyValue(m *pgtype.Map, buf []byte, oid uint32, arg any) ([]byte, error) { - sp := len(buf) - buf = pgio.AppendInt32(buf, -1) - argBuf, err := m.Encode(oid, BinaryFormatCode, arg, buf) - if err != nil { - if argBuf2, err2 := tryScanStringCopyValueThenEncode(m, buf, oid, arg); err2 == nil { - argBuf = argBuf2 - } else { - return nil, err - } - } - - if argBuf != nil { - buf = argBuf - pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) - } - return buf, nil -} - -func tryScanStringCopyValueThenEncode(m *pgtype.Map, buf []byte, oid uint32, arg any) ([]byte, error) { - s, ok := arg.(string) - if !ok { - textBuf, err := m.Encode(oid, TextFormatCode, arg, nil) - if err != nil { - return nil, errors.New("not a string and cannot be encoded as text") - } - s = string(textBuf) - } - - var v any - err := m.Scan(oid, TextFormatCode, []byte(s), &v) - if err != nil { - return nil, err - } - - return m.Encode(oid, BinaryFormatCode, v, buf) -} diff --git a/vendor/github.com/jackc/puddle/v2/CHANGELOG.md b/vendor/github.com/jackc/puddle/v2/CHANGELOG.md deleted file mode 100644 index d0d202c74..000000000 --- a/vendor/github.com/jackc/puddle/v2/CHANGELOG.md +++ /dev/null @@ -1,79 +0,0 @@ -# 2.2.2 (September 10, 2024) - -* Add empty acquire time to stats (Maxim Ivanov) -* Stop importing nanotime from runtime via linkname (maypok86) - -# 2.2.1 (July 15, 2023) - -* Fix: CreateResource cannot overflow pool. This changes documented behavior of CreateResource. Previously, - CreateResource could create a resource even if the pool was full. This could cause the pool to overflow. While this - was documented, it was documenting incorrect behavior. CreateResource now returns an error if the pool is full. - -# 2.2.0 (February 11, 2023) - -* Use Go 1.19 atomics and drop go.uber.org/atomic dependency - -# 2.1.2 (November 12, 2022) - -* Restore support to Go 1.18 via go.uber.org/atomic - -# 2.1.1 (November 11, 2022) - -* Fix create resource concurrently with Stat call race - -# 2.1.0 (October 28, 2022) - -* Concurrency control is now implemented with a semaphore. This simplifies some internal logic, resolves a few error conditions (including a deadlock), and improves performance. (Jan Dubsky) -* Go 1.19 is now required for the improved atomic support. - -# 2.0.1 (October 28, 2022) - -* Fix race condition when Close is called concurrently with multiple constructors - -# 2.0.0 (September 17, 2022) - -* Use generics instead of interface{} (Столяров Владимир Алексеевич) -* Add Reset -* Do not cancel resource construction when Acquire is canceled -* NewPool takes Config - -# 1.3.0 (August 27, 2022) - -* Acquire creates resources in background to allow creation to continue after Acquire is canceled (James Hartig) - -# 1.2.1 (December 2, 2021) - -* TryAcquire now does not block when background constructing resource - -# 1.2.0 (November 20, 2021) - -* Add TryAcquire (A. Jensen) -* Fix: remove memory leak / unintentionally pinned memory when shrinking slices (Alexander Staubo) -* Fix: Do not leave pool locked after panic from nil context - -# 1.1.4 (September 11, 2021) - -* Fix: Deadlock in CreateResource if pool was closed during resource acquisition (Dmitriy Matrenichev) - -# 1.1.3 (December 3, 2020) - -* Fix: Failed resource creation could cause concurrent Acquire to hang. (Evgeny Vanslov) - -# 1.1.2 (September 26, 2020) - -* Fix: Resource.Destroy no longer removes itself from the pool before its destructor has completed. -* Fix: Prevent crash when pool is closed while resource is being created. - -# 1.1.1 (April 2, 2020) - -* Pool.Close can be safely called multiple times -* AcquireAllIDle immediately returns nil if pool is closed -* CreateResource checks if pool is closed before taking any action -* Fix potential race condition when CreateResource and Close are called concurrently. CreateResource now checks if pool is closed before adding newly created resource to pool. - -# 1.1.0 (February 5, 2020) - -* Use runtime.nanotime for faster tracking of acquire time and last usage time. -* Track resource idle time to enable client health check logic. (Patrick Ellul) -* Add CreateResource to construct a new resource without acquiring it. (Patrick Ellul) -* Fix deadlock race when acquire is cancelled. (Michael Tharp) diff --git a/vendor/github.com/jackc/puddle/v2/LICENSE b/vendor/github.com/jackc/puddle/v2/LICENSE deleted file mode 100644 index bcc286c54..000000000 --- a/vendor/github.com/jackc/puddle/v2/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2018 Jack Christensen - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/puddle/v2/README.md b/vendor/github.com/jackc/puddle/v2/README.md deleted file mode 100644 index fa82a9d46..000000000 --- a/vendor/github.com/jackc/puddle/v2/README.md +++ /dev/null @@ -1,80 +0,0 @@ -[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/puddle/v2.svg)](https://pkg.go.dev/github.com/jackc/puddle/v2) -![Build Status](https://github.com/jackc/puddle/actions/workflows/ci.yml/badge.svg) - -# Puddle - -Puddle is a tiny generic resource pool library for Go that uses the standard -context library to signal cancellation of acquires. It is designed to contain -the minimum functionality required for a resource pool. It can be used directly -or it can be used as the base for a domain specific resource pool. For example, -a database connection pool may use puddle internally and implement health checks -and keep-alive behavior without needing to implement any concurrent code of its -own. - -## Features - -* Acquire cancellation via context standard library -* Statistics API for monitoring pool pressure -* No dependencies outside of standard library and golang.org/x/sync -* High performance -* 100% test coverage of reachable code - -## Example Usage - -```go -package main - -import ( - "context" - "log" - "net" - - "github.com/jackc/puddle/v2" -) - -func main() { - constructor := func(context.Context) (net.Conn, error) { - return net.Dial("tcp", "127.0.0.1:8080") - } - destructor := func(value net.Conn) { - value.Close() - } - maxPoolSize := int32(10) - - pool, err := puddle.NewPool(&puddle.Config[net.Conn]{Constructor: constructor, Destructor: destructor, MaxSize: maxPoolSize}) - if err != nil { - log.Fatal(err) - } - - // Acquire resource from the pool. - res, err := pool.Acquire(context.Background()) - if err != nil { - log.Fatal(err) - } - - // Use resource. - _, err = res.Value().Write([]byte{1}) - if err != nil { - log.Fatal(err) - } - - // Release when done. - res.Release() -} -``` - -## Status - -Puddle is stable and feature complete. - -* Bug reports and fixes are welcome. -* New features will usually not be accepted if they can be feasibly implemented in a wrapper. -* Performance optimizations will usually not be accepted unless the performance issue rises to the level of a bug. - -## Supported Go Versions - -puddle supports the same versions of Go that are supported by the Go project. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases. This means puddle supports Go 1.19 and higher. - -## License - -MIT diff --git a/vendor/github.com/jackc/puddle/v2/context.go b/vendor/github.com/jackc/puddle/v2/context.go deleted file mode 100644 index e19d2a609..000000000 --- a/vendor/github.com/jackc/puddle/v2/context.go +++ /dev/null @@ -1,24 +0,0 @@ -package puddle - -import ( - "context" - "time" -) - -// valueCancelCtx combines two contexts into one. One context is used for values and the other is used for cancellation. -type valueCancelCtx struct { - valueCtx context.Context - cancelCtx context.Context -} - -func (ctx *valueCancelCtx) Deadline() (time.Time, bool) { return ctx.cancelCtx.Deadline() } -func (ctx *valueCancelCtx) Done() <-chan struct{} { return ctx.cancelCtx.Done() } -func (ctx *valueCancelCtx) Err() error { return ctx.cancelCtx.Err() } -func (ctx *valueCancelCtx) Value(key any) any { return ctx.valueCtx.Value(key) } - -func newValueCancelCtx(valueCtx, cancelContext context.Context) context.Context { - return &valueCancelCtx{ - valueCtx: valueCtx, - cancelCtx: cancelContext, - } -} diff --git a/vendor/github.com/jackc/puddle/v2/doc.go b/vendor/github.com/jackc/puddle/v2/doc.go deleted file mode 100644 index 818e4a698..000000000 --- a/vendor/github.com/jackc/puddle/v2/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package puddle is a generic resource pool with type-parametrized api. -/* - -Puddle is a tiny generic resource pool library for Go that uses the standard -context library to signal cancellation of acquires. It is designed to contain -the minimum functionality a resource pool needs that cannot be implemented -without concurrency concerns. For example, a database connection pool may use -puddle internally and implement health checks and keep-alive behavior without -needing to implement any concurrent code of its own. -*/ -package puddle diff --git a/vendor/github.com/jackc/puddle/v2/internal/genstack/gen_stack.go b/vendor/github.com/jackc/puddle/v2/internal/genstack/gen_stack.go deleted file mode 100644 index 7e4660c8c..000000000 --- a/vendor/github.com/jackc/puddle/v2/internal/genstack/gen_stack.go +++ /dev/null @@ -1,85 +0,0 @@ -package genstack - -// GenStack implements a generational stack. -// -// GenStack works as common stack except for the fact that all elements in the -// older generation are guaranteed to be popped before any element in the newer -// generation. New elements are always pushed to the current (newest) -// generation. -// -// We could also say that GenStack behaves as a stack in case of a single -// generation, but it behaves as a queue of individual generation stacks. -type GenStack[T any] struct { - // We can represent arbitrary number of generations using 2 stacks. The - // new stack stores all new pushes and the old stack serves all reads. - // Old stack can represent multiple generations. If old == new, then all - // elements pushed in previous (not current) generations have already - // been popped. - - old *stack[T] - new *stack[T] -} - -// NewGenStack creates a new empty GenStack. -func NewGenStack[T any]() *GenStack[T] { - s := &stack[T]{} - return &GenStack[T]{ - old: s, - new: s, - } -} - -func (s *GenStack[T]) Pop() (T, bool) { - // Pushes always append to the new stack, so if the old once becomes - // empty, it will remail empty forever. - if s.old.len() == 0 && s.old != s.new { - s.old = s.new - } - - if s.old.len() == 0 { - var zero T - return zero, false - } - - return s.old.pop(), true -} - -// Push pushes a new element at the top of the stack. -func (s *GenStack[T]) Push(v T) { s.new.push(v) } - -// NextGen starts a new stack generation. -func (s *GenStack[T]) NextGen() { - if s.old == s.new { - s.new = &stack[T]{} - return - } - - // We need to pop from the old stack to the top of the new stack. Let's - // have an example: - // - // Old: 4 3 2 1 - // New: 8 7 6 5 - // PopOrder: 1 2 3 4 5 6 7 8 - // - // - // To preserve pop order, we have to take all elements from the old - // stack and push them to the top of new stack: - // - // New: 8 7 6 5 4 3 2 1 - // - s.new.push(s.old.takeAll()...) - - // We have the old stack allocated and empty, so why not to reuse it as - // new new stack. - s.old, s.new = s.new, s.old -} - -// Len returns number of elements in the stack. -func (s *GenStack[T]) Len() int { - l := s.old.len() - if s.old != s.new { - l += s.new.len() - } - - return l -} diff --git a/vendor/github.com/jackc/puddle/v2/internal/genstack/stack.go b/vendor/github.com/jackc/puddle/v2/internal/genstack/stack.go deleted file mode 100644 index dbced0c72..000000000 --- a/vendor/github.com/jackc/puddle/v2/internal/genstack/stack.go +++ /dev/null @@ -1,39 +0,0 @@ -package genstack - -// stack is a wrapper around an array implementing a stack. -// -// We cannot use slice to represent the stack because append might change the -// pointer value of the slice. That would be an issue in GenStack -// implementation. -type stack[T any] struct { - arr []T -} - -// push pushes a new element at the top of a stack. -func (s *stack[T]) push(vs ...T) { s.arr = append(s.arr, vs...) } - -// pop pops the stack top-most element. -// -// If stack length is zero, this method panics. -func (s *stack[T]) pop() T { - idx := s.len() - 1 - val := s.arr[idx] - - // Avoid memory leak - var zero T - s.arr[idx] = zero - - s.arr = s.arr[:idx] - return val -} - -// takeAll returns all elements in the stack in order as they are stored - i.e. -// the top-most stack element is the last one. -func (s *stack[T]) takeAll() []T { - arr := s.arr - s.arr = nil - return arr -} - -// len returns number of elements in the stack. -func (s *stack[T]) len() int { return len(s.arr) } diff --git a/vendor/github.com/jackc/puddle/v2/log.go b/vendor/github.com/jackc/puddle/v2/log.go deleted file mode 100644 index b21b94630..000000000 --- a/vendor/github.com/jackc/puddle/v2/log.go +++ /dev/null @@ -1,32 +0,0 @@ -package puddle - -import "unsafe" - -type ints interface { - int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 -} - -// log2Int returns log2 of an integer. This function panics if val < 0. For val -// == 0, returns 0. -func log2Int[T ints](val T) uint8 { - if val <= 0 { - panic("log2 of non-positive number does not exist") - } - - return log2IntRange(val, 0, uint8(8*unsafe.Sizeof(val))) -} - -func log2IntRange[T ints](val T, begin, end uint8) uint8 { - length := end - begin - if length == 1 { - return begin - } - - delim := begin + length/2 - mask := T(1) << delim - if mask > val { - return log2IntRange(val, begin, delim) - } else { - return log2IntRange(val, delim, end) - } -} diff --git a/vendor/github.com/jackc/puddle/v2/nanotime.go b/vendor/github.com/jackc/puddle/v2/nanotime.go deleted file mode 100644 index 8a5351a0d..000000000 --- a/vendor/github.com/jackc/puddle/v2/nanotime.go +++ /dev/null @@ -1,16 +0,0 @@ -package puddle - -import "time" - -// nanotime returns the time in nanoseconds since process start. -// -// This approach, described at -// https://github.com/golang/go/issues/61765#issuecomment-1672090302, -// is fast, monotonic, and portable, and avoids the previous -// dependence on runtime.nanotime using the (unsafe) linkname hack. -// In particular, time.Since does less work than time.Now. -func nanotime() int64 { - return time.Since(globalStart).Nanoseconds() -} - -var globalStart = time.Now() diff --git a/vendor/github.com/jackc/puddle/v2/pool.go b/vendor/github.com/jackc/puddle/v2/pool.go deleted file mode 100644 index c411d2f6e..000000000 --- a/vendor/github.com/jackc/puddle/v2/pool.go +++ /dev/null @@ -1,710 +0,0 @@ -package puddle - -import ( - "context" - "errors" - "sync" - "sync/atomic" - "time" - - "github.com/jackc/puddle/v2/internal/genstack" - "golang.org/x/sync/semaphore" -) - -const ( - resourceStatusConstructing = 0 - resourceStatusIdle = iota - resourceStatusAcquired = iota - resourceStatusHijacked = iota -) - -// ErrClosedPool occurs on an attempt to acquire a connection from a closed pool -// or a pool that is closed while the acquire is waiting. -var ErrClosedPool = errors.New("closed pool") - -// ErrNotAvailable occurs on an attempt to acquire a resource from a pool -// that is at maximum capacity and has no available resources. -var ErrNotAvailable = errors.New("resource not available") - -// Constructor is a function called by the pool to construct a resource. -type Constructor[T any] func(ctx context.Context) (res T, err error) - -// Destructor is a function called by the pool to destroy a resource. -type Destructor[T any] func(res T) - -// Resource is the resource handle returned by acquiring from the pool. -type Resource[T any] struct { - value T - pool *Pool[T] - creationTime time.Time - lastUsedNano int64 - poolResetCount int - status byte -} - -// Value returns the resource value. -func (res *Resource[T]) Value() T { - if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) { - panic("tried to access resource that is not acquired or hijacked") - } - return res.value -} - -// Release returns the resource to the pool. res must not be subsequently used. -func (res *Resource[T]) Release() { - if res.status != resourceStatusAcquired { - panic("tried to release resource that is not acquired") - } - res.pool.releaseAcquiredResource(res, nanotime()) -} - -// ReleaseUnused returns the resource to the pool without updating when it was last used used. i.e. LastUsedNanotime -// will not change. res must not be subsequently used. -func (res *Resource[T]) ReleaseUnused() { - if res.status != resourceStatusAcquired { - panic("tried to release resource that is not acquired") - } - res.pool.releaseAcquiredResource(res, res.lastUsedNano) -} - -// Destroy returns the resource to the pool for destruction. res must not be -// subsequently used. -func (res *Resource[T]) Destroy() { - if res.status != resourceStatusAcquired { - panic("tried to destroy resource that is not acquired") - } - go res.pool.destroyAcquiredResource(res) -} - -// Hijack assumes ownership of the resource from the pool. Caller is responsible -// for cleanup of resource value. -func (res *Resource[T]) Hijack() { - if res.status != resourceStatusAcquired { - panic("tried to hijack resource that is not acquired") - } - res.pool.hijackAcquiredResource(res) -} - -// CreationTime returns when the resource was created by the pool. -func (res *Resource[T]) CreationTime() time.Time { - if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) { - panic("tried to access resource that is not acquired or hijacked") - } - return res.creationTime -} - -// LastUsedNanotime returns when Release was last called on the resource measured in nanoseconds from an arbitrary time -// (a monotonic time). Returns creation time if Release has never been called. This is only useful to compare with -// other calls to LastUsedNanotime. In almost all cases, IdleDuration should be used instead. -func (res *Resource[T]) LastUsedNanotime() int64 { - if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) { - panic("tried to access resource that is not acquired or hijacked") - } - - return res.lastUsedNano -} - -// IdleDuration returns the duration since Release was last called on the resource. This is equivalent to subtracting -// LastUsedNanotime to the current nanotime. -func (res *Resource[T]) IdleDuration() time.Duration { - if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) { - panic("tried to access resource that is not acquired or hijacked") - } - - return time.Duration(nanotime() - res.lastUsedNano) -} - -// Pool is a concurrency-safe resource pool. -type Pool[T any] struct { - // mux is the pool internal lock. Any modification of shared state of - // the pool (but Acquires of acquireSem) must be performed only by - // holder of the lock. Long running operations are not allowed when mux - // is held. - mux sync.Mutex - // acquireSem provides an allowance to acquire a resource. - // - // Releases are allowed only when caller holds mux. Acquires have to - // happen before mux is locked (doesn't apply to semaphore.TryAcquire in - // AcquireAllIdle). - acquireSem *semaphore.Weighted - destructWG sync.WaitGroup - - allResources resList[T] - idleResources *genstack.GenStack[*Resource[T]] - - constructor Constructor[T] - destructor Destructor[T] - maxSize int32 - - acquireCount int64 - acquireDuration time.Duration - emptyAcquireCount int64 - emptyAcquireWaitTime time.Duration - canceledAcquireCount atomic.Int64 - - resetCount int - - baseAcquireCtx context.Context - cancelBaseAcquireCtx context.CancelFunc - closed bool -} - -type Config[T any] struct { - Constructor Constructor[T] - Destructor Destructor[T] - MaxSize int32 -} - -// NewPool creates a new pool. Returns an error iff MaxSize is less than 1. -func NewPool[T any](config *Config[T]) (*Pool[T], error) { - if config.MaxSize < 1 { - return nil, errors.New("MaxSize must be >= 1") - } - - baseAcquireCtx, cancelBaseAcquireCtx := context.WithCancel(context.Background()) - - return &Pool[T]{ - acquireSem: semaphore.NewWeighted(int64(config.MaxSize)), - idleResources: genstack.NewGenStack[*Resource[T]](), - maxSize: config.MaxSize, - constructor: config.Constructor, - destructor: config.Destructor, - baseAcquireCtx: baseAcquireCtx, - cancelBaseAcquireCtx: cancelBaseAcquireCtx, - }, nil -} - -// Close destroys all resources in the pool and rejects future Acquire calls. -// Blocks until all resources are returned to pool and destroyed. -func (p *Pool[T]) Close() { - defer p.destructWG.Wait() - - p.mux.Lock() - defer p.mux.Unlock() - - if p.closed { - return - } - p.closed = true - p.cancelBaseAcquireCtx() - - for res, ok := p.idleResources.Pop(); ok; res, ok = p.idleResources.Pop() { - p.allResources.remove(res) - go p.destructResourceValue(res.value) - } -} - -// Stat is a snapshot of Pool statistics. -type Stat struct { - constructingResources int32 - acquiredResources int32 - idleResources int32 - maxResources int32 - acquireCount int64 - acquireDuration time.Duration - emptyAcquireCount int64 - emptyAcquireWaitTime time.Duration - canceledAcquireCount int64 -} - -// TotalResources returns the total number of resources currently in the pool. -// The value is the sum of ConstructingResources, AcquiredResources, and -// IdleResources. -func (s *Stat) TotalResources() int32 { - return s.constructingResources + s.acquiredResources + s.idleResources -} - -// ConstructingResources returns the number of resources with construction in progress in -// the pool. -func (s *Stat) ConstructingResources() int32 { - return s.constructingResources -} - -// AcquiredResources returns the number of currently acquired resources in the pool. -func (s *Stat) AcquiredResources() int32 { - return s.acquiredResources -} - -// IdleResources returns the number of currently idle resources in the pool. -func (s *Stat) IdleResources() int32 { - return s.idleResources -} - -// MaxResources returns the maximum size of the pool. -func (s *Stat) MaxResources() int32 { - return s.maxResources -} - -// AcquireCount returns the cumulative count of successful acquires from the pool. -func (s *Stat) AcquireCount() int64 { - return s.acquireCount -} - -// AcquireDuration returns the total duration of all successful acquires from -// the pool. -func (s *Stat) AcquireDuration() time.Duration { - return s.acquireDuration -} - -// EmptyAcquireCount returns the cumulative count of successful acquires from the pool -// that waited for a resource to be released or constructed because the pool was -// empty. -func (s *Stat) EmptyAcquireCount() int64 { - return s.emptyAcquireCount -} - -// EmptyAcquireWaitTime returns the cumulative time waited for successful acquires -// from the pool for a resource to be released or constructed because the pool was -// empty. -func (s *Stat) EmptyAcquireWaitTime() time.Duration { - return s.emptyAcquireWaitTime -} - -// CanceledAcquireCount returns the cumulative count of acquires from the pool -// that were canceled by a context. -func (s *Stat) CanceledAcquireCount() int64 { - return s.canceledAcquireCount -} - -// Stat returns the current pool statistics. -func (p *Pool[T]) Stat() *Stat { - p.mux.Lock() - defer p.mux.Unlock() - - s := &Stat{ - maxResources: p.maxSize, - acquireCount: p.acquireCount, - emptyAcquireCount: p.emptyAcquireCount, - emptyAcquireWaitTime: p.emptyAcquireWaitTime, - canceledAcquireCount: p.canceledAcquireCount.Load(), - acquireDuration: p.acquireDuration, - } - - for _, res := range p.allResources { - switch res.status { - case resourceStatusConstructing: - s.constructingResources += 1 - case resourceStatusIdle: - s.idleResources += 1 - case resourceStatusAcquired: - s.acquiredResources += 1 - } - } - - return s -} - -// tryAcquireIdleResource checks if there is any idle resource. If there is -// some, this method removes it from idle list and returns it. If the idle pool -// is empty, this method returns nil and doesn't modify the idleResources slice. -// -// WARNING: Caller of this method must hold the pool mutex! -func (p *Pool[T]) tryAcquireIdleResource() *Resource[T] { - res, ok := p.idleResources.Pop() - if !ok { - return nil - } - - res.status = resourceStatusAcquired - return res -} - -// createNewResource creates a new resource and inserts it into list of pool -// resources. -// -// WARNING: Caller of this method must hold the pool mutex! -func (p *Pool[T]) createNewResource() *Resource[T] { - res := &Resource[T]{ - pool: p, - creationTime: time.Now(), - lastUsedNano: nanotime(), - poolResetCount: p.resetCount, - status: resourceStatusConstructing, - } - - p.allResources.append(res) - p.destructWG.Add(1) - - return res -} - -// Acquire gets a resource from the pool. If no resources are available and the pool is not at maximum capacity it will -// create a new resource. If the pool is at maximum capacity it will block until a resource is available. ctx can be -// used to cancel the Acquire. -// -// If Acquire creates a new resource the resource constructor function will receive a context that delegates Value() to -// ctx. Canceling ctx will cause Acquire to return immediately but it will not cancel the resource creation. This avoids -// the problem of it being impossible to create resources when the time to create a resource is greater than any one -// caller of Acquire is willing to wait. -func (p *Pool[T]) Acquire(ctx context.Context) (_ *Resource[T], err error) { - select { - case <-ctx.Done(): - p.canceledAcquireCount.Add(1) - return nil, ctx.Err() - default: - } - - return p.acquire(ctx) -} - -// acquire is a continuation of Acquire function that doesn't check context -// validity. -// -// This function exists solely only for benchmarking purposes. -func (p *Pool[T]) acquire(ctx context.Context) (*Resource[T], error) { - startNano := nanotime() - - var waitedForLock bool - if !p.acquireSem.TryAcquire(1) { - waitedForLock = true - err := p.acquireSem.Acquire(ctx, 1) - if err != nil { - p.canceledAcquireCount.Add(1) - return nil, err - } - } - - p.mux.Lock() - if p.closed { - p.acquireSem.Release(1) - p.mux.Unlock() - return nil, ErrClosedPool - } - - // If a resource is available in the pool. - if res := p.tryAcquireIdleResource(); res != nil { - waitTime := time.Duration(nanotime() - startNano) - if waitedForLock { - p.emptyAcquireCount += 1 - p.emptyAcquireWaitTime += waitTime - } - p.acquireCount += 1 - p.acquireDuration += waitTime - p.mux.Unlock() - return res, nil - } - - if len(p.allResources) >= int(p.maxSize) { - // Unreachable code. - panic("bug: semaphore allowed more acquires than pool allows") - } - - // The resource is not idle, but there is enough space to create one. - res := p.createNewResource() - p.mux.Unlock() - - res, err := p.initResourceValue(ctx, res) - if err != nil { - return nil, err - } - - p.mux.Lock() - defer p.mux.Unlock() - - p.emptyAcquireCount += 1 - p.acquireCount += 1 - waitTime := time.Duration(nanotime() - startNano) - p.acquireDuration += waitTime - p.emptyAcquireWaitTime += waitTime - - return res, nil -} - -func (p *Pool[T]) initResourceValue(ctx context.Context, res *Resource[T]) (*Resource[T], error) { - // Create the resource in a goroutine to immediately return from Acquire - // if ctx is canceled without also canceling the constructor. - // - // See: - // - https://github.com/jackc/pgx/issues/1287 - // - https://github.com/jackc/pgx/issues/1259 - constructErrChan := make(chan error) - go func() { - constructorCtx := newValueCancelCtx(ctx, p.baseAcquireCtx) - value, err := p.constructor(constructorCtx) - if err != nil { - p.mux.Lock() - p.allResources.remove(res) - p.destructWG.Done() - - // The resource won't be acquired because its - // construction failed. We have to allow someone else to - // take that resouce. - p.acquireSem.Release(1) - p.mux.Unlock() - - select { - case constructErrChan <- err: - case <-ctx.Done(): - // The caller is cancelled, so no-one awaits the - // error. This branch avoid goroutine leak. - } - return - } - - // The resource is already in p.allResources where it might be read. So we need to acquire the lock to update its - // status. - p.mux.Lock() - res.value = value - res.status = resourceStatusAcquired - p.mux.Unlock() - - // This select works because the channel is unbuffered. - select { - case constructErrChan <- nil: - case <-ctx.Done(): - p.releaseAcquiredResource(res, res.lastUsedNano) - } - }() - - select { - case <-ctx.Done(): - p.canceledAcquireCount.Add(1) - return nil, ctx.Err() - case err := <-constructErrChan: - if err != nil { - return nil, err - } - return res, nil - } -} - -// TryAcquire gets a resource from the pool if one is immediately available. If not, it returns ErrNotAvailable. If no -// resources are available but the pool has room to grow, a resource will be created in the background. ctx is only -// used to cancel the background creation. -func (p *Pool[T]) TryAcquire(ctx context.Context) (*Resource[T], error) { - if !p.acquireSem.TryAcquire(1) { - return nil, ErrNotAvailable - } - - p.mux.Lock() - defer p.mux.Unlock() - - if p.closed { - p.acquireSem.Release(1) - return nil, ErrClosedPool - } - - // If a resource is available now - if res := p.tryAcquireIdleResource(); res != nil { - p.acquireCount += 1 - return res, nil - } - - if len(p.allResources) >= int(p.maxSize) { - // Unreachable code. - panic("bug: semaphore allowed more acquires than pool allows") - } - - res := p.createNewResource() - go func() { - value, err := p.constructor(ctx) - - p.mux.Lock() - defer p.mux.Unlock() - // We have to create the resource and only then release the - // semaphore - For the time being there is no resource that - // someone could acquire. - defer p.acquireSem.Release(1) - - if err != nil { - p.allResources.remove(res) - p.destructWG.Done() - return - } - - res.value = value - res.status = resourceStatusIdle - p.idleResources.Push(res) - }() - - return nil, ErrNotAvailable -} - -// acquireSemAll tries to acquire num free tokens from sem. This function is -// guaranteed to acquire at least the lowest number of tokens that has been -// available in the semaphore during runtime of this function. -// -// For the time being, semaphore doesn't allow to acquire all tokens atomically -// (see https://github.com/golang/sync/pull/19). We simulate this by trying all -// powers of 2 that are less or equal to num. -// -// For example, let's immagine we have 19 free tokens in the semaphore which in -// total has 24 tokens (i.e. the maxSize of the pool is 24 resources). Then if -// num is 24, the log2Uint(24) is 4 and we try to acquire 16, 8, 4, 2 and 1 -// tokens. Out of those, the acquire of 16, 2 and 1 tokens will succeed. -// -// Naturally, Acquires and Releases of the semaphore might take place -// concurrently. For this reason, it's not guaranteed that absolutely all free -// tokens in the semaphore will be acquired. But it's guaranteed that at least -// the minimal number of tokens that has been present over the whole process -// will be acquired. This is sufficient for the use-case we have in this -// package. -// -// TODO: Replace this with acquireSem.TryAcquireAll() if it gets to -// upstream. https://github.com/golang/sync/pull/19 -func acquireSemAll(sem *semaphore.Weighted, num int) int { - if sem.TryAcquire(int64(num)) { - return num - } - - var acquired int - for i := int(log2Int(num)); i >= 0; i-- { - val := 1 << i - if sem.TryAcquire(int64(val)) { - acquired += val - } - } - - return acquired -} - -// AcquireAllIdle acquires all currently idle resources. Its intended use is for -// health check and keep-alive functionality. It does not update pool -// statistics. -func (p *Pool[T]) AcquireAllIdle() []*Resource[T] { - p.mux.Lock() - defer p.mux.Unlock() - - if p.closed { - return nil - } - - numIdle := p.idleResources.Len() - if numIdle == 0 { - return nil - } - - // In acquireSemAll we use only TryAcquire and not Acquire. Because - // TryAcquire cannot block, the fact that we hold mutex locked and try - // to acquire semaphore cannot result in dead-lock. - // - // Because the mutex is locked, no parallel Release can run. This - // implies that the number of tokens can only decrease because some - // Acquire/TryAcquire call can consume the semaphore token. Consequently - // acquired is always less or equal to numIdle. Moreover if acquired < - // numIdle, then there are some parallel Acquire/TryAcquire calls that - // will take the remaining idle connections. - acquired := acquireSemAll(p.acquireSem, numIdle) - - idle := make([]*Resource[T], acquired) - for i := range idle { - res, _ := p.idleResources.Pop() - res.status = resourceStatusAcquired - idle[i] = res - } - - // We have to bump the generation to ensure that Acquire/TryAcquire - // calls running in parallel (those which caused acquired < numIdle) - // will consume old connections and not freshly released connections - // instead. - p.idleResources.NextGen() - - return idle -} - -// CreateResource constructs a new resource without acquiring it. It goes straight in the IdlePool. If the pool is full -// it returns an error. It can be useful to maintain warm resources under little load. -func (p *Pool[T]) CreateResource(ctx context.Context) error { - if !p.acquireSem.TryAcquire(1) { - return ErrNotAvailable - } - - p.mux.Lock() - if p.closed { - p.acquireSem.Release(1) - p.mux.Unlock() - return ErrClosedPool - } - - if len(p.allResources) >= int(p.maxSize) { - p.acquireSem.Release(1) - p.mux.Unlock() - return ErrNotAvailable - } - - res := p.createNewResource() - p.mux.Unlock() - - value, err := p.constructor(ctx) - p.mux.Lock() - defer p.mux.Unlock() - defer p.acquireSem.Release(1) - if err != nil { - p.allResources.remove(res) - p.destructWG.Done() - return err - } - - res.value = value - res.status = resourceStatusIdle - - // If closed while constructing resource then destroy it and return an error - if p.closed { - go p.destructResourceValue(res.value) - return ErrClosedPool - } - - p.idleResources.Push(res) - - return nil -} - -// Reset destroys all resources, but leaves the pool open. It is intended for use when an error is detected that would -// disrupt all resources (such as a network interruption or a server state change). -// -// It is safe to reset a pool while resources are checked out. Those resources will be destroyed when they are returned -// to the pool. -func (p *Pool[T]) Reset() { - p.mux.Lock() - defer p.mux.Unlock() - - p.resetCount++ - - for res, ok := p.idleResources.Pop(); ok; res, ok = p.idleResources.Pop() { - p.allResources.remove(res) - go p.destructResourceValue(res.value) - } -} - -// releaseAcquiredResource returns res to the the pool. -func (p *Pool[T]) releaseAcquiredResource(res *Resource[T], lastUsedNano int64) { - p.mux.Lock() - defer p.mux.Unlock() - defer p.acquireSem.Release(1) - - if p.closed || res.poolResetCount != p.resetCount { - p.allResources.remove(res) - go p.destructResourceValue(res.value) - } else { - res.lastUsedNano = lastUsedNano - res.status = resourceStatusIdle - p.idleResources.Push(res) - } -} - -// Remove removes res from the pool and closes it. If res is not part of the -// pool Remove will panic. -func (p *Pool[T]) destroyAcquiredResource(res *Resource[T]) { - p.destructResourceValue(res.value) - - p.mux.Lock() - defer p.mux.Unlock() - defer p.acquireSem.Release(1) - - p.allResources.remove(res) -} - -func (p *Pool[T]) hijackAcquiredResource(res *Resource[T]) { - p.mux.Lock() - defer p.mux.Unlock() - defer p.acquireSem.Release(1) - - p.allResources.remove(res) - res.status = resourceStatusHijacked - p.destructWG.Done() // not responsible for destructing hijacked resources -} - -func (p *Pool[T]) destructResourceValue(value T) { - p.destructor(value) - p.destructWG.Done() -} diff --git a/vendor/github.com/jackc/puddle/v2/resource_list.go b/vendor/github.com/jackc/puddle/v2/resource_list.go deleted file mode 100644 index b2430959b..000000000 --- a/vendor/github.com/jackc/puddle/v2/resource_list.go +++ /dev/null @@ -1,28 +0,0 @@ -package puddle - -type resList[T any] []*Resource[T] - -func (l *resList[T]) append(val *Resource[T]) { *l = append(*l, val) } - -func (l *resList[T]) popBack() *Resource[T] { - idx := len(*l) - 1 - val := (*l)[idx] - (*l)[idx] = nil // Avoid memory leak - *l = (*l)[:idx] - - return val -} - -func (l *resList[T]) remove(val *Resource[T]) { - for i, elem := range *l { - if elem == val { - lastIdx := len(*l) - 1 - (*l)[i] = (*l)[lastIdx] - (*l)[lastIdx] = nil // Avoid memory leak - (*l) = (*l)[:lastIdx] - return - } - } - - panic("BUG: removeResource could not find res in slice") -} diff --git a/vendor/github.com/jmespath/go-jmespath/.gitignore b/vendor/github.com/jmespath/go-jmespath/.gitignore deleted file mode 100644 index 5091fb073..000000000 --- a/vendor/github.com/jmespath/go-jmespath/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/jpgo -jmespath-fuzz.zip -cpu.out -go-jmespath.test diff --git a/vendor/github.com/jmespath/go-jmespath/.travis.yml b/vendor/github.com/jmespath/go-jmespath/.travis.yml deleted file mode 100644 index c56f37c0c..000000000 --- a/vendor/github.com/jmespath/go-jmespath/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: go - -sudo: false - -go: - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x - - 1.13.x - - 1.14.x - - 1.15.x - - tip - -allow_failures: - - go: tip - -script: make build - -matrix: - include: - - language: go - go: 1.15.x - script: make test diff --git a/vendor/github.com/jmespath/go-jmespath/LICENSE b/vendor/github.com/jmespath/go-jmespath/LICENSE deleted file mode 100644 index b03310a91..000000000 --- a/vendor/github.com/jmespath/go-jmespath/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2015 James Saryerwinnie - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT 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/vendor/github.com/jmespath/go-jmespath/Makefile b/vendor/github.com/jmespath/go-jmespath/Makefile deleted file mode 100644 index fb38ec276..000000000 --- a/vendor/github.com/jmespath/go-jmespath/Makefile +++ /dev/null @@ -1,51 +0,0 @@ - -CMD = jpgo - -SRC_PKGS=./ ./cmd/... ./fuzz/... - -help: - @echo "Please use \`make ' where is one of" - @echo " test to run all the tests" - @echo " build to build the library and jp executable" - @echo " generate to run codegen" - - -generate: - go generate ${SRC_PKGS} - -build: - rm -f $(CMD) - go build ${SRC_PKGS} - rm -f cmd/$(CMD)/$(CMD) && cd cmd/$(CMD)/ && go build ./... - mv cmd/$(CMD)/$(CMD) . - -test: test-internal-testify - echo "making tests ${SRC_PKGS}" - go test -v ${SRC_PKGS} - -check: - go vet ${SRC_PKGS} - @echo "golint ${SRC_PKGS}" - @lint=`golint ${SRC_PKGS}`; \ - lint=`echo "$$lint" | grep -v "astnodetype_string.go" | grep -v "toktype_string.go"`; \ - echo "$$lint"; \ - if [ "$$lint" != "" ]; then exit 1; fi - -htmlc: - go test -coverprofile="/tmp/jpcov" && go tool cover -html="/tmp/jpcov" && unlink /tmp/jpcov - -buildfuzz: - go-fuzz-build github.com/jmespath/go-jmespath/fuzz - -fuzz: buildfuzz - go-fuzz -bin=./jmespath-fuzz.zip -workdir=fuzz/testdata - -bench: - go test -bench . -cpuprofile cpu.out - -pprof-cpu: - go tool pprof ./go-jmespath.test ./cpu.out - -test-internal-testify: - cd internal/testify && go test ./... - diff --git a/vendor/github.com/jmespath/go-jmespath/README.md b/vendor/github.com/jmespath/go-jmespath/README.md deleted file mode 100644 index 110ad7999..000000000 --- a/vendor/github.com/jmespath/go-jmespath/README.md +++ /dev/null @@ -1,87 +0,0 @@ -# go-jmespath - A JMESPath implementation in Go - -[![Build Status](https://img.shields.io/travis/jmespath/go-jmespath.svg)](https://travis-ci.org/jmespath/go-jmespath) - - - -go-jmespath is a GO implementation of JMESPath, -which is a query language for JSON. It will take a JSON -document and transform it into another JSON document -through a JMESPath expression. - -Using go-jmespath is really easy. There's a single function -you use, `jmespath.search`: - - -```go -> import "github.com/jmespath/go-jmespath" -> -> var jsondata = []byte(`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.Search("foo.bar.baz[2]", data) -result = 2 -``` - -In the example we gave the ``search`` function input data of -`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}` as well as the JMESPath -expression `foo.bar.baz[2]`, and the `search` function evaluated -the expression against the input data to produce the result ``2``. - -The JMESPath language can do a lot more than select an element -from a list. Here are a few more examples: - -```go -> var jsondata = []byte(`{"foo": {"bar": {"baz": [0, 1, 2, 3, 4]}}}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search("foo.bar", data) -result = { "baz": [ 0, 1, 2, 3, 4 ] } - - -> var jsondata = []byte(`{"foo": [{"first": "a", "last": "b"}, - {"first": "c", "last": "d"}]}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search({"foo[*].first", data) -result [ 'a', 'c' ] - - -> var jsondata = []byte(`{"foo": [{"age": 20}, {"age": 25}, - {"age": 30}, {"age": 35}, - {"age": 40}]}`) // your data -> var data interface{} -> err := json.Unmarshal(jsondata, &data) -> result, err := jmespath.search("foo[?age > `30`]") -result = [ { age: 35 }, { age: 40 } ] -``` - -You can also pre-compile your query. This is usefull if -you are going to run multiple searches with it: - -```go - > var jsondata = []byte(`{"foo": "bar"}`) - > var data interface{} - > err := json.Unmarshal(jsondata, &data) - > precompiled, err := Compile("foo") - > if err != nil{ - > // ... handle the error - > } - > result, err := precompiled.Search(data) - result = "bar" -``` - -## More Resources - -The example above only show a small amount of what -a JMESPath expression can do. If you want to take a -tour of the language, the *best* place to go is the -[JMESPath Tutorial](http://jmespath.org/tutorial.html). - -One of the best things about JMESPath is that it is -implemented in many different programming languages including -python, ruby, php, lua, etc. To see a complete list of libraries, -check out the [JMESPath libraries page](http://jmespath.org/libraries.html). - -And finally, the full JMESPath specification can be found -on the [JMESPath site](http://jmespath.org/specification.html). diff --git a/vendor/github.com/jmespath/go-jmespath/api.go b/vendor/github.com/jmespath/go-jmespath/api.go deleted file mode 100644 index 010efe9bf..000000000 --- a/vendor/github.com/jmespath/go-jmespath/api.go +++ /dev/null @@ -1,49 +0,0 @@ -package jmespath - -import "strconv" - -// JMESPath is the representation of a compiled JMES path query. A JMESPath is -// safe for concurrent use by multiple goroutines. -type JMESPath struct { - ast ASTNode - intr *treeInterpreter -} - -// Compile parses a JMESPath expression and returns, if successful, a JMESPath -// object that can be used to match against data. -func Compile(expression string) (*JMESPath, error) { - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - jmespath := &JMESPath{ast: ast, intr: newInterpreter()} - return jmespath, nil -} - -// MustCompile is like Compile but panics if the expression cannot be parsed. -// It simplifies safe initialization of global variables holding compiled -// JMESPaths. -func MustCompile(expression string) *JMESPath { - jmespath, err := Compile(expression) - if err != nil { - panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error()) - } - return jmespath -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func (jp *JMESPath) Search(data interface{}) (interface{}, error) { - return jp.intr.Execute(jp.ast, data) -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func Search(expression string, data interface{}) (interface{}, error) { - intr := newInterpreter() - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - return intr.Execute(ast, data) -} diff --git a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go b/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go deleted file mode 100644 index 1cd2d239c..000000000 --- a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// generated by stringer -type astNodeType; DO NOT EDIT - -package jmespath - -import "fmt" - -const _astNodeType_name = "ASTEmptyASTComparatorASTCurrentNodeASTExpRefASTFunctionExpressionASTFieldASTFilterProjectionASTFlattenASTIdentityASTIndexASTIndexExpressionASTKeyValPairASTLiteralASTMultiSelectHashASTMultiSelectListASTOrExpressionASTAndExpressionASTNotExpressionASTPipeASTProjectionASTSubexpressionASTSliceASTValueProjection" - -var _astNodeType_index = [...]uint16{0, 8, 21, 35, 44, 65, 73, 92, 102, 113, 121, 139, 152, 162, 180, 198, 213, 229, 245, 252, 265, 281, 289, 307} - -func (i astNodeType) String() string { - if i < 0 || i >= astNodeType(len(_astNodeType_index)-1) { - return fmt.Sprintf("astNodeType(%d)", i) - } - return _astNodeType_name[_astNodeType_index[i]:_astNodeType_index[i+1]] -} diff --git a/vendor/github.com/jmespath/go-jmespath/functions.go b/vendor/github.com/jmespath/go-jmespath/functions.go deleted file mode 100644 index 9b7cd89b4..000000000 --- a/vendor/github.com/jmespath/go-jmespath/functions.go +++ /dev/null @@ -1,842 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "unicode/utf8" -) - -type jpFunction func(arguments []interface{}) (interface{}, error) - -type jpType string - -const ( - jpUnknown jpType = "unknown" - jpNumber jpType = "number" - jpString jpType = "string" - jpArray jpType = "array" - jpObject jpType = "object" - jpArrayNumber jpType = "array[number]" - jpArrayString jpType = "array[string]" - jpExpref jpType = "expref" - jpAny jpType = "any" -) - -type functionEntry struct { - name string - arguments []argSpec - handler jpFunction - hasExpRef bool -} - -type argSpec struct { - types []jpType - variadic bool -} - -type byExprString struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprString) Len() int { - return len(a.items) -} -func (a *byExprString) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprString) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(string) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(string) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type byExprFloat struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprFloat) Len() int { - return len(a.items) -} -func (a *byExprFloat) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprFloat) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(float64) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(float64) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type functionCaller struct { - functionTable map[string]functionEntry -} - -func newFunctionCaller() *functionCaller { - caller := &functionCaller{} - caller.functionTable = map[string]functionEntry{ - "length": { - name: "length", - arguments: []argSpec{ - {types: []jpType{jpString, jpArray, jpObject}}, - }, - handler: jpfLength, - }, - "starts_with": { - name: "starts_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfStartsWith, - }, - "abs": { - name: "abs", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfAbs, - }, - "avg": { - name: "avg", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfAvg, - }, - "ceil": { - name: "ceil", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfCeil, - }, - "contains": { - name: "contains", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - {types: []jpType{jpAny}}, - }, - handler: jpfContains, - }, - "ends_with": { - name: "ends_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfEndsWith, - }, - "floor": { - name: "floor", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfFloor, - }, - "map": { - name: "amp", - arguments: []argSpec{ - {types: []jpType{jpExpref}}, - {types: []jpType{jpArray}}, - }, - handler: jpfMap, - hasExpRef: true, - }, - "max": { - name: "max", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMax, - }, - "merge": { - name: "merge", - arguments: []argSpec{ - {types: []jpType{jpObject}, variadic: true}, - }, - handler: jpfMerge, - }, - "max_by": { - name: "max_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMaxBy, - hasExpRef: true, - }, - "sum": { - name: "sum", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfSum, - }, - "min": { - name: "min", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMin, - }, - "min_by": { - name: "min_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMinBy, - hasExpRef: true, - }, - "type": { - name: "type", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfType, - }, - "keys": { - name: "keys", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfKeys, - }, - "values": { - name: "values", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfValues, - }, - "sort": { - name: "sort", - arguments: []argSpec{ - {types: []jpType{jpArrayString, jpArrayNumber}}, - }, - handler: jpfSort, - }, - "sort_by": { - name: "sort_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfSortBy, - hasExpRef: true, - }, - "join": { - name: "join", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpArrayString}}, - }, - handler: jpfJoin, - }, - "reverse": { - name: "reverse", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - }, - handler: jpfReverse, - }, - "to_array": { - name: "to_array", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToArray, - }, - "to_string": { - name: "to_string", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToString, - }, - "to_number": { - name: "to_number", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToNumber, - }, - "not_null": { - name: "not_null", - arguments: []argSpec{ - {types: []jpType{jpAny}, variadic: true}, - }, - handler: jpfNotNull, - }, - } - return caller -} - -func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) { - if len(e.arguments) == 0 { - return arguments, nil - } - if !e.arguments[len(e.arguments)-1].variadic { - if len(e.arguments) != len(arguments) { - return nil, errors.New("incorrect number of args") - } - for i, spec := range e.arguments { - userArg := arguments[i] - err := spec.typeCheck(userArg) - if err != nil { - return nil, err - } - } - return arguments, nil - } - if len(arguments) < len(e.arguments) { - return nil, errors.New("Invalid arity.") - } - return arguments, nil -} - -func (a *argSpec) typeCheck(arg interface{}) error { - for _, t := range a.types { - switch t { - case jpNumber: - if _, ok := arg.(float64); ok { - return nil - } - case jpString: - if _, ok := arg.(string); ok { - return nil - } - case jpArray: - if isSliceType(arg) { - return nil - } - case jpObject: - if _, ok := arg.(map[string]interface{}); ok { - return nil - } - case jpArrayNumber: - if _, ok := toArrayNum(arg); ok { - return nil - } - case jpArrayString: - if _, ok := toArrayStr(arg); ok { - return nil - } - case jpAny: - return nil - case jpExpref: - if _, ok := arg.(expRef); ok { - return nil - } - } - } - return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types) -} - -func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) { - entry, ok := f.functionTable[name] - if !ok { - return nil, errors.New("unknown function: " + name) - } - resolvedArgs, err := entry.resolveArgs(arguments) - if err != nil { - return nil, err - } - if entry.hasExpRef { - var extra []interface{} - extra = append(extra, intr) - resolvedArgs = append(extra, resolvedArgs...) - } - return entry.handler(resolvedArgs) -} - -func jpfAbs(arguments []interface{}) (interface{}, error) { - num := arguments[0].(float64) - return math.Abs(num), nil -} - -func jpfLength(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if c, ok := arg.(string); ok { - return float64(utf8.RuneCountInString(c)), nil - } else if isSliceType(arg) { - v := reflect.ValueOf(arg) - return float64(v.Len()), nil - } else if c, ok := arg.(map[string]interface{}); ok { - return float64(len(c)), nil - } - return nil, errors.New("could not compute length()") -} - -func jpfStartsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - prefix := arguments[1].(string) - return strings.HasPrefix(search, prefix), nil -} - -func jpfAvg(arguments []interface{}) (interface{}, error) { - // We've already type checked the value so we can safely use - // type assertions. - args := arguments[0].([]interface{}) - length := float64(len(args)) - numerator := 0.0 - for _, n := range args { - numerator += n.(float64) - } - return numerator / length, nil -} -func jpfCeil(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Ceil(val), nil -} -func jpfContains(arguments []interface{}) (interface{}, error) { - search := arguments[0] - el := arguments[1] - if searchStr, ok := search.(string); ok { - if elStr, ok := el.(string); ok { - return strings.Index(searchStr, elStr) != -1, nil - } - return false, nil - } - // Otherwise this is a generic contains for []interface{} - general := search.([]interface{}) - for _, item := range general { - if item == el { - return true, nil - } - } - return false, nil -} -func jpfEndsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - suffix := arguments[1].(string) - return strings.HasSuffix(search, suffix), nil -} -func jpfFloor(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Floor(val), nil -} -func jpfMap(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - exp := arguments[1].(expRef) - node := exp.ref - arr := arguments[2].([]interface{}) - mapped := make([]interface{}, 0, len(arr)) - for _, value := range arr { - current, err := intr.Execute(node, value) - if err != nil { - return nil, err - } - mapped = append(mapped, current) - } - return mapped, nil -} -func jpfMax(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil - } - // Otherwise we're dealing with a max() of strings. - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil -} -func jpfMerge(arguments []interface{}) (interface{}, error) { - final := make(map[string]interface{}) - for _, m := range arguments { - mapped := m.(map[string]interface{}) - for key, value := range mapped { - final[key] = value - } - } - return final, nil -} -func jpfMaxBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - switch t := start.(type) { - case float64: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - case string: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - default: - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfSum(arguments []interface{}) (interface{}, error) { - items, _ := toArrayNum(arguments[0]) - sum := 0.0 - for _, item := range items { - sum += item - } - return sum, nil -} - -func jpfMin(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil - } - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil -} - -func jpfMinBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if t, ok := start.(float64); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else if t, ok := start.(string); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfType(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if _, ok := arg.(float64); ok { - return "number", nil - } - if _, ok := arg.(string); ok { - return "string", nil - } - if _, ok := arg.([]interface{}); ok { - return "array", nil - } - if _, ok := arg.(map[string]interface{}); ok { - return "object", nil - } - if arg == nil { - return "null", nil - } - if arg == true || arg == false { - return "boolean", nil - } - return nil, errors.New("unknown type") -} -func jpfKeys(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for key := range arg { - collected = append(collected, key) - } - return collected, nil -} -func jpfValues(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for _, value := range arg { - collected = append(collected, value) - } - return collected, nil -} -func jpfSort(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - d := sort.Float64Slice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil - } - // Otherwise we're dealing with sort()'ing strings. - items, _ := toArrayStr(arguments[0]) - d := sort.StringSlice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil -} -func jpfSortBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return arr, nil - } else if len(arr) == 1 { - return arr, nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if _, ok := start.(float64); ok { - sortable := &byExprFloat{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else if _, ok := start.(string); ok { - sortable := &byExprString{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfJoin(arguments []interface{}) (interface{}, error) { - sep := arguments[0].(string) - // We can't just do arguments[1].([]string), we have to - // manually convert each item to a string. - arrayStr := []string{} - for _, item := range arguments[1].([]interface{}) { - arrayStr = append(arrayStr, item.(string)) - } - return strings.Join(arrayStr, sep), nil -} -func jpfReverse(arguments []interface{}) (interface{}, error) { - if s, ok := arguments[0].(string); ok { - r := []rune(s) - for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r), nil - } - items := arguments[0].([]interface{}) - length := len(items) - reversed := make([]interface{}, length) - for i, item := range items { - reversed[length-(i+1)] = item - } - return reversed, nil -} -func jpfToArray(arguments []interface{}) (interface{}, error) { - if _, ok := arguments[0].([]interface{}); ok { - return arguments[0], nil - } - return arguments[:1:1], nil -} -func jpfToString(arguments []interface{}) (interface{}, error) { - if v, ok := arguments[0].(string); ok { - return v, nil - } - result, err := json.Marshal(arguments[0]) - if err != nil { - return nil, err - } - return string(result), nil -} -func jpfToNumber(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if v, ok := arg.(float64); ok { - return v, nil - } - if v, ok := arg.(string); ok { - conv, err := strconv.ParseFloat(v, 64) - if err != nil { - return nil, nil - } - return conv, nil - } - if _, ok := arg.([]interface{}); ok { - return nil, nil - } - if _, ok := arg.(map[string]interface{}); ok { - return nil, nil - } - if arg == nil { - return nil, nil - } - if arg == true || arg == false { - return nil, nil - } - return nil, errors.New("unknown type") -} -func jpfNotNull(arguments []interface{}) (interface{}, error) { - for _, arg := range arguments { - if arg != nil { - return arg, nil - } - } - return nil, nil -} diff --git a/vendor/github.com/jmespath/go-jmespath/interpreter.go b/vendor/github.com/jmespath/go-jmespath/interpreter.go deleted file mode 100644 index 13c74604c..000000000 --- a/vendor/github.com/jmespath/go-jmespath/interpreter.go +++ /dev/null @@ -1,418 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" - "unicode" - "unicode/utf8" -) - -/* This is a tree based interpreter. It walks the AST and directly - interprets the AST to search through a JSON document. -*/ - -type treeInterpreter struct { - fCall *functionCaller -} - -func newInterpreter() *treeInterpreter { - interpreter := treeInterpreter{} - interpreter.fCall = newFunctionCaller() - return &interpreter -} - -type expRef struct { - ref ASTNode -} - -// Execute takes an ASTNode and input data and interprets the AST directly. -// It will produce the result of applying the JMESPath expression associated -// with the ASTNode to the input data "value". -func (intr *treeInterpreter) Execute(node ASTNode, value interface{}) (interface{}, error) { - switch node.nodeType { - case ASTComparator: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - right, err := intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - switch node.value { - case tEQ: - return objsEqual(left, right), nil - case tNE: - return !objsEqual(left, right), nil - } - leftNum, ok := left.(float64) - if !ok { - return nil, nil - } - rightNum, ok := right.(float64) - if !ok { - return nil, nil - } - switch node.value { - case tGT: - return leftNum > rightNum, nil - case tGTE: - return leftNum >= rightNum, nil - case tLT: - return leftNum < rightNum, nil - case tLTE: - return leftNum <= rightNum, nil - } - case ASTExpRef: - return expRef{ref: node.children[0]}, nil - case ASTFunctionExpression: - resolvedArgs := []interface{}{} - for _, arg := range node.children { - current, err := intr.Execute(arg, value) - if err != nil { - return nil, err - } - resolvedArgs = append(resolvedArgs, current) - } - return intr.fCall.CallFunction(node.value.(string), resolvedArgs, intr) - case ASTField: - if m, ok := value.(map[string]interface{}); ok { - key := node.value.(string) - return m[key], nil - } - return intr.fieldFromStruct(node.value.(string), value) - case ASTFilterProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.filterProjectionWithReflection(node, left) - } - return nil, nil - } - compareNode := node.children[2] - collected := []interface{}{} - for _, element := range sliceType { - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil - case ASTFlatten: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - // If we can't type convert to []interface{}, there's - // a chance this could still work via reflection if we're - // dealing with user provided types. - if isSliceType(left) { - return intr.flattenWithReflection(left) - } - return nil, nil - } - flattened := []interface{}{} - for _, element := range sliceType { - if elementSlice, ok := element.([]interface{}); ok { - flattened = append(flattened, elementSlice...) - } else if isSliceType(element) { - reflectFlat := []interface{}{} - v := reflect.ValueOf(element) - for i := 0; i < v.Len(); i++ { - reflectFlat = append(reflectFlat, v.Index(i).Interface()) - } - flattened = append(flattened, reflectFlat...) - } else { - flattened = append(flattened, element) - } - } - return flattened, nil - case ASTIdentity, ASTCurrentNode: - return value, nil - case ASTIndex: - if sliceType, ok := value.([]interface{}); ok { - index := node.value.(int) - if index < 0 { - index += len(sliceType) - } - if index < len(sliceType) && index >= 0 { - return sliceType[index], nil - } - return nil, nil - } - // Otherwise try via reflection. - rv := reflect.ValueOf(value) - if rv.Kind() == reflect.Slice { - index := node.value.(int) - if index < 0 { - index += rv.Len() - } - if index < rv.Len() && index >= 0 { - v := rv.Index(index) - return v.Interface(), nil - } - } - return nil, nil - case ASTKeyValPair: - return intr.Execute(node.children[0], value) - case ASTLiteral: - return node.value, nil - case ASTMultiSelectHash: - if value == nil { - return nil, nil - } - collected := make(map[string]interface{}) - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - key := child.value.(string) - collected[key] = current - } - return collected, nil - case ASTMultiSelectList: - if value == nil { - return nil, nil - } - collected := []interface{}{} - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - collected = append(collected, current) - } - return collected, nil - case ASTOrExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - matched, err = intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - } - return matched, nil - case ASTAndExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return matched, nil - } - return intr.Execute(node.children[1], value) - case ASTNotExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return true, nil - } - return false, nil - case ASTPipe: - result := value - var err error - for _, child := range node.children { - result, err = intr.Execute(child, result) - if err != nil { - return nil, err - } - } - return result, nil - case ASTProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.projectWithReflection(node, left) - } - return nil, nil - } - collected := []interface{}{} - var current interface{} - for _, element := range sliceType { - current, err = intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - case ASTSubexpression, ASTIndexExpression: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - return intr.Execute(node.children[1], left) - case ASTSlice: - sliceType, ok := value.([]interface{}) - if !ok { - if isSliceType(value) { - return intr.sliceWithReflection(node, value) - } - return nil, nil - } - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - return slice(sliceType, sliceParams) - case ASTValueProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - mapType, ok := left.(map[string]interface{}) - if !ok { - return nil, nil - } - values := make([]interface{}, len(mapType)) - for _, value := range mapType { - values = append(values, value) - } - collected := []interface{}{} - for _, element := range values { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - } - return nil, errors.New("Unknown AST node: " + node.nodeType.String()) -} - -func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) { - rv := reflect.ValueOf(value) - first, n := utf8.DecodeRuneInString(key) - fieldName := string(unicode.ToUpper(first)) + key[n:] - if rv.Kind() == reflect.Struct { - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } else if rv.Kind() == reflect.Ptr { - // Handle multiple levels of indirection? - if rv.IsNil() { - return nil, nil - } - rv = rv.Elem() - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } - return nil, nil -} - -func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - flattened := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - if reflect.TypeOf(element).Kind() == reflect.Slice { - // Then insert the contents of the element - // slice into the flattened slice, - // i.e flattened = append(flattened, mySlice...) - elementV := reflect.ValueOf(element) - for j := 0; j < elementV.Len(); j++ { - flattened = append( - flattened, elementV.Index(j).Interface()) - } - } else { - flattened = append(flattened, element) - } - } - return flattened, nil -} - -func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - final := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - final = append(final, element) - } - return slice(final, sliceParams) -} - -func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}) (interface{}, error) { - compareNode := node.children[2] - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil -} - -func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}) (interface{}, error) { - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if result != nil { - collected = append(collected, result) - } - } - return collected, nil -} diff --git a/vendor/github.com/jmespath/go-jmespath/lexer.go b/vendor/github.com/jmespath/go-jmespath/lexer.go deleted file mode 100644 index 817900c8f..000000000 --- a/vendor/github.com/jmespath/go-jmespath/lexer.go +++ /dev/null @@ -1,420 +0,0 @@ -package jmespath - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "strings" - "unicode/utf8" -) - -type token struct { - tokenType tokType - value string - position int - length int -} - -type tokType int - -const eof = -1 - -// Lexer contains information about the expression being tokenized. -type Lexer struct { - expression string // The expression provided by the user. - currentPos int // The current position in the string. - lastWidth int // The width of the current rune. This - buf bytes.Buffer // Internal buffer used for building up values. -} - -// SyntaxError is the main error used whenever a lexing or parsing error occurs. -type SyntaxError struct { - msg string // Error message displayed to user - Expression string // Expression that generated a SyntaxError - Offset int // The location in the string where the error occurred -} - -func (e SyntaxError) Error() string { - // In the future, it would be good to underline the specific - // location where the error occurred. - return "SyntaxError: " + e.msg -} - -// HighlightLocation will show where the syntax error occurred. -// It will place a "^" character on a line below the expression -// at the point where the syntax error occurred. -func (e SyntaxError) HighlightLocation() string { - return e.Expression + "\n" + strings.Repeat(" ", e.Offset) + "^" -} - -//go:generate stringer -type=tokType -const ( - tUnknown tokType = iota - tStar - tDot - tFilter - tFlatten - tLparen - tRparen - tLbracket - tRbracket - tLbrace - tRbrace - tOr - tPipe - tNumber - tUnquotedIdentifier - tQuotedIdentifier - tComma - tColon - tLT - tLTE - tGT - tGTE - tEQ - tNE - tJSONLiteral - tStringLiteral - tCurrent - tExpref - tAnd - tNot - tEOF -) - -var basicTokens = map[rune]tokType{ - '.': tDot, - '*': tStar, - ',': tComma, - ':': tColon, - '{': tLbrace, - '}': tRbrace, - ']': tRbracket, // tLbracket not included because it could be "[]" - '(': tLparen, - ')': tRparen, - '@': tCurrent, -} - -// Bit mask for [a-zA-Z_] shifted down 64 bits to fit in a single uint64. -// When using this bitmask just be sure to shift the rune down 64 bits -// before checking against identifierStartBits. -const identifierStartBits uint64 = 576460745995190270 - -// Bit mask for [a-zA-Z0-9], 128 bits -> 2 uint64s. -var identifierTrailingBits = [2]uint64{287948901175001088, 576460745995190270} - -var whiteSpace = map[rune]bool{ - ' ': true, '\t': true, '\n': true, '\r': true, -} - -func (t token) String() string { - return fmt.Sprintf("Token{%+v, %s, %d, %d}", - t.tokenType, t.value, t.position, t.length) -} - -// NewLexer creates a new JMESPath lexer. -func NewLexer() *Lexer { - lexer := Lexer{} - return &lexer -} - -func (lexer *Lexer) next() rune { - if lexer.currentPos >= len(lexer.expression) { - lexer.lastWidth = 0 - return eof - } - r, w := utf8.DecodeRuneInString(lexer.expression[lexer.currentPos:]) - lexer.lastWidth = w - lexer.currentPos += w - return r -} - -func (lexer *Lexer) back() { - lexer.currentPos -= lexer.lastWidth -} - -func (lexer *Lexer) peek() rune { - t := lexer.next() - lexer.back() - return t -} - -// tokenize takes an expression and returns corresponding tokens. -func (lexer *Lexer) tokenize(expression string) ([]token, error) { - var tokens []token - lexer.expression = expression - lexer.currentPos = 0 - lexer.lastWidth = 0 -loop: - for { - r := lexer.next() - if identifierStartBits&(1<<(uint64(r)-64)) > 0 { - t := lexer.consumeUnquotedIdentifier() - tokens = append(tokens, t) - } else if val, ok := basicTokens[r]; ok { - // Basic single char token. - t := token{ - tokenType: val, - value: string(r), - position: lexer.currentPos - lexer.lastWidth, - length: 1, - } - tokens = append(tokens, t) - } else if r == '-' || (r >= '0' && r <= '9') { - t := lexer.consumeNumber() - tokens = append(tokens, t) - } else if r == '[' { - t := lexer.consumeLBracket() - tokens = append(tokens, t) - } else if r == '"' { - t, err := lexer.consumeQuotedIdentifier() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '\'' { - t, err := lexer.consumeRawStringLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '`' { - t, err := lexer.consumeLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '|' { - t := lexer.matchOrElse(r, '|', tOr, tPipe) - tokens = append(tokens, t) - } else if r == '<' { - t := lexer.matchOrElse(r, '=', tLTE, tLT) - tokens = append(tokens, t) - } else if r == '>' { - t := lexer.matchOrElse(r, '=', tGTE, tGT) - tokens = append(tokens, t) - } else if r == '!' { - t := lexer.matchOrElse(r, '=', tNE, tNot) - tokens = append(tokens, t) - } else if r == '=' { - t := lexer.matchOrElse(r, '=', tEQ, tUnknown) - tokens = append(tokens, t) - } else if r == '&' { - t := lexer.matchOrElse(r, '&', tAnd, tExpref) - tokens = append(tokens, t) - } else if r == eof { - break loop - } else if _, ok := whiteSpace[r]; ok { - // Ignore whitespace - } else { - return tokens, lexer.syntaxError(fmt.Sprintf("Unknown char: %s", strconv.QuoteRuneToASCII(r))) - } - } - tokens = append(tokens, token{tEOF, "", len(lexer.expression), 0}) - return tokens, nil -} - -// Consume characters until the ending rune "r" is reached. -// If the end of the expression is reached before seeing the -// terminating rune "r", then an error is returned. -// If no error occurs then the matching substring is returned. -// The returned string will not include the ending rune. -func (lexer *Lexer) consumeUntil(end rune) (string, error) { - start := lexer.currentPos - current := lexer.next() - for current != end && current != eof { - if current == '\\' && lexer.peek() != eof { - lexer.next() - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return "", SyntaxError{ - msg: "Unclosed delimiter: " + string(end), - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - return lexer.expression[start : lexer.currentPos-lexer.lastWidth], nil -} - -func (lexer *Lexer) consumeLiteral() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('`') - if err != nil { - return token{}, err - } - value = strings.Replace(value, "\\`", "`", -1) - return token{ - tokenType: tJSONLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) consumeRawStringLiteral() (token, error) { - start := lexer.currentPos - currentIndex := start - current := lexer.next() - for current != '\'' && lexer.peek() != eof { - if current == '\\' && lexer.peek() == '\'' { - chunk := lexer.expression[currentIndex : lexer.currentPos-1] - lexer.buf.WriteString(chunk) - lexer.buf.WriteString("'") - lexer.next() - currentIndex = lexer.currentPos - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return token{}, SyntaxError{ - msg: "Unclosed delimiter: '", - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - if currentIndex < lexer.currentPos { - lexer.buf.WriteString(lexer.expression[currentIndex : lexer.currentPos-1]) - } - value := lexer.buf.String() - // Reset the buffer so it can reused again. - lexer.buf.Reset() - return token{ - tokenType: tStringLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: lexer.expression, - Offset: lexer.currentPos - 1, - } -} - -// Checks for a two char token, otherwise matches a single character -// token. This is used whenever a two char token overlaps a single -// char token, e.g. "||" -> tPipe, "|" -> tOr. -func (lexer *Lexer) matchOrElse(first rune, second rune, matchedType tokType, singleCharType tokType) token { - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == second { - t = token{ - tokenType: matchedType, - value: string(first) + string(second), - position: start, - length: 2, - } - } else { - lexer.back() - t = token{ - tokenType: singleCharType, - value: string(first), - position: start, - length: 1, - } - } - return t -} - -func (lexer *Lexer) consumeLBracket() token { - // There's three options here: - // 1. A filter expression "[?" - // 2. A flatten operator "[]" - // 3. A bare rbracket "[" - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == '?' { - t = token{ - tokenType: tFilter, - value: "[?", - position: start, - length: 2, - } - } else if nextRune == ']' { - t = token{ - tokenType: tFlatten, - value: "[]", - position: start, - length: 2, - } - } else { - t = token{ - tokenType: tLbracket, - value: "[", - position: start, - length: 1, - } - lexer.back() - } - return t -} - -func (lexer *Lexer) consumeQuotedIdentifier() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('"') - if err != nil { - return token{}, err - } - var decoded string - asJSON := []byte("\"" + value + "\"") - if err := json.Unmarshal([]byte(asJSON), &decoded); err != nil { - return token{}, err - } - return token{ - tokenType: tQuotedIdentifier, - value: decoded, - position: start - 1, - length: len(decoded), - }, nil -} - -func (lexer *Lexer) consumeUnquotedIdentifier() token { - // Consume runes until we reach the end of an unquoted - // identifier. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < 0 || r > 128 || identifierTrailingBits[uint64(r)/64]&(1<<(uint64(r)%64)) == 0 { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tUnquotedIdentifier, - value: value, - position: start, - length: lexer.currentPos - start, - } -} - -func (lexer *Lexer) consumeNumber() token { - // Consume runes until we reach something that's not a number. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < '0' || r > '9' { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tNumber, - value: value, - position: start, - length: lexer.currentPos - start, - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/parser.go b/vendor/github.com/jmespath/go-jmespath/parser.go deleted file mode 100644 index 4abc303ab..000000000 --- a/vendor/github.com/jmespath/go-jmespath/parser.go +++ /dev/null @@ -1,603 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" -) - -type astNodeType int - -//go:generate stringer -type astNodeType -const ( - ASTEmpty astNodeType = iota - ASTComparator - ASTCurrentNode - ASTExpRef - ASTFunctionExpression - ASTField - ASTFilterProjection - ASTFlatten - ASTIdentity - ASTIndex - ASTIndexExpression - ASTKeyValPair - ASTLiteral - ASTMultiSelectHash - ASTMultiSelectList - ASTOrExpression - ASTAndExpression - ASTNotExpression - ASTPipe - ASTProjection - ASTSubexpression - ASTSlice - ASTValueProjection -) - -// ASTNode represents the abstract syntax tree of a JMESPath expression. -type ASTNode struct { - nodeType astNodeType - value interface{} - children []ASTNode -} - -func (node ASTNode) String() string { - return node.PrettyPrint(0) -} - -// PrettyPrint will pretty print the parsed AST. -// The AST is an implementation detail and this pretty print -// function is provided as a convenience method to help with -// debugging. You should not rely on its output as the internal -// structure of the AST may change at any time. -func (node ASTNode) PrettyPrint(indent int) string { - spaces := strings.Repeat(" ", indent) - output := fmt.Sprintf("%s%s {\n", spaces, node.nodeType) - nextIndent := indent + 2 - if node.value != nil { - if converted, ok := node.value.(fmt.Stringer); ok { - // Account for things like comparator nodes - // that are enums with a String() method. - output += fmt.Sprintf("%svalue: %s\n", strings.Repeat(" ", nextIndent), converted.String()) - } else { - output += fmt.Sprintf("%svalue: %#v\n", strings.Repeat(" ", nextIndent), node.value) - } - } - lastIndex := len(node.children) - if lastIndex > 0 { - output += fmt.Sprintf("%schildren: {\n", strings.Repeat(" ", nextIndent)) - childIndent := nextIndent + 2 - for _, elem := range node.children { - output += elem.PrettyPrint(childIndent) - } - } - output += fmt.Sprintf("%s}\n", spaces) - return output -} - -var bindingPowers = map[tokType]int{ - tEOF: 0, - tUnquotedIdentifier: 0, - tQuotedIdentifier: 0, - tRbracket: 0, - tRparen: 0, - tComma: 0, - tRbrace: 0, - tNumber: 0, - tCurrent: 0, - tExpref: 0, - tColon: 0, - tPipe: 1, - tOr: 2, - tAnd: 3, - tEQ: 5, - tLT: 5, - tLTE: 5, - tGT: 5, - tGTE: 5, - tNE: 5, - tFlatten: 9, - tStar: 20, - tFilter: 21, - tDot: 40, - tNot: 45, - tLbrace: 50, - tLbracket: 55, - tLparen: 60, -} - -// Parser holds state about the current expression being parsed. -type Parser struct { - expression string - tokens []token - index int -} - -// NewParser creates a new JMESPath parser. -func NewParser() *Parser { - p := Parser{} - return &p -} - -// Parse will compile a JMESPath expression. -func (p *Parser) Parse(expression string) (ASTNode, error) { - lexer := NewLexer() - p.expression = expression - p.index = 0 - tokens, err := lexer.tokenize(expression) - if err != nil { - return ASTNode{}, err - } - p.tokens = tokens - parsed, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() != tEOF { - return ASTNode{}, p.syntaxError(fmt.Sprintf( - "Unexpected token at the end of the expression: %s", p.current())) - } - return parsed, nil -} - -func (p *Parser) parseExpression(bindingPower int) (ASTNode, error) { - var err error - leftToken := p.lookaheadToken(0) - p.advance() - leftNode, err := p.nud(leftToken) - if err != nil { - return ASTNode{}, err - } - currentToken := p.current() - for bindingPower < bindingPowers[currentToken] { - p.advance() - leftNode, err = p.led(currentToken, leftNode) - if err != nil { - return ASTNode{}, err - } - currentToken = p.current() - } - return leftNode, nil -} - -func (p *Parser) parseIndexExpression() (ASTNode, error) { - if p.lookahead(0) == tColon || p.lookahead(1) == tColon { - return p.parseSliceExpression() - } - indexStr := p.lookaheadToken(0).value - parsedInt, err := strconv.Atoi(indexStr) - if err != nil { - return ASTNode{}, err - } - indexNode := ASTNode{nodeType: ASTIndex, value: parsedInt} - p.advance() - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return indexNode, nil -} - -func (p *Parser) parseSliceExpression() (ASTNode, error) { - parts := []*int{nil, nil, nil} - index := 0 - current := p.current() - for current != tRbracket && index < 3 { - if current == tColon { - index++ - p.advance() - } else if current == tNumber { - parsedInt, err := strconv.Atoi(p.lookaheadToken(0).value) - if err != nil { - return ASTNode{}, err - } - parts[index] = &parsedInt - p.advance() - } else { - return ASTNode{}, p.syntaxError( - "Expected tColon or tNumber" + ", received: " + p.current().String()) - } - current = p.current() - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTSlice, - value: parts, - }, nil -} - -func (p *Parser) match(tokenType tokType) error { - if p.current() == tokenType { - p.advance() - return nil - } - return p.syntaxError("Expected " + tokenType.String() + ", received: " + p.current().String()) -} - -func (p *Parser) led(tokenType tokType, node ASTNode) (ASTNode, error) { - switch tokenType { - case tDot: - if p.current() != tStar { - right, err := p.parseDotRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTSubexpression, - children: []ASTNode{node, right}, - }, err - } - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTValueProjection, - children: []ASTNode{node, right}, - }, err - case tPipe: - right, err := p.parseExpression(bindingPowers[tPipe]) - return ASTNode{nodeType: ASTPipe, children: []ASTNode{node, right}}, err - case tOr: - right, err := p.parseExpression(bindingPowers[tOr]) - return ASTNode{nodeType: ASTOrExpression, children: []ASTNode{node, right}}, err - case tAnd: - right, err := p.parseExpression(bindingPowers[tAnd]) - return ASTNode{nodeType: ASTAndExpression, children: []ASTNode{node, right}}, err - case tLparen: - name := node.value - var args []ASTNode - for p.current() != tRparen { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() == tComma { - if err := p.match(tComma); err != nil { - return ASTNode{}, err - } - } - args = append(args, expression) - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTFunctionExpression, - value: name, - children: args, - }, nil - case tFilter: - return p.parseFilter(node) - case tFlatten: - left := ASTNode{nodeType: ASTFlatten, children: []ASTNode{node}} - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{left, right}, - }, err - case tEQ, tNE, tGT, tGTE, tLT, tLTE: - right, err := p.parseExpression(bindingPowers[tokenType]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTComparator, - value: tokenType, - children: []ASTNode{node, right}, - }, nil - case tLbracket: - tokenType := p.current() - var right ASTNode - var err error - if tokenType == tNumber || tokenType == tColon { - right, err = p.parseIndexExpression() - if err != nil { - return ASTNode{}, err - } - return p.projectIfSlice(node, right) - } - // Otherwise this is a projection. - if err := p.match(tStar); err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{node, right}, - }, nil - } - return ASTNode{}, p.syntaxError("Unexpected token: " + tokenType.String()) -} - -func (p *Parser) nud(token token) (ASTNode, error) { - switch token.tokenType { - case tJSONLiteral: - var parsed interface{} - err := json.Unmarshal([]byte(token.value), &parsed) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTLiteral, value: parsed}, nil - case tStringLiteral: - return ASTNode{nodeType: ASTLiteral, value: token.value}, nil - case tUnquotedIdentifier: - return ASTNode{ - nodeType: ASTField, - value: token.value, - }, nil - case tQuotedIdentifier: - node := ASTNode{nodeType: ASTField, value: token.value} - if p.current() == tLparen { - return ASTNode{}, p.syntaxErrorToken("Can't have quoted identifier as function name.", token) - } - return node, nil - case tStar: - left := ASTNode{nodeType: ASTIdentity} - var right ASTNode - var err error - if p.current() == tRbracket { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - } - return ASTNode{nodeType: ASTValueProjection, children: []ASTNode{left, right}}, err - case tFilter: - return p.parseFilter(ASTNode{nodeType: ASTIdentity}) - case tLbrace: - return p.parseMultiSelectHash() - case tFlatten: - left := ASTNode{ - nodeType: ASTFlatten, - children: []ASTNode{{nodeType: ASTIdentity}}, - } - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTProjection, children: []ASTNode{left, right}}, nil - case tLbracket: - tokenType := p.current() - //var right ASTNode - if tokenType == tNumber || tokenType == tColon { - right, err := p.parseIndexExpression() - if err != nil { - return ASTNode{}, nil - } - return p.projectIfSlice(ASTNode{nodeType: ASTIdentity}, right) - } else if tokenType == tStar && p.lookahead(1) == tRbracket { - p.advance() - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{{nodeType: ASTIdentity}, right}, - }, nil - } else { - return p.parseMultiSelectList() - } - case tCurrent: - return ASTNode{nodeType: ASTCurrentNode}, nil - case tExpref: - expression, err := p.parseExpression(bindingPowers[tExpref]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTExpRef, children: []ASTNode{expression}}, nil - case tNot: - expression, err := p.parseExpression(bindingPowers[tNot]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTNotExpression, children: []ASTNode{expression}}, nil - case tLparen: - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return expression, nil - case tEOF: - return ASTNode{}, p.syntaxErrorToken("Incomplete expression", token) - } - - return ASTNode{}, p.syntaxErrorToken("Invalid token: "+token.tokenType.String(), token) -} - -func (p *Parser) parseMultiSelectList() (ASTNode, error) { - var expressions []ASTNode - for { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - expressions = append(expressions, expression) - if p.current() == tRbracket { - break - } - err = p.match(tComma) - if err != nil { - return ASTNode{}, err - } - } - err := p.match(tRbracket) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTMultiSelectList, - children: expressions, - }, nil -} - -func (p *Parser) parseMultiSelectHash() (ASTNode, error) { - var children []ASTNode - for { - keyToken := p.lookaheadToken(0) - if err := p.match(tUnquotedIdentifier); err != nil { - if err := p.match(tQuotedIdentifier); err != nil { - return ASTNode{}, p.syntaxError("Expected tQuotedIdentifier or tUnquotedIdentifier") - } - } - keyName := keyToken.value - err := p.match(tColon) - if err != nil { - return ASTNode{}, err - } - value, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - node := ASTNode{ - nodeType: ASTKeyValPair, - value: keyName, - children: []ASTNode{value}, - } - children = append(children, node) - if p.current() == tComma { - err := p.match(tComma) - if err != nil { - return ASTNode{}, nil - } - } else if p.current() == tRbrace { - err := p.match(tRbrace) - if err != nil { - return ASTNode{}, nil - } - break - } - } - return ASTNode{ - nodeType: ASTMultiSelectHash, - children: children, - }, nil -} - -func (p *Parser) projectIfSlice(left ASTNode, right ASTNode) (ASTNode, error) { - indexExpr := ASTNode{ - nodeType: ASTIndexExpression, - children: []ASTNode{left, right}, - } - if right.nodeType == ASTSlice { - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{indexExpr, right}, - }, err - } - return indexExpr, nil -} -func (p *Parser) parseFilter(node ASTNode) (ASTNode, error) { - var right, condition ASTNode - var err error - condition, err = p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - if p.current() == tFlatten { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tFilter]) - if err != nil { - return ASTNode{}, err - } - } - - return ASTNode{ - nodeType: ASTFilterProjection, - children: []ASTNode{node, right, condition}, - }, nil -} - -func (p *Parser) parseDotRHS(bindingPower int) (ASTNode, error) { - lookahead := p.current() - if tokensOneOf([]tokType{tQuotedIdentifier, tUnquotedIdentifier, tStar}, lookahead) { - return p.parseExpression(bindingPower) - } else if lookahead == tLbracket { - if err := p.match(tLbracket); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectList() - } else if lookahead == tLbrace { - if err := p.match(tLbrace); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectHash() - } - return ASTNode{}, p.syntaxError("Expected identifier, lbracket, or lbrace") -} - -func (p *Parser) parseProjectionRHS(bindingPower int) (ASTNode, error) { - current := p.current() - if bindingPowers[current] < 10 { - return ASTNode{nodeType: ASTIdentity}, nil - } else if current == tLbracket { - return p.parseExpression(bindingPower) - } else if current == tFilter { - return p.parseExpression(bindingPower) - } else if current == tDot { - err := p.match(tDot) - if err != nil { - return ASTNode{}, err - } - return p.parseDotRHS(bindingPower) - } else { - return ASTNode{}, p.syntaxError("Error") - } -} - -func (p *Parser) lookahead(number int) tokType { - return p.lookaheadToken(number).tokenType -} - -func (p *Parser) current() tokType { - return p.lookahead(0) -} - -func (p *Parser) lookaheadToken(number int) token { - return p.tokens[p.index+number] -} - -func (p *Parser) advance() { - p.index++ -} - -func tokensOneOf(elements []tokType, token tokType) bool { - for _, elem := range elements { - if elem == token { - return true - } - } - return false -} - -func (p *Parser) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: p.lookaheadToken(0).position, - } -} - -// Create a SyntaxError based on the provided token. -// This differs from syntaxError() which creates a SyntaxError -// based on the current lookahead token. -func (p *Parser) syntaxErrorToken(msg string, t token) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: t.position, - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/toktype_string.go b/vendor/github.com/jmespath/go-jmespath/toktype_string.go deleted file mode 100644 index dae79cbdf..000000000 --- a/vendor/github.com/jmespath/go-jmespath/toktype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// generated by stringer -type=tokType; DO NOT EDIT - -package jmespath - -import "fmt" - -const _tokType_name = "tUnknowntStartDottFiltertFlattentLparentRparentLbrackettRbrackettLbracetRbracetOrtPipetNumbertUnquotedIdentifiertQuotedIdentifiertCommatColontLTtLTEtGTtGTEtEQtNEtJSONLiteraltStringLiteraltCurrenttExpreftAndtNottEOF" - -var _tokType_index = [...]uint8{0, 8, 13, 17, 24, 32, 39, 46, 55, 64, 71, 78, 81, 86, 93, 112, 129, 135, 141, 144, 148, 151, 155, 158, 161, 173, 187, 195, 202, 206, 210, 214} - -func (i tokType) String() string { - if i < 0 || i >= tokType(len(_tokType_index)-1) { - return fmt.Sprintf("tokType(%d)", i) - } - return _tokType_name[_tokType_index[i]:_tokType_index[i+1]] -} diff --git a/vendor/github.com/jmespath/go-jmespath/util.go b/vendor/github.com/jmespath/go-jmespath/util.go deleted file mode 100644 index ddc1b7d7d..000000000 --- a/vendor/github.com/jmespath/go-jmespath/util.go +++ /dev/null @@ -1,185 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" -) - -// IsFalse determines if an object is false based on the JMESPath spec. -// JMESPath defines false values to be any of: -// - An empty string array, or hash. -// - The boolean value false. -// - nil -func isFalse(value interface{}) bool { - switch v := value.(type) { - case bool: - return !v - case []interface{}: - return len(v) == 0 - case map[string]interface{}: - return len(v) == 0 - case string: - return len(v) == 0 - case nil: - return true - } - // Try the reflection cases before returning false. - rv := reflect.ValueOf(value) - switch rv.Kind() { - case reflect.Struct: - // A struct type will never be false, even if - // all of its values are the zero type. - return false - case reflect.Slice, reflect.Map: - return rv.Len() == 0 - case reflect.Ptr: - if rv.IsNil() { - return true - } - // If it's a pointer type, we'll try to deref the pointer - // and evaluate the pointer value for isFalse. - element := rv.Elem() - return isFalse(element.Interface()) - } - return false -} - -// ObjsEqual is a generic object equality check. -// It will take two arbitrary objects and recursively determine -// if they are equal. -func objsEqual(left interface{}, right interface{}) bool { - return reflect.DeepEqual(left, right) -} - -// SliceParam refers to a single part of a slice. -// A slice consists of a start, a stop, and a step, similar to -// python slices. -type sliceParam struct { - N int - Specified bool -} - -// Slice supports [start:stop:step] style slicing that's supported in JMESPath. -func slice(slice []interface{}, parts []sliceParam) ([]interface{}, error) { - computed, err := computeSliceParams(len(slice), parts) - if err != nil { - return nil, err - } - start, stop, step := computed[0], computed[1], computed[2] - result := []interface{}{} - if step > 0 { - for i := start; i < stop; i += step { - result = append(result, slice[i]) - } - } else { - for i := start; i > stop; i += step { - result = append(result, slice[i]) - } - } - return result, nil -} - -func computeSliceParams(length int, parts []sliceParam) ([]int, error) { - var start, stop, step int - if !parts[2].Specified { - step = 1 - } else if parts[2].N == 0 { - return nil, errors.New("Invalid slice, step cannot be 0") - } else { - step = parts[2].N - } - var stepValueNegative bool - if step < 0 { - stepValueNegative = true - } else { - stepValueNegative = false - } - - if !parts[0].Specified { - if stepValueNegative { - start = length - 1 - } else { - start = 0 - } - } else { - start = capSlice(length, parts[0].N, step) - } - - if !parts[1].Specified { - if stepValueNegative { - stop = -1 - } else { - stop = length - } - } else { - stop = capSlice(length, parts[1].N, step) - } - return []int{start, stop, step}, nil -} - -func capSlice(length int, actual int, step int) int { - if actual < 0 { - actual += length - if actual < 0 { - if step < 0 { - actual = -1 - } else { - actual = 0 - } - } - } else if actual >= length { - if step < 0 { - actual = length - 1 - } else { - actual = length - } - } - return actual -} - -// ToArrayNum converts an empty interface type to a slice of float64. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. -func toArrayNum(data interface{}) ([]float64, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]float64, len(d)) - for i, el := range d { - item, ok := el.(float64) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -// ToArrayStr converts an empty interface type to a slice of strings. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. If the input data could be entirely -// converted, then the converted data, along with a second value of true, -// will be returned. -func toArrayStr(data interface{}) ([]string, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]string, len(d)) - for i, el := range d { - item, ok := el.(string) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -func isSliceType(v interface{}) bool { - if v == nil { - return false - } - return reflect.TypeOf(v).Kind() == reflect.Slice -} diff --git a/vendor/github.com/joho/godotenv/.gitignore b/vendor/github.com/joho/godotenv/.gitignore deleted file mode 100644 index e43b0f988..000000000 --- a/vendor/github.com/joho/godotenv/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.DS_Store diff --git a/vendor/github.com/joho/godotenv/LICENCE b/vendor/github.com/joho/godotenv/LICENCE deleted file mode 100644 index e7ddd51be..000000000 --- a/vendor/github.com/joho/godotenv/LICENCE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2013 John Barton - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/vendor/github.com/joho/godotenv/README.md b/vendor/github.com/joho/godotenv/README.md deleted file mode 100644 index bfbe66a0e..000000000 --- a/vendor/github.com/joho/godotenv/README.md +++ /dev/null @@ -1,202 +0,0 @@ -# GoDotEnv ![CI](https://github.com/joho/godotenv/workflows/CI/badge.svg) [![Go Report Card](https://goreportcard.com/badge/github.com/joho/godotenv)](https://goreportcard.com/report/github.com/joho/godotenv) - -A Go (golang) port of the Ruby [dotenv](https://github.com/bkeepers/dotenv) project (which loads env vars from a .env file). - -From the original Library: - -> Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments–such as resource handles for databases or credentials for external services–should be extracted from the code into environment variables. -> -> But it is not always practical to set environment variables on development machines or continuous integration servers where multiple projects are run. Dotenv load variables from a .env file into ENV when the environment is bootstrapped. - -It can be used as a library (for loading in env for your own daemons etc.) or as a bin command. - -There is test coverage and CI for both linuxish and Windows environments, but I make no guarantees about the bin version working on Windows. - -## Installation - -As a library - -```shell -go get github.com/joho/godotenv -``` - -or if you want to use it as a bin command - -go >= 1.17 -```shell -go install github.com/joho/godotenv/cmd/godotenv@latest -``` - -go < 1.17 -```shell -go get github.com/joho/godotenv/cmd/godotenv -``` - -## Usage - -Add your application configuration to your `.env` file in the root of your project: - -```shell -S3_BUCKET=YOURS3BUCKET -SECRET_KEY=YOURSECRETKEYGOESHERE -``` - -Then in your Go app you can do something like - -```go -package main - -import ( - "log" - "os" - - "github.com/joho/godotenv" -) - -func main() { - err := godotenv.Load() - if err != nil { - log.Fatal("Error loading .env file") - } - - s3Bucket := os.Getenv("S3_BUCKET") - secretKey := os.Getenv("SECRET_KEY") - - // now do something with s3 or whatever -} -``` - -If you're even lazier than that, you can just take advantage of the autoload package which will read in `.env` on import - -```go -import _ "github.com/joho/godotenv/autoload" -``` - -While `.env` in the project root is the default, you don't have to be constrained, both examples below are 100% legit - -```go -godotenv.Load("somerandomfile") -godotenv.Load("filenumberone.env", "filenumbertwo.env") -``` - -If you want to be really fancy with your env file you can do comments and exports (below is a valid env file) - -```shell -# I am a comment and that is OK -SOME_VAR=someval -FOO=BAR # comments at line end are OK too -export BAR=BAZ -``` - -Or finally you can do YAML(ish) style - -```yaml -FOO: bar -BAR: baz -``` - -as a final aside, if you don't want godotenv munging your env you can just get a map back instead - -```go -var myEnv map[string]string -myEnv, err := godotenv.Read() - -s3Bucket := myEnv["S3_BUCKET"] -``` - -... or from an `io.Reader` instead of a local file - -```go -reader := getRemoteFile() -myEnv, err := godotenv.Parse(reader) -``` - -... or from a `string` if you so desire - -```go -content := getRemoteFileContent() -myEnv, err := godotenv.Unmarshal(content) -``` - -### Precedence & Conventions - -Existing envs take precedence of envs that are loaded later. - -The [convention](https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use) -for managing multiple environments (i.e. development, test, production) -is to create an env named `{YOURAPP}_ENV` and load envs in this order: - -```go -env := os.Getenv("FOO_ENV") -if "" == env { - env = "development" -} - -godotenv.Load(".env." + env + ".local") -if "test" != env { - godotenv.Load(".env.local") -} -godotenv.Load(".env." + env) -godotenv.Load() // The Original .env -``` - -If you need to, you can also use `godotenv.Overload()` to defy this convention -and overwrite existing envs instead of only supplanting them. Use with caution. - -### Command Mode - -Assuming you've installed the command as above and you've got `$GOPATH/bin` in your `$PATH` - -``` -godotenv -f /some/path/to/.env some_command with some args -``` - -If you don't specify `-f` it will fall back on the default of loading `.env` in `PWD` - -By default, it won't override existing environment variables; you can do that with the `-o` flag. - -### Writing Env Files - -Godotenv can also write a map representing the environment to a correctly-formatted and escaped file - -```go -env, err := godotenv.Unmarshal("KEY=value") -err := godotenv.Write(env, "./.env") -``` - -... or to a string - -```go -env, err := godotenv.Unmarshal("KEY=value") -content, err := godotenv.Marshal(env) -``` - -## Contributing - -Contributions are welcome, but with some caveats. - -This library has been declared feature complete (see [#182](https://github.com/joho/godotenv/issues/182) for background) and will not be accepting issues or pull requests adding new functionality or breaking the library API. - -Contributions would be gladly accepted that: - -* bring this library's parsing into closer compatibility with the mainline dotenv implementations, in particular [Ruby's dotenv](https://github.com/bkeepers/dotenv) and [Node.js' dotenv](https://github.com/motdotla/dotenv) -* keep the library up to date with the go ecosystem (ie CI bumps, documentation changes, changes in the core libraries) -* bug fixes for use cases that pertain to the library's purpose of easing development of codebases deployed into twelve factor environments - -*code changes without tests and references to peer dotenv implementations will not be accepted* - -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Added some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request - -## Releases - -Releases should follow [Semver](http://semver.org/) though the first couple of releases are `v1` and `v1.1`. - -Use [annotated tags for all releases](https://github.com/joho/godotenv/issues/30). Example `git tag -a v1.2.1` - -## Who? - -The original library [dotenv](https://github.com/bkeepers/dotenv) was written by [Brandon Keepers](http://opensoul.org/), and this port was done by [John Barton](https://johnbarton.co/) based off the tests/fixtures in the original library. diff --git a/vendor/github.com/joho/godotenv/godotenv.go b/vendor/github.com/joho/godotenv/godotenv.go deleted file mode 100644 index 61b0ebbaf..000000000 --- a/vendor/github.com/joho/godotenv/godotenv.go +++ /dev/null @@ -1,228 +0,0 @@ -// Package godotenv is a go port of the ruby dotenv library (https://github.com/bkeepers/dotenv) -// -// Examples/readme can be found on the GitHub page at https://github.com/joho/godotenv -// -// The TL;DR is that you make a .env file that looks something like -// -// SOME_ENV_VAR=somevalue -// -// and then in your go code you can call -// -// godotenv.Load() -// -// and all the env vars declared in .env will be available through os.Getenv("SOME_ENV_VAR") -package godotenv - -import ( - "bytes" - "fmt" - "io" - "os" - "os/exec" - "sort" - "strconv" - "strings" -) - -const doubleQuoteSpecialChars = "\\\n\r\"!$`" - -// Parse reads an env file from io.Reader, returning a map of keys and values. -func Parse(r io.Reader) (map[string]string, error) { - var buf bytes.Buffer - _, err := io.Copy(&buf, r) - if err != nil { - return nil, err - } - - return UnmarshalBytes(buf.Bytes()) -} - -// Load will read your env file(s) and load them into ENV for this process. -// -// Call this function as close as possible to the start of your program (ideally in main). -// -// If you call Load without any args it will default to loading .env in the current path. -// -// You can otherwise tell it which files to load (there can be more than one) like: -// -// godotenv.Load("fileone", "filetwo") -// -// It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults. -func Load(filenames ...string) (err error) { - filenames = filenamesOrDefault(filenames) - - for _, filename := range filenames { - err = loadFile(filename, false) - if err != nil { - return // return early on a spazout - } - } - return -} - -// Overload will read your env file(s) and load them into ENV for this process. -// -// Call this function as close as possible to the start of your program (ideally in main). -// -// If you call Overload without any args it will default to loading .env in the current path. -// -// You can otherwise tell it which files to load (there can be more than one) like: -// -// godotenv.Overload("fileone", "filetwo") -// -// It's important to note this WILL OVERRIDE an env variable that already exists - consider the .env file to forcefully set all vars. -func Overload(filenames ...string) (err error) { - filenames = filenamesOrDefault(filenames) - - for _, filename := range filenames { - err = loadFile(filename, true) - if err != nil { - return // return early on a spazout - } - } - return -} - -// Read all env (with same file loading semantics as Load) but return values as -// a map rather than automatically writing values into env -func Read(filenames ...string) (envMap map[string]string, err error) { - filenames = filenamesOrDefault(filenames) - envMap = make(map[string]string) - - for _, filename := range filenames { - individualEnvMap, individualErr := readFile(filename) - - if individualErr != nil { - err = individualErr - return // return early on a spazout - } - - for key, value := range individualEnvMap { - envMap[key] = value - } - } - - return -} - -// Unmarshal reads an env file from a string, returning a map of keys and values. -func Unmarshal(str string) (envMap map[string]string, err error) { - return UnmarshalBytes([]byte(str)) -} - -// UnmarshalBytes parses env file from byte slice of chars, returning a map of keys and values. -func UnmarshalBytes(src []byte) (map[string]string, error) { - out := make(map[string]string) - err := parseBytes(src, out) - - return out, err -} - -// Exec loads env vars from the specified filenames (empty map falls back to default) -// then executes the cmd specified. -// -// Simply hooks up os.Stdin/err/out to the command and calls Run(). -// -// If you want more fine grained control over your command it's recommended -// that you use `Load()`, `Overload()` or `Read()` and the `os/exec` package yourself. -func Exec(filenames []string, cmd string, cmdArgs []string, overload bool) error { - op := Load - if overload { - op = Overload - } - if err := op(filenames...); err != nil { - return err - } - - command := exec.Command(cmd, cmdArgs...) - command.Stdin = os.Stdin - command.Stdout = os.Stdout - command.Stderr = os.Stderr - return command.Run() -} - -// Write serializes the given environment and writes it to a file. -func Write(envMap map[string]string, filename string) error { - content, err := Marshal(envMap) - if err != nil { - return err - } - file, err := os.Create(filename) - if err != nil { - return err - } - defer file.Close() - _, err = file.WriteString(content + "\n") - if err != nil { - return err - } - return file.Sync() -} - -// Marshal outputs the given environment as a dotenv-formatted environment file. -// Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped. -func Marshal(envMap map[string]string) (string, error) { - lines := make([]string, 0, len(envMap)) - for k, v := range envMap { - if d, err := strconv.Atoi(v); err == nil { - lines = append(lines, fmt.Sprintf(`%s=%d`, k, d)) - } else { - lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v))) - } - } - sort.Strings(lines) - return strings.Join(lines, "\n"), nil -} - -func filenamesOrDefault(filenames []string) []string { - if len(filenames) == 0 { - return []string{".env"} - } - return filenames -} - -func loadFile(filename string, overload bool) error { - envMap, err := readFile(filename) - if err != nil { - return err - } - - currentEnv := map[string]bool{} - rawEnv := os.Environ() - for _, rawEnvLine := range rawEnv { - key := strings.Split(rawEnvLine, "=")[0] - currentEnv[key] = true - } - - for key, value := range envMap { - if !currentEnv[key] || overload { - _ = os.Setenv(key, value) - } - } - - return nil -} - -func readFile(filename string) (envMap map[string]string, err error) { - file, err := os.Open(filename) - if err != nil { - return - } - defer file.Close() - - return Parse(file) -} - -func doubleQuoteEscape(line string) string { - for _, c := range doubleQuoteSpecialChars { - toReplace := "\\" + string(c) - if c == '\n' { - toReplace = `\n` - } - if c == '\r' { - toReplace = `\r` - } - line = strings.Replace(line, string(c), toReplace, -1) - } - return line -} diff --git a/vendor/github.com/joho/godotenv/parser.go b/vendor/github.com/joho/godotenv/parser.go deleted file mode 100644 index cc709af89..000000000 --- a/vendor/github.com/joho/godotenv/parser.go +++ /dev/null @@ -1,271 +0,0 @@ -package godotenv - -import ( - "bytes" - "errors" - "fmt" - "regexp" - "strings" - "unicode" -) - -const ( - charComment = '#' - prefixSingleQuote = '\'' - prefixDoubleQuote = '"' - - exportPrefix = "export" -) - -func parseBytes(src []byte, out map[string]string) error { - src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1) - cutset := src - for { - cutset = getStatementStart(cutset) - if cutset == nil { - // reached end of file - break - } - - key, left, err := locateKeyName(cutset) - if err != nil { - return err - } - - value, left, err := extractVarValue(left, out) - if err != nil { - return err - } - - out[key] = value - cutset = left - } - - return nil -} - -// getStatementPosition returns position of statement begin. -// -// It skips any comment line or non-whitespace character. -func getStatementStart(src []byte) []byte { - pos := indexOfNonSpaceChar(src) - if pos == -1 { - return nil - } - - src = src[pos:] - if src[0] != charComment { - return src - } - - // skip comment section - pos = bytes.IndexFunc(src, isCharFunc('\n')) - if pos == -1 { - return nil - } - - return getStatementStart(src[pos:]) -} - -// locateKeyName locates and parses key name and returns rest of slice -func locateKeyName(src []byte) (key string, cutset []byte, err error) { - // trim "export" and space at beginning - src = bytes.TrimLeftFunc(src, isSpace) - if bytes.HasPrefix(src, []byte(exportPrefix)) { - trimmed := bytes.TrimPrefix(src, []byte(exportPrefix)) - if bytes.IndexFunc(trimmed, isSpace) == 0 { - src = bytes.TrimLeftFunc(trimmed, isSpace) - } - } - - // locate key name end and validate it in single loop - offset := 0 -loop: - for i, char := range src { - rchar := rune(char) - if isSpace(rchar) { - continue - } - - switch char { - case '=', ':': - // library also supports yaml-style value declaration - key = string(src[0:i]) - offset = i + 1 - break loop - case '_': - default: - // variable name should match [A-Za-z0-9_.] - if unicode.IsLetter(rchar) || unicode.IsNumber(rchar) || rchar == '.' { - continue - } - - return "", nil, fmt.Errorf( - `unexpected character %q in variable name near %q`, - string(char), string(src)) - } - } - - if len(src) == 0 { - return "", nil, errors.New("zero length string") - } - - // trim whitespace - key = strings.TrimRightFunc(key, unicode.IsSpace) - cutset = bytes.TrimLeftFunc(src[offset:], isSpace) - return key, cutset, nil -} - -// extractVarValue extracts variable value and returns rest of slice -func extractVarValue(src []byte, vars map[string]string) (value string, rest []byte, err error) { - quote, hasPrefix := hasQuotePrefix(src) - if !hasPrefix { - // unquoted value - read until end of line - endOfLine := bytes.IndexFunc(src, isLineEnd) - - // Hit EOF without a trailing newline - if endOfLine == -1 { - endOfLine = len(src) - - if endOfLine == 0 { - return "", nil, nil - } - } - - // Convert line to rune away to do accurate countback of runes - line := []rune(string(src[0:endOfLine])) - - // Assume end of line is end of var - endOfVar := len(line) - if endOfVar == 0 { - return "", src[endOfLine:], nil - } - - // Work backwards to check if the line ends in whitespace then - // a comment (ie asdasd # some comment) - for i := endOfVar - 1; i >= 0; i-- { - if line[i] == charComment && i > 0 { - if isSpace(line[i-1]) { - endOfVar = i - break - } - } - } - - trimmed := strings.TrimFunc(string(line[0:endOfVar]), isSpace) - - return expandVariables(trimmed, vars), src[endOfLine:], nil - } - - // lookup quoted string terminator - for i := 1; i < len(src); i++ { - if char := src[i]; char != quote { - continue - } - - // skip escaped quote symbol (\" or \', depends on quote) - if prevChar := src[i-1]; prevChar == '\\' { - continue - } - - // trim quotes - trimFunc := isCharFunc(rune(quote)) - value = string(bytes.TrimLeftFunc(bytes.TrimRightFunc(src[0:i], trimFunc), trimFunc)) - if quote == prefixDoubleQuote { - // unescape newlines for double quote (this is compat feature) - // and expand environment variables - value = expandVariables(expandEscapes(value), vars) - } - - return value, src[i+1:], nil - } - - // return formatted error if quoted string is not terminated - valEndIndex := bytes.IndexFunc(src, isCharFunc('\n')) - if valEndIndex == -1 { - valEndIndex = len(src) - } - - return "", nil, fmt.Errorf("unterminated quoted value %s", src[:valEndIndex]) -} - -func expandEscapes(str string) string { - out := escapeRegex.ReplaceAllStringFunc(str, func(match string) string { - c := strings.TrimPrefix(match, `\`) - switch c { - case "n": - return "\n" - case "r": - return "\r" - default: - return match - } - }) - return unescapeCharsRegex.ReplaceAllString(out, "$1") -} - -func indexOfNonSpaceChar(src []byte) int { - return bytes.IndexFunc(src, func(r rune) bool { - return !unicode.IsSpace(r) - }) -} - -// hasQuotePrefix reports whether charset starts with single or double quote and returns quote character -func hasQuotePrefix(src []byte) (prefix byte, isQuored bool) { - if len(src) == 0 { - return 0, false - } - - switch prefix := src[0]; prefix { - case prefixDoubleQuote, prefixSingleQuote: - return prefix, true - default: - return 0, false - } -} - -func isCharFunc(char rune) func(rune) bool { - return func(v rune) bool { - return v == char - } -} - -// isSpace reports whether the rune is a space character but not line break character -// -// this differs from unicode.IsSpace, which also applies line break as space -func isSpace(r rune) bool { - switch r { - case '\t', '\v', '\f', '\r', ' ', 0x85, 0xA0: - return true - } - return false -} - -func isLineEnd(r rune) bool { - if r == '\n' || r == '\r' { - return true - } - return false -} - -var ( - escapeRegex = regexp.MustCompile(`\\.`) - expandVarRegex = regexp.MustCompile(`(\\)?(\$)(\()?\{?([A-Z0-9_]+)?\}?`) - unescapeCharsRegex = regexp.MustCompile(`\\([^$])`) -) - -func expandVariables(v string, m map[string]string) string { - return expandVarRegex.ReplaceAllStringFunc(v, func(s string) string { - submatch := expandVarRegex.FindStringSubmatch(s) - - if submatch == nil { - return s - } - if submatch[1] == "\\" || submatch[2] == "(" { - return submatch[0][1:] - } else if submatch[4] != "" { - return m[submatch[4]] - } - return s - }) -} diff --git a/vendor/github.com/josharian/intern/README.md b/vendor/github.com/josharian/intern/README.md deleted file mode 100644 index ffc44b219..000000000 --- a/vendor/github.com/josharian/intern/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Docs: https://godoc.org/github.com/josharian/intern - -See also [Go issue 5160](https://golang.org/issue/5160). - -License: MIT diff --git a/vendor/github.com/josharian/intern/intern.go b/vendor/github.com/josharian/intern/intern.go deleted file mode 100644 index 7acb1fe90..000000000 --- a/vendor/github.com/josharian/intern/intern.go +++ /dev/null @@ -1,44 +0,0 @@ -// Package intern interns strings. -// Interning is best effort only. -// Interned strings may be removed automatically -// at any time without notification. -// All functions may be called concurrently -// with themselves and each other. -package intern - -import "sync" - -var ( - pool sync.Pool = sync.Pool{ - New: func() interface{} { - return make(map[string]string) - }, - } -) - -// String returns s, interned. -func String(s string) string { - m := pool.Get().(map[string]string) - c, ok := m[s] - if ok { - pool.Put(m) - return c - } - m[s] = s - pool.Put(m) - return s -} - -// Bytes returns b converted to a string, interned. -func Bytes(b []byte) string { - m := pool.Get().(map[string]string) - c, ok := m[string(b)] - if ok { - pool.Put(m) - return c - } - s := string(b) - m[s] = s - pool.Put(m) - return s -} diff --git a/vendor/github.com/josharian/intern/license.md b/vendor/github.com/josharian/intern/license.md deleted file mode 100644 index 353d3055f..000000000 --- a/vendor/github.com/josharian/intern/license.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Josh Bleecher Snyder - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/klauspost/compress/.gitattributes b/vendor/github.com/klauspost/compress/.gitattributes deleted file mode 100644 index 402433593..000000000 --- a/vendor/github.com/klauspost/compress/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -* -text -*.bin -text -diff diff --git a/vendor/github.com/klauspost/compress/.gitignore b/vendor/github.com/klauspost/compress/.gitignore deleted file mode 100644 index d31b37815..000000000 --- a/vendor/github.com/klauspost/compress/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# 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 -/s2/cmd/_s2sx/sfx-exe - -# Linux perf files -perf.data -perf.data.old - -# gdb history -.gdb_history diff --git a/vendor/github.com/klauspost/compress/.goreleaser.yml b/vendor/github.com/klauspost/compress/.goreleaser.yml deleted file mode 100644 index a22953805..000000000 --- a/vendor/github.com/klauspost/compress/.goreleaser.yml +++ /dev/null @@ -1,123 +0,0 @@ -# This is an example goreleaser.yaml file with some sane defaults. -# Make sure to check the documentation at http://goreleaser.com -before: - hooks: - - ./gen.sh - -builds: - - - id: "s2c" - binary: s2c - main: ./s2/cmd/s2c/main.go - flags: - - -trimpath - env: - - CGO_ENABLED=0 - goos: - - aix - - linux - - freebsd - - netbsd - - windows - - darwin - goarch: - - 386 - - amd64 - - arm - - arm64 - - ppc64 - - ppc64le - - mips64 - - mips64le - goarm: - - 7 - - - id: "s2d" - binary: s2d - main: ./s2/cmd/s2d/main.go - flags: - - -trimpath - env: - - CGO_ENABLED=0 - goos: - - aix - - linux - - freebsd - - netbsd - - windows - - darwin - goarch: - - 386 - - amd64 - - arm - - arm64 - - ppc64 - - ppc64le - - mips64 - - mips64le - goarm: - - 7 - - - id: "s2sx" - binary: s2sx - main: ./s2/cmd/_s2sx/main.go - flags: - - -modfile=s2sx.mod - - -trimpath - env: - - CGO_ENABLED=0 - goos: - - aix - - linux - - freebsd - - netbsd - - windows - - darwin - goarch: - - 386 - - amd64 - - arm - - arm64 - - ppc64 - - ppc64le - - mips64 - - mips64le - goarm: - - 7 - -archives: - - - id: s2-binaries - name_template: "s2-{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" - format_overrides: - - goos: windows - format: zip - files: - - unpack/* - - s2/LICENSE - - s2/README.md -checksum: - name_template: 'checksums.txt' -snapshot: - name_template: "{{ .Tag }}-next" -changelog: - sort: asc - filters: - exclude: - - '^doc:' - - '^docs:' - - '^test:' - - '^tests:' - - '^Update\sREADME.md' - -nfpms: - - - file_name_template: "s2_package__{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" - vendor: Klaus Post - homepage: https://github.com/klauspost/compress - maintainer: Klaus Post - description: S2 Compression Tool - license: BSD 3-Clause - formats: - - deb - - rpm diff --git a/vendor/github.com/klauspost/compress/LICENSE b/vendor/github.com/klauspost/compress/LICENSE deleted file mode 100644 index 87d557477..000000000 --- a/vendor/github.com/klauspost/compress/LICENSE +++ /dev/null @@ -1,304 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. -Copyright (c) 2019 Klaus Post. 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 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. - ------------------- - -Files: gzhttp/* - - 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 2016-2017 The New York Times Company - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ------------------- - -Files: s2/cmd/internal/readahead/* - -The MIT License (MIT) - -Copyright (c) 2015 Klaus Post - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - ---------------------- -Files: snappy/* -Files: internal/snapref/* - -Copyright (c) 2011 The Snappy-Go Authors. 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 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. - ------------------ - -Files: s2/cmd/internal/filepathx/* - -Copyright 2016 The filepathx Authors - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/klauspost/compress/README.md b/vendor/github.com/klauspost/compress/README.md deleted file mode 100644 index 05c7359e4..000000000 --- a/vendor/github.com/klauspost/compress/README.md +++ /dev/null @@ -1,700 +0,0 @@ -# compress - -This package provides various compression algorithms. - -* [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and decompression in pure Go. -* [S2](https://github.com/klauspost/compress/tree/master/s2#s2-compression) is a high performance replacement for Snappy. -* Optimized [deflate](https://godoc.org/github.com/klauspost/compress/flate) packages which can be used as a dropin replacement for [gzip](https://godoc.org/github.com/klauspost/compress/gzip), [zip](https://godoc.org/github.com/klauspost/compress/zip) and [zlib](https://godoc.org/github.com/klauspost/compress/zlib). -* [snappy](https://github.com/klauspost/compress/tree/master/snappy) is a drop-in replacement for `github.com/golang/snappy` offering better compression and concurrent streams. -* [huff0](https://github.com/klauspost/compress/tree/master/huff0) and [FSE](https://github.com/klauspost/compress/tree/master/fse) implementations for raw entropy encoding. -* [gzhttp](https://github.com/klauspost/compress/tree/master/gzhttp) Provides client and server wrappers for handling gzipped requests efficiently. -* [pgzip](https://github.com/klauspost/pgzip) is a separate package that provides a very fast parallel gzip implementation. - -[![Go Reference](https://pkg.go.dev/badge/klauspost/compress.svg)](https://pkg.go.dev/github.com/klauspost/compress?tab=subdirectories) -[![Go](https://github.com/klauspost/compress/actions/workflows/go.yml/badge.svg)](https://github.com/klauspost/compress/actions/workflows/go.yml) -[![Sourcegraph Badge](https://sourcegraph.com/github.com/klauspost/compress/-/badge.svg)](https://sourcegraph.com/github.com/klauspost/compress?badge) - -# changelog - -* Feb 5th, 2024 - [1.17.6](https://github.com/klauspost/compress/releases/tag/v1.17.6) - * zstd: Fix incorrect repeat coding in best mode https://github.com/klauspost/compress/pull/923 - * s2: Fix DecodeConcurrent deadlock on errors https://github.com/klauspost/compress/pull/925 - -* Jan 26th, 2024 - [v1.17.5](https://github.com/klauspost/compress/releases/tag/v1.17.5) - * flate: Fix reset with dictionary on custom window encodes https://github.com/klauspost/compress/pull/912 - * zstd: Add Frame header encoding and stripping https://github.com/klauspost/compress/pull/908 - * zstd: Limit better/best default window to 8MB https://github.com/klauspost/compress/pull/913 - * zstd: Speed improvements by @greatroar in https://github.com/klauspost/compress/pull/896 https://github.com/klauspost/compress/pull/910 - * s2: Fix callbacks for skippable blocks and disallow 0xfe (Padding) by @Jille in https://github.com/klauspost/compress/pull/916 https://github.com/klauspost/compress/pull/917 -https://github.com/klauspost/compress/pull/919 https://github.com/klauspost/compress/pull/918 - -* Dec 1st, 2023 - [v1.17.4](https://github.com/klauspost/compress/releases/tag/v1.17.4) - * huff0: Speed up symbol counting by @greatroar in https://github.com/klauspost/compress/pull/887 - * huff0: Remove byteReader by @greatroar in https://github.com/klauspost/compress/pull/886 - * gzhttp: Allow overriding decompression on transport https://github.com/klauspost/compress/pull/892 - * gzhttp: Clamp compression level https://github.com/klauspost/compress/pull/890 - * gzip: Error out if reserved bits are set https://github.com/klauspost/compress/pull/891 - -* Nov 15th, 2023 - [v1.17.3](https://github.com/klauspost/compress/releases/tag/v1.17.3) - * fse: Fix max header size https://github.com/klauspost/compress/pull/881 - * zstd: Improve better/best compression https://github.com/klauspost/compress/pull/877 - * gzhttp: Fix missing content type on Close https://github.com/klauspost/compress/pull/883 - -* Oct 22nd, 2023 - [v1.17.2](https://github.com/klauspost/compress/releases/tag/v1.17.2) - * zstd: Fix rare *CORRUPTION* output in "best" mode. See https://github.com/klauspost/compress/pull/876 - -* Oct 14th, 2023 - [v1.17.1](https://github.com/klauspost/compress/releases/tag/v1.17.1) - * s2: Fix S2 "best" dictionary wrong encoding by @klauspost in https://github.com/klauspost/compress/pull/871 - * flate: Reduce allocations in decompressor and minor code improvements by @fakefloordiv in https://github.com/klauspost/compress/pull/869 - * s2: Fix EstimateBlockSize on 6&7 length input by @klauspost in https://github.com/klauspost/compress/pull/867 - -* Sept 19th, 2023 - [v1.17.0](https://github.com/klauspost/compress/releases/tag/v1.17.0) - * Add experimental dictionary builder https://github.com/klauspost/compress/pull/853 - * Add xerial snappy read/writer https://github.com/klauspost/compress/pull/838 - * flate: Add limited window compression https://github.com/klauspost/compress/pull/843 - * s2: Do 2 overlapping match checks https://github.com/klauspost/compress/pull/839 - * flate: Add amd64 assembly matchlen https://github.com/klauspost/compress/pull/837 - * gzip: Copy bufio.Reader on Reset by @thatguystone in https://github.com/klauspost/compress/pull/860 - -
- See changes to v1.16.x - - -* July 1st, 2023 - [v1.16.7](https://github.com/klauspost/compress/releases/tag/v1.16.7) - * zstd: Fix default level first dictionary encode https://github.com/klauspost/compress/pull/829 - * s2: add GetBufferCapacity() method by @GiedriusS in https://github.com/klauspost/compress/pull/832 - -* June 13, 2023 - [v1.16.6](https://github.com/klauspost/compress/releases/tag/v1.16.6) - * zstd: correctly ignore WithEncoderPadding(1) by @ianlancetaylor in https://github.com/klauspost/compress/pull/806 - * zstd: Add amd64 match length assembly https://github.com/klauspost/compress/pull/824 - * gzhttp: Handle informational headers by @rtribotte in https://github.com/klauspost/compress/pull/815 - * s2: Improve Better compression slightly https://github.com/klauspost/compress/pull/663 - -* Apr 16, 2023 - [v1.16.5](https://github.com/klauspost/compress/releases/tag/v1.16.5) - * zstd: readByte needs to use io.ReadFull by @jnoxon in https://github.com/klauspost/compress/pull/802 - * gzip: Fix WriterTo after initial read https://github.com/klauspost/compress/pull/804 - -* Apr 5, 2023 - [v1.16.4](https://github.com/klauspost/compress/releases/tag/v1.16.4) - * zstd: Improve zstd best efficiency by @greatroar and @klauspost in https://github.com/klauspost/compress/pull/784 - * zstd: Respect WithAllLitEntropyCompression https://github.com/klauspost/compress/pull/792 - * zstd: Fix amd64 not always detecting corrupt data https://github.com/klauspost/compress/pull/785 - * zstd: Various minor improvements by @greatroar in https://github.com/klauspost/compress/pull/788 https://github.com/klauspost/compress/pull/794 https://github.com/klauspost/compress/pull/795 - * s2: Fix huge block overflow https://github.com/klauspost/compress/pull/779 - * s2: Allow CustomEncoder fallback https://github.com/klauspost/compress/pull/780 - * gzhttp: Suppport ResponseWriter Unwrap() in gzhttp handler by @jgimenez in https://github.com/klauspost/compress/pull/799 - -* Mar 13, 2023 - [v1.16.1](https://github.com/klauspost/compress/releases/tag/v1.16.1) - * zstd: Speed up + improve best encoder by @greatroar in https://github.com/klauspost/compress/pull/776 - * gzhttp: Add optional [BREACH mitigation](https://github.com/klauspost/compress/tree/master/gzhttp#breach-mitigation). https://github.com/klauspost/compress/pull/762 https://github.com/klauspost/compress/pull/768 https://github.com/klauspost/compress/pull/769 https://github.com/klauspost/compress/pull/770 https://github.com/klauspost/compress/pull/767 - * s2: Add Intel LZ4s converter https://github.com/klauspost/compress/pull/766 - * zstd: Minor bug fixes https://github.com/klauspost/compress/pull/771 https://github.com/klauspost/compress/pull/772 https://github.com/klauspost/compress/pull/773 - * huff0: Speed up compress1xDo by @greatroar in https://github.com/klauspost/compress/pull/774 - -* Feb 26, 2023 - [v1.16.0](https://github.com/klauspost/compress/releases/tag/v1.16.0) - * s2: Add [Dictionary](https://github.com/klauspost/compress/tree/master/s2#dictionaries) support. https://github.com/klauspost/compress/pull/685 - * s2: Add Compression Size Estimate. https://github.com/klauspost/compress/pull/752 - * s2: Add support for custom stream encoder. https://github.com/klauspost/compress/pull/755 - * s2: Add LZ4 block converter. https://github.com/klauspost/compress/pull/748 - * s2: Support io.ReaderAt in ReadSeeker. https://github.com/klauspost/compress/pull/747 - * s2c/s2sx: Use concurrent decoding. https://github.com/klauspost/compress/pull/746 -
- -
- See changes to v1.15.x - -* Jan 21st, 2023 (v1.15.15) - * deflate: Improve level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/739 - * zstd: Add delta encoding support by @greatroar in https://github.com/klauspost/compress/pull/728 - * zstd: Various speed improvements by @greatroar https://github.com/klauspost/compress/pull/741 https://github.com/klauspost/compress/pull/734 https://github.com/klauspost/compress/pull/736 https://github.com/klauspost/compress/pull/744 https://github.com/klauspost/compress/pull/743 https://github.com/klauspost/compress/pull/745 - * gzhttp: Add SuffixETag() and DropETag() options to prevent ETag collisions on compressed responses by @willbicks in https://github.com/klauspost/compress/pull/740 - -* Jan 3rd, 2023 (v1.15.14) - - * flate: Improve speed in big stateless blocks https://github.com/klauspost/compress/pull/718 - * zstd: Minor speed tweaks by @greatroar in https://github.com/klauspost/compress/pull/716 https://github.com/klauspost/compress/pull/720 - * export NoGzipResponseWriter for custom ResponseWriter wrappers by @harshavardhana in https://github.com/klauspost/compress/pull/722 - * s2: Add example for indexing and existing stream https://github.com/klauspost/compress/pull/723 - -* Dec 11, 2022 (v1.15.13) - * zstd: Add [MaxEncodedSize](https://pkg.go.dev/github.com/klauspost/compress@v1.15.13/zstd#Encoder.MaxEncodedSize) to encoder https://github.com/klauspost/compress/pull/691 - * zstd: Various tweaks and improvements https://github.com/klauspost/compress/pull/693 https://github.com/klauspost/compress/pull/695 https://github.com/klauspost/compress/pull/696 https://github.com/klauspost/compress/pull/701 https://github.com/klauspost/compress/pull/702 https://github.com/klauspost/compress/pull/703 https://github.com/klauspost/compress/pull/704 https://github.com/klauspost/compress/pull/705 https://github.com/klauspost/compress/pull/706 https://github.com/klauspost/compress/pull/707 https://github.com/klauspost/compress/pull/708 - -* Oct 26, 2022 (v1.15.12) - - * zstd: Tweak decoder allocs. https://github.com/klauspost/compress/pull/680 - * gzhttp: Always delete `HeaderNoCompression` https://github.com/klauspost/compress/pull/683 - -* Sept 26, 2022 (v1.15.11) - - * flate: Improve level 1-3 compression https://github.com/klauspost/compress/pull/678 - * zstd: Improve "best" compression by @nightwolfz in https://github.com/klauspost/compress/pull/677 - * zstd: Fix+reduce decompression allocations https://github.com/klauspost/compress/pull/668 - * zstd: Fix non-effective noescape tag https://github.com/klauspost/compress/pull/667 - -* Sept 16, 2022 (v1.15.10) - - * zstd: Add [WithDecodeAllCapLimit](https://pkg.go.dev/github.com/klauspost/compress@v1.15.10/zstd#WithDecodeAllCapLimit) https://github.com/klauspost/compress/pull/649 - * Add Go 1.19 - deprecate Go 1.16 https://github.com/klauspost/compress/pull/651 - * flate: Improve level 5+6 compression https://github.com/klauspost/compress/pull/656 - * zstd: Improve "better" compresssion https://github.com/klauspost/compress/pull/657 - * s2: Improve "best" compression https://github.com/klauspost/compress/pull/658 - * s2: Improve "better" compression. https://github.com/klauspost/compress/pull/635 - * s2: Slightly faster non-assembly decompression https://github.com/klauspost/compress/pull/646 - * Use arrays for constant size copies https://github.com/klauspost/compress/pull/659 - -* July 21, 2022 (v1.15.9) - - * zstd: Fix decoder crash on amd64 (no BMI) on invalid input https://github.com/klauspost/compress/pull/645 - * zstd: Disable decoder extended memory copies (amd64) due to possible crashes https://github.com/klauspost/compress/pull/644 - * zstd: Allow single segments up to "max decoded size" by @klauspost in https://github.com/klauspost/compress/pull/643 - -* July 13, 2022 (v1.15.8) - - * gzip: fix stack exhaustion bug in Reader.Read https://github.com/klauspost/compress/pull/641 - * s2: Add Index header trim/restore https://github.com/klauspost/compress/pull/638 - * zstd: Optimize seqdeq amd64 asm by @greatroar in https://github.com/klauspost/compress/pull/636 - * zstd: Improve decoder memcopy https://github.com/klauspost/compress/pull/637 - * huff0: Pass a single bitReader pointer to asm by @greatroar in https://github.com/klauspost/compress/pull/634 - * zstd: Branchless getBits for amd64 w/o BMI2 by @greatroar in https://github.com/klauspost/compress/pull/640 - * gzhttp: Remove header before writing https://github.com/klauspost/compress/pull/639 - -* June 29, 2022 (v1.15.7) - - * s2: Fix absolute forward seeks https://github.com/klauspost/compress/pull/633 - * zip: Merge upstream https://github.com/klauspost/compress/pull/631 - * zip: Re-add zip64 fix https://github.com/klauspost/compress/pull/624 - * zstd: translate fseDecoder.buildDtable into asm by @WojciechMula in https://github.com/klauspost/compress/pull/598 - * flate: Faster histograms https://github.com/klauspost/compress/pull/620 - * deflate: Use compound hcode https://github.com/klauspost/compress/pull/622 - -* June 3, 2022 (v1.15.6) - * s2: Improve coding for long, close matches https://github.com/klauspost/compress/pull/613 - * s2c: Add Snappy/S2 stream recompression https://github.com/klauspost/compress/pull/611 - * zstd: Always use configured block size https://github.com/klauspost/compress/pull/605 - * zstd: Fix incorrect hash table placement for dict encoding in default https://github.com/klauspost/compress/pull/606 - * zstd: Apply default config to ZipDecompressor without options https://github.com/klauspost/compress/pull/608 - * gzhttp: Exclude more common archive formats https://github.com/klauspost/compress/pull/612 - * s2: Add ReaderIgnoreCRC https://github.com/klauspost/compress/pull/609 - * s2: Remove sanity load on index creation https://github.com/klauspost/compress/pull/607 - * snappy: Use dedicated function for scoring https://github.com/klauspost/compress/pull/614 - * s2c+s2d: Use official snappy framed extension https://github.com/klauspost/compress/pull/610 - -* May 25, 2022 (v1.15.5) - * s2: Add concurrent stream decompression https://github.com/klauspost/compress/pull/602 - * s2: Fix final emit oob read crash on amd64 https://github.com/klauspost/compress/pull/601 - * huff0: asm implementation of Decompress1X by @WojciechMula https://github.com/klauspost/compress/pull/596 - * zstd: Use 1 less goroutine for stream decoding https://github.com/klauspost/compress/pull/588 - * zstd: Copy literal in 16 byte blocks when possible https://github.com/klauspost/compress/pull/592 - * zstd: Speed up when WithDecoderLowmem(false) https://github.com/klauspost/compress/pull/599 - * zstd: faster next state update in BMI2 version of decode by @WojciechMula in https://github.com/klauspost/compress/pull/593 - * huff0: Do not check max size when reading table. https://github.com/klauspost/compress/pull/586 - * flate: Inplace hashing for level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/590 - - -* May 11, 2022 (v1.15.4) - * huff0: decompress directly into output by @WojciechMula in [#577](https://github.com/klauspost/compress/pull/577) - * inflate: Keep dict on stack [#581](https://github.com/klauspost/compress/pull/581) - * zstd: Faster decoding memcopy in asm [#583](https://github.com/klauspost/compress/pull/583) - * zstd: Fix ignored crc [#580](https://github.com/klauspost/compress/pull/580) - -* May 5, 2022 (v1.15.3) - * zstd: Allow to ignore checksum checking by @WojciechMula [#572](https://github.com/klauspost/compress/pull/572) - * s2: Fix incorrect seek for io.SeekEnd in [#575](https://github.com/klauspost/compress/pull/575) - -* Apr 26, 2022 (v1.15.2) - * zstd: Add x86-64 assembly for decompression on streams and blocks. Contributed by [@WojciechMula](https://github.com/WojciechMula). Typically 2x faster. [#528](https://github.com/klauspost/compress/pull/528) [#531](https://github.com/klauspost/compress/pull/531) [#545](https://github.com/klauspost/compress/pull/545) [#537](https://github.com/klauspost/compress/pull/537) - * zstd: Add options to ZipDecompressor and fixes [#539](https://github.com/klauspost/compress/pull/539) - * s2: Use sorted search for index [#555](https://github.com/klauspost/compress/pull/555) - * Minimum version is Go 1.16, added CI test on 1.18. - -* Mar 11, 2022 (v1.15.1) - * huff0: Add x86 assembly of Decode4X by @WojciechMula in [#512](https://github.com/klauspost/compress/pull/512) - * zstd: Reuse zip decoders in [#514](https://github.com/klauspost/compress/pull/514) - * zstd: Detect extra block data and report as corrupted in [#520](https://github.com/klauspost/compress/pull/520) - * zstd: Handle zero sized frame content size stricter in [#521](https://github.com/klauspost/compress/pull/521) - * zstd: Add stricter block size checks in [#523](https://github.com/klauspost/compress/pull/523) - -* Mar 3, 2022 (v1.15.0) - * zstd: Refactor decoder by @klauspost in [#498](https://github.com/klauspost/compress/pull/498) - * zstd: Add stream encoding without goroutines by @klauspost in [#505](https://github.com/klauspost/compress/pull/505) - * huff0: Prevent single blocks exceeding 16 bits by @klauspost in[#507](https://github.com/klauspost/compress/pull/507) - * flate: Inline literal emission by @klauspost in [#509](https://github.com/klauspost/compress/pull/509) - * gzhttp: Add zstd to transport by @klauspost in [#400](https://github.com/klauspost/compress/pull/400) - * gzhttp: Make content-type optional by @klauspost in [#510](https://github.com/klauspost/compress/pull/510) - -Both compression and decompression now supports "synchronous" stream operations. This means that whenever "concurrency" is set to 1, they will operate without spawning goroutines. - -Stream decompression is now faster on asynchronous, since the goroutine allocation much more effectively splits the workload. On typical streams this will typically use 2 cores fully for decompression. When a stream has finished decoding no goroutines will be left over, so decoders can now safely be pooled and still be garbage collected. - -While the release has been extensively tested, it is recommended to testing when upgrading. - -
- -
- See changes to v1.14.x - -* Feb 22, 2022 (v1.14.4) - * flate: Fix rare huffman only (-2) corruption. [#503](https://github.com/klauspost/compress/pull/503) - * zip: Update deprecated CreateHeaderRaw to correctly call CreateRaw by @saracen in [#502](https://github.com/klauspost/compress/pull/502) - * zip: don't read data descriptor early by @saracen in [#501](https://github.com/klauspost/compress/pull/501) #501 - * huff0: Use static decompression buffer up to 30% faster by @klauspost in [#499](https://github.com/klauspost/compress/pull/499) [#500](https://github.com/klauspost/compress/pull/500) - -* Feb 17, 2022 (v1.14.3) - * flate: Improve fastest levels compression speed ~10% more throughput. [#482](https://github.com/klauspost/compress/pull/482) [#489](https://github.com/klauspost/compress/pull/489) [#490](https://github.com/klauspost/compress/pull/490) [#491](https://github.com/klauspost/compress/pull/491) [#494](https://github.com/klauspost/compress/pull/494) [#478](https://github.com/klauspost/compress/pull/478) - * flate: Faster decompression speed, ~5-10%. [#483](https://github.com/klauspost/compress/pull/483) - * s2: Faster compression with Go v1.18 and amd64 microarch level 3+. [#484](https://github.com/klauspost/compress/pull/484) [#486](https://github.com/klauspost/compress/pull/486) - -* Jan 25, 2022 (v1.14.2) - * zstd: improve header decoder by @dsnet [#476](https://github.com/klauspost/compress/pull/476) - * zstd: Add bigger default blocks [#469](https://github.com/klauspost/compress/pull/469) - * zstd: Remove unused decompression buffer [#470](https://github.com/klauspost/compress/pull/470) - * zstd: Fix logically dead code by @ningmingxiao [#472](https://github.com/klauspost/compress/pull/472) - * flate: Improve level 7-9 [#471](https://github.com/klauspost/compress/pull/471) [#473](https://github.com/klauspost/compress/pull/473) - * zstd: Add noasm tag for xxhash [#475](https://github.com/klauspost/compress/pull/475) - -* Jan 11, 2022 (v1.14.1) - * s2: Add stream index in [#462](https://github.com/klauspost/compress/pull/462) - * flate: Speed and efficiency improvements in [#439](https://github.com/klauspost/compress/pull/439) [#461](https://github.com/klauspost/compress/pull/461) [#455](https://github.com/klauspost/compress/pull/455) [#452](https://github.com/klauspost/compress/pull/452) [#458](https://github.com/klauspost/compress/pull/458) - * zstd: Performance improvement in [#420]( https://github.com/klauspost/compress/pull/420) [#456](https://github.com/klauspost/compress/pull/456) [#437](https://github.com/klauspost/compress/pull/437) [#467](https://github.com/klauspost/compress/pull/467) [#468](https://github.com/klauspost/compress/pull/468) - * zstd: add arm64 xxhash assembly in [#464](https://github.com/klauspost/compress/pull/464) - * Add garbled for binaries for s2 in [#445](https://github.com/klauspost/compress/pull/445) -
- -
- See changes to v1.13.x - -* Aug 30, 2021 (v1.13.5) - * gz/zlib/flate: Alias stdlib errors [#425](https://github.com/klauspost/compress/pull/425) - * s2: Add block support to commandline tools [#413](https://github.com/klauspost/compress/pull/413) - * zstd: pooledZipWriter should return Writers to the same pool [#426](https://github.com/klauspost/compress/pull/426) - * Removed golang/snappy as external dependency for tests [#421](https://github.com/klauspost/compress/pull/421) - -* Aug 12, 2021 (v1.13.4) - * Add [snappy replacement package](https://github.com/klauspost/compress/tree/master/snappy). - * zstd: Fix incorrect encoding in "best" mode [#415](https://github.com/klauspost/compress/pull/415) - -* Aug 3, 2021 (v1.13.3) - * zstd: Improve Best compression [#404](https://github.com/klauspost/compress/pull/404) - * zstd: Fix WriteTo error forwarding [#411](https://github.com/klauspost/compress/pull/411) - * gzhttp: Return http.HandlerFunc instead of http.Handler. Unlikely breaking change. [#406](https://github.com/klauspost/compress/pull/406) - * s2sx: Fix max size error [#399](https://github.com/klauspost/compress/pull/399) - * zstd: Add optional stream content size on reset [#401](https://github.com/klauspost/compress/pull/401) - * zstd: use SpeedBestCompression for level >= 10 [#410](https://github.com/klauspost/compress/pull/410) - -* Jun 14, 2021 (v1.13.1) - * s2: Add full Snappy output support [#396](https://github.com/klauspost/compress/pull/396) - * zstd: Add configurable [Decoder window](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithDecoderMaxWindow) size [#394](https://github.com/klauspost/compress/pull/394) - * gzhttp: Add header to skip compression [#389](https://github.com/klauspost/compress/pull/389) - * s2: Improve speed with bigger output margin [#395](https://github.com/klauspost/compress/pull/395) - -* Jun 3, 2021 (v1.13.0) - * Added [gzhttp](https://github.com/klauspost/compress/tree/master/gzhttp#gzip-handler) which allows wrapping HTTP servers and clients with GZIP compressors. - * zstd: Detect short invalid signatures [#382](https://github.com/klauspost/compress/pull/382) - * zstd: Spawn decoder goroutine only if needed. [#380](https://github.com/klauspost/compress/pull/380) -
- - -
- See changes to v1.12.x - -* May 25, 2021 (v1.12.3) - * deflate: Better/faster Huffman encoding [#374](https://github.com/klauspost/compress/pull/374) - * deflate: Allocate less for history. [#375](https://github.com/klauspost/compress/pull/375) - * zstd: Forward read errors [#373](https://github.com/klauspost/compress/pull/373) - -* Apr 27, 2021 (v1.12.2) - * zstd: Improve better/best compression [#360](https://github.com/klauspost/compress/pull/360) [#364](https://github.com/klauspost/compress/pull/364) [#365](https://github.com/klauspost/compress/pull/365) - * zstd: Add helpers to compress/decompress zstd inside zip files [#363](https://github.com/klauspost/compress/pull/363) - * deflate: Improve level 5+6 compression [#367](https://github.com/klauspost/compress/pull/367) - * s2: Improve better/best compression [#358](https://github.com/klauspost/compress/pull/358) [#359](https://github.com/klauspost/compress/pull/358) - * s2: Load after checking src limit on amd64. [#362](https://github.com/klauspost/compress/pull/362) - * s2sx: Limit max executable size [#368](https://github.com/klauspost/compress/pull/368) - -* Apr 14, 2021 (v1.12.1) - * snappy package removed. Upstream added as dependency. - * s2: Better compression in "best" mode [#353](https://github.com/klauspost/compress/pull/353) - * s2sx: Add stdin input and detect pre-compressed from signature [#352](https://github.com/klauspost/compress/pull/352) - * s2c/s2d: Add http as possible input [#348](https://github.com/klauspost/compress/pull/348) - * s2c/s2d/s2sx: Always truncate when writing files [#352](https://github.com/klauspost/compress/pull/352) - * zstd: Reduce memory usage further when using [WithLowerEncoderMem](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithLowerEncoderMem) [#346](https://github.com/klauspost/compress/pull/346) - * s2: Fix potential problem with amd64 assembly and profilers [#349](https://github.com/klauspost/compress/pull/349) -
- -
- See changes to v1.11.x - -* Mar 26, 2021 (v1.11.13) - * zstd: Big speedup on small dictionary encodes [#344](https://github.com/klauspost/compress/pull/344) [#345](https://github.com/klauspost/compress/pull/345) - * zstd: Add [WithLowerEncoderMem](https://pkg.go.dev/github.com/klauspost/compress/zstd#WithLowerEncoderMem) encoder option [#336](https://github.com/klauspost/compress/pull/336) - * deflate: Improve entropy compression [#338](https://github.com/klauspost/compress/pull/338) - * s2: Clean up and minor performance improvement in best [#341](https://github.com/klauspost/compress/pull/341) - -* Mar 5, 2021 (v1.11.12) - * s2: Add `s2sx` binary that creates [self extracting archives](https://github.com/klauspost/compress/tree/master/s2#s2sx-self-extracting-archives). - * s2: Speed up decompression on non-assembly platforms [#328](https://github.com/klauspost/compress/pull/328) - -* Mar 1, 2021 (v1.11.9) - * s2: Add ARM64 decompression assembly. Around 2x output speed. [#324](https://github.com/klauspost/compress/pull/324) - * s2: Improve "better" speed and efficiency. [#325](https://github.com/klauspost/compress/pull/325) - * s2: Fix binaries. - -* Feb 25, 2021 (v1.11.8) - * s2: Fixed occational out-of-bounds write on amd64. Upgrade recommended. - * s2: Add AMD64 assembly for better mode. 25-50% faster. [#315](https://github.com/klauspost/compress/pull/315) - * s2: Less upfront decoder allocation. [#322](https://github.com/klauspost/compress/pull/322) - * zstd: Faster "compression" of incompressible data. [#314](https://github.com/klauspost/compress/pull/314) - * zip: Fix zip64 headers. [#313](https://github.com/klauspost/compress/pull/313) - -* Jan 14, 2021 (v1.11.7) - * Use Bytes() interface to get bytes across packages. [#309](https://github.com/klauspost/compress/pull/309) - * s2: Add 'best' compression option. [#310](https://github.com/klauspost/compress/pull/310) - * s2: Add ReaderMaxBlockSize, changes `s2.NewReader` signature to include varargs. [#311](https://github.com/klauspost/compress/pull/311) - * s2: Fix crash on small better buffers. [#308](https://github.com/klauspost/compress/pull/308) - * s2: Clean up decoder. [#312](https://github.com/klauspost/compress/pull/312) - -* Jan 7, 2021 (v1.11.6) - * zstd: Make decoder allocations smaller [#306](https://github.com/klauspost/compress/pull/306) - * zstd: Free Decoder resources when Reset is called with a nil io.Reader [#305](https://github.com/klauspost/compress/pull/305) - -* Dec 20, 2020 (v1.11.4) - * zstd: Add Best compression mode [#304](https://github.com/klauspost/compress/pull/304) - * Add header decoder [#299](https://github.com/klauspost/compress/pull/299) - * s2: Add uncompressed stream option [#297](https://github.com/klauspost/compress/pull/297) - * Simplify/speed up small blocks with known max size. [#300](https://github.com/klauspost/compress/pull/300) - * zstd: Always reset literal dict encoder [#303](https://github.com/klauspost/compress/pull/303) - -* Nov 15, 2020 (v1.11.3) - * inflate: 10-15% faster decompression [#293](https://github.com/klauspost/compress/pull/293) - * zstd: Tweak DecodeAll default allocation [#295](https://github.com/klauspost/compress/pull/295) - -* Oct 11, 2020 (v1.11.2) - * s2: Fix out of bounds read in "better" block compression [#291](https://github.com/klauspost/compress/pull/291) - -* Oct 1, 2020 (v1.11.1) - * zstd: Set allLitEntropy true in default configuration [#286](https://github.com/klauspost/compress/pull/286) - -* Sept 8, 2020 (v1.11.0) - * zstd: Add experimental compression [dictionaries](https://github.com/klauspost/compress/tree/master/zstd#dictionaries) [#281](https://github.com/klauspost/compress/pull/281) - * zstd: Fix mixed Write and ReadFrom calls [#282](https://github.com/klauspost/compress/pull/282) - * inflate/gz: Limit variable shifts, ~5% faster decompression [#274](https://github.com/klauspost/compress/pull/274) -
- -
- See changes to v1.10.x - -* July 8, 2020 (v1.10.11) - * zstd: Fix extra block when compressing with ReadFrom. [#278](https://github.com/klauspost/compress/pull/278) - * huff0: Also populate compression table when reading decoding table. [#275](https://github.com/klauspost/compress/pull/275) - -* June 23, 2020 (v1.10.10) - * zstd: Skip entropy compression in fastest mode when no matches. [#270](https://github.com/klauspost/compress/pull/270) - -* June 16, 2020 (v1.10.9): - * zstd: API change for specifying dictionaries. See [#268](https://github.com/klauspost/compress/pull/268) - * zip: update CreateHeaderRaw to handle zip64 fields. [#266](https://github.com/klauspost/compress/pull/266) - * Fuzzit tests removed. The service has been purchased and is no longer available. - -* June 5, 2020 (v1.10.8): - * 1.15x faster zstd block decompression. [#265](https://github.com/klauspost/compress/pull/265) - -* June 1, 2020 (v1.10.7): - * Added zstd decompression [dictionary support](https://github.com/klauspost/compress/tree/master/zstd#dictionaries) - * Increase zstd decompression speed up to 1.19x. [#259](https://github.com/klauspost/compress/pull/259) - * Remove internal reset call in zstd compression and reduce allocations. [#263](https://github.com/klauspost/compress/pull/263) - -* May 21, 2020: (v1.10.6) - * zstd: Reduce allocations while decoding. [#258](https://github.com/klauspost/compress/pull/258), [#252](https://github.com/klauspost/compress/pull/252) - * zstd: Stricter decompression checks. - -* April 12, 2020: (v1.10.5) - * s2-commands: Flush output when receiving SIGINT. [#239](https://github.com/klauspost/compress/pull/239) - -* Apr 8, 2020: (v1.10.4) - * zstd: Minor/special case optimizations. [#251](https://github.com/klauspost/compress/pull/251), [#250](https://github.com/klauspost/compress/pull/250), [#249](https://github.com/klauspost/compress/pull/249), [#247](https://github.com/klauspost/compress/pull/247) -* Mar 11, 2020: (v1.10.3) - * s2: Use S2 encoder in pure Go mode for Snappy output as well. [#245](https://github.com/klauspost/compress/pull/245) - * s2: Fix pure Go block encoder. [#244](https://github.com/klauspost/compress/pull/244) - * zstd: Added "better compression" mode. [#240](https://github.com/klauspost/compress/pull/240) - * zstd: Improve speed of fastest compression mode by 5-10% [#241](https://github.com/klauspost/compress/pull/241) - * zstd: Skip creating encoders when not needed. [#238](https://github.com/klauspost/compress/pull/238) - -* Feb 27, 2020: (v1.10.2) - * Close to 50% speedup in inflate (gzip/zip decompression). [#236](https://github.com/klauspost/compress/pull/236) [#234](https://github.com/klauspost/compress/pull/234) [#232](https://github.com/klauspost/compress/pull/232) - * Reduce deflate level 1-6 memory usage up to 59%. [#227](https://github.com/klauspost/compress/pull/227) - -* Feb 18, 2020: (v1.10.1) - * Fix zstd crash when resetting multiple times without sending data. [#226](https://github.com/klauspost/compress/pull/226) - * deflate: Fix dictionary use on level 1-6. [#224](https://github.com/klauspost/compress/pull/224) - * Remove deflate writer reference when closing. [#224](https://github.com/klauspost/compress/pull/224) - -* Feb 4, 2020: (v1.10.0) - * Add optional dictionary to [stateless deflate](https://pkg.go.dev/github.com/klauspost/compress/flate?tab=doc#StatelessDeflate). Breaking change, send `nil` for previous behaviour. [#216](https://github.com/klauspost/compress/pull/216) - * Fix buffer overflow on repeated small block deflate. [#218](https://github.com/klauspost/compress/pull/218) - * Allow copying content from an existing ZIP file without decompressing+compressing. [#214](https://github.com/klauspost/compress/pull/214) - * Added [S2](https://github.com/klauspost/compress/tree/master/s2#s2-compression) AMD64 assembler and various optimizations. Stream speed >10GB/s. [#186](https://github.com/klauspost/compress/pull/186) - -
- -
- See changes prior to v1.10.0 - -* Jan 20,2020 (v1.9.8) Optimize gzip/deflate with better size estimates and faster table generation. [#207](https://github.com/klauspost/compress/pull/207) by [luyu6056](https://github.com/luyu6056), [#206](https://github.com/klauspost/compress/pull/206). -* Jan 11, 2020: S2 Encode/Decode will use provided buffer if capacity is big enough. [#204](https://github.com/klauspost/compress/pull/204) -* Jan 5, 2020: (v1.9.7) Fix another zstd regression in v1.9.5 - v1.9.6 removed. -* Jan 4, 2020: (v1.9.6) Regression in v1.9.5 fixed causing corrupt zstd encodes in rare cases. -* Jan 4, 2020: Faster IO in [s2c + s2d commandline tools](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) compression/decompression. [#192](https://github.com/klauspost/compress/pull/192) -* Dec 29, 2019: Removed v1.9.5 since fuzz tests showed a compatibility problem with the reference zstandard decoder. -* Dec 29, 2019: (v1.9.5) zstd: 10-20% faster block compression. [#199](https://github.com/klauspost/compress/pull/199) -* Dec 29, 2019: [zip](https://godoc.org/github.com/klauspost/compress/zip) package updated with latest Go features -* Dec 29, 2019: zstd: Single segment flag condintions tweaked. [#197](https://github.com/klauspost/compress/pull/197) -* Dec 18, 2019: s2: Faster compression when ReadFrom is used. [#198](https://github.com/klauspost/compress/pull/198) -* Dec 10, 2019: s2: Fix repeat length output when just above at 16MB limit. -* Dec 10, 2019: zstd: Add function to get decoder as io.ReadCloser. [#191](https://github.com/klauspost/compress/pull/191) -* Dec 3, 2019: (v1.9.4) S2: limit max repeat length. [#188](https://github.com/klauspost/compress/pull/188) -* Dec 3, 2019: Add [WithNoEntropyCompression](https://godoc.org/github.com/klauspost/compress/zstd#WithNoEntropyCompression) to zstd [#187](https://github.com/klauspost/compress/pull/187) -* Dec 3, 2019: Reduce memory use for tests. Check for leaked goroutines. -* Nov 28, 2019 (v1.9.3) Less allocations in stateless deflate. -* Nov 28, 2019: 5-20% Faster huff0 decode. Impacts zstd as well. [#184](https://github.com/klauspost/compress/pull/184) -* Nov 12, 2019 (v1.9.2) Added [Stateless Compression](#stateless-compression) for gzip/deflate. -* Nov 12, 2019: Fixed zstd decompression of large single blocks. [#180](https://github.com/klauspost/compress/pull/180) -* Nov 11, 2019: Set default [s2c](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) block size to 4MB. -* Nov 11, 2019: Reduce inflate memory use by 1KB. -* Nov 10, 2019: Less allocations in deflate bit writer. -* Nov 10, 2019: Fix inconsistent error returned by zstd decoder. -* Oct 28, 2019 (v1.9.1) ztsd: Fix crash when compressing blocks. [#174](https://github.com/klauspost/compress/pull/174) -* Oct 24, 2019 (v1.9.0) zstd: Fix rare data corruption [#173](https://github.com/klauspost/compress/pull/173) -* Oct 24, 2019 zstd: Fix huff0 out of buffer write [#171](https://github.com/klauspost/compress/pull/171) and always return errors [#172](https://github.com/klauspost/compress/pull/172) -* Oct 10, 2019: Big deflate rewrite, 30-40% faster with better compression [#105](https://github.com/klauspost/compress/pull/105) - -
- -
- See changes prior to v1.9.0 - -* Oct 10, 2019: (v1.8.6) zstd: Allow partial reads to get flushed data. [#169](https://github.com/klauspost/compress/pull/169) -* Oct 3, 2019: Fix inconsistent results on broken zstd streams. -* Sep 25, 2019: Added `-rm` (remove source files) and `-q` (no output except errors) to `s2c` and `s2d` [commands](https://github.com/klauspost/compress/tree/master/s2#commandline-tools) -* Sep 16, 2019: (v1.8.4) Add `s2c` and `s2d` [commandline tools](https://github.com/klauspost/compress/tree/master/s2#commandline-tools). -* Sep 10, 2019: (v1.8.3) Fix s2 decoder [Skip](https://godoc.org/github.com/klauspost/compress/s2#Reader.Skip). -* Sep 7, 2019: zstd: Added [WithWindowSize](https://godoc.org/github.com/klauspost/compress/zstd#WithWindowSize), contributed by [ianwilkes](https://github.com/ianwilkes). -* Sep 5, 2019: (v1.8.2) Add [WithZeroFrames](https://godoc.org/github.com/klauspost/compress/zstd#WithZeroFrames) which adds full zero payload block encoding option. -* Sep 5, 2019: Lazy initialization of zstandard predefined en/decoder tables. -* Aug 26, 2019: (v1.8.1) S2: 1-2% compression increase in "better" compression mode. -* Aug 26, 2019: zstd: Check maximum size of Huffman 1X compressed literals while decoding. -* Aug 24, 2019: (v1.8.0) Added [S2 compression](https://github.com/klauspost/compress/tree/master/s2#s2-compression), a high performance replacement for Snappy. -* Aug 21, 2019: (v1.7.6) Fixed minor issues found by fuzzer. One could lead to zstd not decompressing. -* Aug 18, 2019: Add [fuzzit](https://fuzzit.dev/) continuous fuzzing. -* Aug 14, 2019: zstd: Skip incompressible data 2x faster. [#147](https://github.com/klauspost/compress/pull/147) -* Aug 4, 2019 (v1.7.5): Better literal compression. [#146](https://github.com/klauspost/compress/pull/146) -* Aug 4, 2019: Faster zstd compression. [#143](https://github.com/klauspost/compress/pull/143) [#144](https://github.com/klauspost/compress/pull/144) -* Aug 4, 2019: Faster zstd decompression. [#145](https://github.com/klauspost/compress/pull/145) [#143](https://github.com/klauspost/compress/pull/143) [#142](https://github.com/klauspost/compress/pull/142) -* July 15, 2019 (v1.7.4): Fix double EOF block in rare cases on zstd encoder. -* July 15, 2019 (v1.7.3): Minor speedup/compression increase in default zstd encoder. -* July 14, 2019: zstd decoder: Fix decompression error on multiple uses with mixed content. -* July 7, 2019 (v1.7.2): Snappy update, zstd decoder potential race fix. -* June 17, 2019: zstd decompression bugfix. -* June 17, 2019: fix 32 bit builds. -* June 17, 2019: Easier use in modules (less dependencies). -* June 9, 2019: New stronger "default" [zstd](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression mode. Matches zstd default compression ratio. -* June 5, 2019: 20-40% throughput in [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and better compression. -* June 5, 2019: deflate/gzip compression: Reduce memory usage of lower compression levels. -* June 2, 2019: Added [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression! -* May 25, 2019: deflate/gzip: 10% faster bit writer, mostly visible in lower levels. -* Apr 22, 2019: [zstd](https://github.com/klauspost/compress/tree/master/zstd#zstd) decompression added. -* Aug 1, 2018: Added [huff0 README](https://github.com/klauspost/compress/tree/master/huff0#huff0-entropy-compression). -* Jul 8, 2018: Added [Performance Update 2018](#performance-update-2018) below. -* Jun 23, 2018: Merged [Go 1.11 inflate optimizations](https://go-review.googlesource.com/c/go/+/102235). Go 1.9 is now required. Backwards compatible version tagged with [v1.3.0](https://github.com/klauspost/compress/releases/tag/v1.3.0). -* Apr 2, 2018: Added [huff0](https://godoc.org/github.com/klauspost/compress/huff0) en/decoder. Experimental for now, API may change. -* Mar 4, 2018: Added [FSE Entropy](https://godoc.org/github.com/klauspost/compress/fse) en/decoder. Experimental for now, API may change. -* Nov 3, 2017: Add compression [Estimate](https://godoc.org/github.com/klauspost/compress#Estimate) function. -* May 28, 2017: Reduce allocations when resetting decoder. -* Apr 02, 2017: Change back to official crc32, since changes were merged in Go 1.7. -* Jan 14, 2017: Reduce stack pressure due to array copies. See [Issue #18625](https://github.com/golang/go/issues/18625). -* Oct 25, 2016: Level 2-4 have been rewritten and now offers significantly better performance than before. -* Oct 20, 2016: Port zlib changes from Go 1.7 to fix zlib writer issue. Please update. -* Oct 16, 2016: Go 1.7 changes merged. Apples to apples this package is a few percent faster, but has a significantly better balance between speed and compression per level. -* Mar 24, 2016: Always attempt Huffman encoding on level 4-7. This improves base 64 encoded data compression. -* Mar 24, 2016: Small speedup for level 1-3. -* Feb 19, 2016: Faster bit writer, level -2 is 15% faster, level 1 is 4% faster. -* Feb 19, 2016: Handle small payloads faster in level 1-3. -* Feb 19, 2016: Added faster level 2 + 3 compression modes. -* Feb 19, 2016: [Rebalanced compression levels](https://blog.klauspost.com/rebalancing-deflate-compression-levels/), so there is a more even progresssion in terms of compression. New default level is 5. -* Feb 14, 2016: Snappy: Merge upstream changes. -* Feb 14, 2016: Snappy: Fix aggressive skipping. -* Feb 14, 2016: Snappy: Update benchmark. -* Feb 13, 2016: Deflate: Fixed assembler problem that could lead to sub-optimal compression. -* Feb 12, 2016: Snappy: Added AMD64 SSE 4.2 optimizations to matching, which makes easy to compress material run faster. Typical speedup is around 25%. -* Feb 9, 2016: Added Snappy package fork. This version is 5-7% faster, much more on hard to compress content. -* Jan 30, 2016: Optimize level 1 to 3 by not considering static dictionary or storing uncompressed. ~4-5% speedup. -* Jan 16, 2016: Optimization on deflate level 1,2,3 compression. -* Jan 8 2016: Merge [CL 18317](https://go-review.googlesource.com/#/c/18317): fix reading, writing of zip64 archives. -* Dec 8 2015: Make level 1 and -2 deterministic even if write size differs. -* Dec 8 2015: Split encoding functions, so hashing and matching can potentially be inlined. 1-3% faster on AMD64. 5% faster on other platforms. -* Dec 8 2015: Fixed rare [one byte out-of bounds read](https://github.com/klauspost/compress/issues/20). Please update! -* Nov 23 2015: Optimization on token writer. ~2-4% faster. Contributed by [@dsnet](https://github.com/dsnet). -* Nov 20 2015: Small optimization to bit writer on 64 bit systems. -* Nov 17 2015: Fixed out-of-bound errors if the underlying Writer returned an error. See [#15](https://github.com/klauspost/compress/issues/15). -* Nov 12 2015: Added [io.WriterTo](https://golang.org/pkg/io/#WriterTo) support to gzip/inflate. -* Nov 11 2015: Merged [CL 16669](https://go-review.googlesource.com/#/c/16669/4): archive/zip: enable overriding (de)compressors per file -* Oct 15 2015: Added skipping on uncompressible data. Random data speed up >5x. - -
- -# deflate usage - -The packages are drop-in replacements for standard libraries. Simply replace the import path to use them: - -| old import | new import | Documentation -|--------------------|-----------------------------------------|--------------------| -| `compress/gzip` | `github.com/klauspost/compress/gzip` | [gzip](https://pkg.go.dev/github.com/klauspost/compress/gzip?tab=doc) -| `compress/zlib` | `github.com/klauspost/compress/zlib` | [zlib](https://pkg.go.dev/github.com/klauspost/compress/zlib?tab=doc) -| `archive/zip` | `github.com/klauspost/compress/zip` | [zip](https://pkg.go.dev/github.com/klauspost/compress/zip?tab=doc) -| `compress/flate` | `github.com/klauspost/compress/flate` | [flate](https://pkg.go.dev/github.com/klauspost/compress/flate?tab=doc) - -* Optimized [deflate](https://godoc.org/github.com/klauspost/compress/flate) packages which can be used as a dropin replacement for [gzip](https://godoc.org/github.com/klauspost/compress/gzip), [zip](https://godoc.org/github.com/klauspost/compress/zip) and [zlib](https://godoc.org/github.com/klauspost/compress/zlib). - -You may also be interested in [pgzip](https://github.com/klauspost/pgzip), which is a drop in replacement for gzip, which support multithreaded compression on big files and the optimized [crc32](https://github.com/klauspost/crc32) package used by these packages. - -The packages contains the same as the standard library, so you can use the godoc for that: [gzip](http://golang.org/pkg/compress/gzip/), [zip](http://golang.org/pkg/archive/zip/), [zlib](http://golang.org/pkg/compress/zlib/), [flate](http://golang.org/pkg/compress/flate/). - -Currently there is only minor speedup on decompression (mostly CRC32 calculation). - -Memory usage is typically 1MB for a Writer. stdlib is in the same range. -If you expect to have a lot of concurrently allocated Writers consider using -the stateless compress described below. - -For compression performance, see: [this spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing). - -To disable all assembly add `-tags=noasm`. This works across all packages. - -# Stateless compression - -This package offers stateless compression as a special option for gzip/deflate. -It will do compression but without maintaining any state between Write calls. - -This means there will be no memory kept between Write calls, but compression and speed will be suboptimal. - -This is only relevant in cases where you expect to run many thousands of compressors concurrently, -but with very little activity. This is *not* intended for regular web servers serving individual requests. - -Because of this, the size of actual Write calls will affect output size. - -In gzip, specify level `-3` / `gzip.StatelessCompression` to enable. - -For direct deflate use, NewStatelessWriter and StatelessDeflate are available. See [documentation](https://godoc.org/github.com/klauspost/compress/flate#NewStatelessWriter) - -A `bufio.Writer` can of course be used to control write sizes. For example, to use a 4KB buffer: - -```go - // replace 'ioutil.Discard' with your output. - gzw, err := gzip.NewWriterLevel(ioutil.Discard, gzip.StatelessCompression) - if err != nil { - return err - } - defer gzw.Close() - - w := bufio.NewWriterSize(gzw, 4096) - defer w.Flush() - - // Write to 'w' -``` - -This will only use up to 4KB in memory when the writer is idle. - -Compression is almost always worse than the fastest compression level -and each write will allocate (a little) memory. - -# Performance Update 2018 - -It has been a while since we have been looking at the speed of this package compared to the standard library, so I thought I would re-do my tests and give some overall recommendations based on the current state. All benchmarks have been performed with Go 1.10 on my Desktop Intel(R) Core(TM) i7-2600 CPU @3.40GHz. Since I last ran the tests, I have gotten more RAM, which means tests with big files are no longer limited by my SSD. - -The raw results are in my [updated spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing). Due to cgo changes and upstream updates i could not get the cgo version of gzip to compile. Instead I included the [zstd](https://github.com/datadog/zstd) cgo implementation. If I get cgo gzip to work again, I might replace the results in the sheet. - -The columns to take note of are: *MB/s* - the throughput. *Reduction* - the data size reduction in percent of the original. *Rel Speed* relative speed compared to the standard library at the same level. *Smaller* - how many percent smaller is the compressed output compared to stdlib. Negative means the output was bigger. *Loss* means the loss (or gain) in compression as a percentage difference of the input. - -The `gzstd` (standard library gzip) and `gzkp` (this package gzip) only uses one CPU core. [`pgzip`](https://github.com/klauspost/pgzip), [`bgzf`](https://github.com/biogo/hts/tree/master/bgzf) uses all 4 cores. [`zstd`](https://github.com/DataDog/zstd) uses one core, and is a beast (but not Go, yet). - - -## Overall differences. - -There appears to be a roughly 5-10% speed advantage over the standard library when comparing at similar compression levels. - -The biggest difference you will see is the result of [re-balancing](https://blog.klauspost.com/rebalancing-deflate-compression-levels/) the compression levels. I wanted by library to give a smoother transition between the compression levels than the standard library. - -This package attempts to provide a more smooth transition, where "1" is taking a lot of shortcuts, "5" is the reasonable trade-off and "9" is the "give me the best compression", and the values in between gives something reasonable in between. The standard library has big differences in levels 1-4, but levels 5-9 having no significant gains - often spending a lot more time than can be justified by the achieved compression. - -There are links to all the test data in the [spreadsheet](https://docs.google.com/spreadsheets/d/1nuNE2nPfuINCZJRMt6wFWhKpToF95I47XjSsc-1rbPQ/edit?usp=sharing) in the top left field on each tab. - -## Web Content - -This test set aims to emulate typical use in a web server. The test-set is 4GB data in 53k files, and is a mixture of (mostly) HTML, JS, CSS. - -Since level 1 and 9 are close to being the same code, they are quite close. But looking at the levels in-between the differences are quite big. - -Looking at level 6, this package is 88% faster, but will output about 6% more data. For a web server, this means you can serve 88% more data, but have to pay for 6% more bandwidth. You can draw your own conclusions on what would be the most expensive for your case. - -## Object files - -This test is for typical data files stored on a server. In this case it is a collection of Go precompiled objects. They are very compressible. - -The picture is similar to the web content, but with small differences since this is very compressible. Levels 2-3 offer good speed, but is sacrificing quite a bit of compression. - -The standard library seems suboptimal on level 3 and 4 - offering both worse compression and speed than level 6 & 7 of this package respectively. - -## Highly Compressible File - -This is a JSON file with very high redundancy. The reduction starts at 95% on level 1, so in real life terms we are dealing with something like a highly redundant stream of data, etc. - -It is definitely visible that we are dealing with specialized content here, so the results are very scattered. This package does not do very well at levels 1-4, but picks up significantly at level 5 and levels 7 and 8 offering great speed for the achieved compression. - -So if you know you content is extremely compressible you might want to go slightly higher than the defaults. The standard library has a huge gap between levels 3 and 4 in terms of speed (2.75x slowdown), so it offers little "middle ground". - -## Medium-High Compressible - -This is a pretty common test corpus: [enwik9](http://mattmahoney.net/dc/textdata.html). It contains the first 10^9 bytes of the English Wikipedia dump on Mar. 3, 2006. This is a very good test of typical text based compression and more data heavy streams. - -We see a similar picture here as in "Web Content". On equal levels some compression is sacrificed for more speed. Level 5 seems to be the best trade-off between speed and size, beating stdlib level 3 in both. - -## Medium Compressible - -I will combine two test sets, one [10GB file set](http://mattmahoney.net/dc/10gb.html) and a VM disk image (~8GB). Both contain different data types and represent a typical backup scenario. - -The most notable thing is how quickly the standard library drops to very low compression speeds around level 5-6 without any big gains in compression. Since this type of data is fairly common, this does not seem like good behavior. - - -## Un-compressible Content - -This is mainly a test of how good the algorithms are at detecting un-compressible input. The standard library only offers this feature with very conservative settings at level 1. Obviously there is no reason for the algorithms to try to compress input that cannot be compressed. The only downside is that it might skip some compressible data on false detections. - - -## Huffman only compression - -This compression library adds a special compression level, named `HuffmanOnly`, which allows near linear time compression. This is done by completely disabling matching of previous data, and only reduce the number of bits to represent each character. - -This means that often used characters, like 'e' and ' ' (space) in text use the fewest bits to represent, and rare characters like '¤' takes more bits to represent. For more information see [wikipedia](https://en.wikipedia.org/wiki/Huffman_coding) or this nice [video](https://youtu.be/ZdooBTdW5bM). - -Since this type of compression has much less variance, the compression speed is mostly unaffected by the input data, and is usually more than *180MB/s* for a single core. - -The downside is that the compression ratio is usually considerably worse than even the fastest conventional compression. The compression ratio can never be better than 8:1 (12.5%). - -The linear time compression can be used as a "better than nothing" mode, where you cannot risk the encoder to slow down on some content. For comparison, the size of the "Twain" text is *233460 bytes* (+29% vs. level 1) and encode speed is 144MB/s (4.5x level 1). So in this case you trade a 30% size increase for a 4 times speedup. - -For more information see my blog post on [Fast Linear Time Compression](http://blog.klauspost.com/constant-time-gzipzip-compression/). - -This is implemented on Go 1.7 as "Huffman Only" mode, though not exposed for gzip. - -# Other packages - -Here are other packages of good quality and pure Go (no cgo wrappers or autoconverted code): - -* [github.com/pierrec/lz4](https://github.com/pierrec/lz4) - strong multithreaded LZ4 compression. -* [github.com/cosnicolaou/pbzip2](https://github.com/cosnicolaou/pbzip2) - multithreaded bzip2 decompression. -* [github.com/dsnet/compress](https://github.com/dsnet/compress) - brotli decompression, bzip2 writer. -* [github.com/ronanh/intcomp](https://github.com/ronanh/intcomp) - Integer compression. -* [github.com/spenczar/fpc](https://github.com/spenczar/fpc) - Float compression. -* [github.com/minio/zipindex](https://github.com/minio/zipindex) - External ZIP directory index. -* [github.com/ybirader/pzip](https://github.com/ybirader/pzip) - Fast concurrent zip archiver and extractor. - -# license - -This code is licensed under the same conditions as the original Go code. See LICENSE file. diff --git a/vendor/github.com/klauspost/compress/SECURITY.md b/vendor/github.com/klauspost/compress/SECURITY.md deleted file mode 100644 index ca6685e2b..000000000 --- a/vendor/github.com/klauspost/compress/SECURITY.md +++ /dev/null @@ -1,25 +0,0 @@ -# Security Policy - -## Supported Versions - -Security updates are applied only to the latest release. - -## Vulnerability Definition - -A security vulnerability is a bug that with certain input triggers a crash or an infinite loop. Most calls will have varying execution time and only in rare cases will slow operation be considered a security vulnerability. - -Corrupted output generally is not considered a security vulnerability, unless independent operations are able to affect each other. Note that not all functionality is re-entrant and safe to use concurrently. - -Out-of-memory crashes only applies if the en/decoder uses an abnormal amount of memory, with appropriate options applied, to limit maximum window size, concurrency, etc. However, if you are in doubt you are welcome to file a security issue. - -It is assumed that all callers are trusted, meaning internal data exposed through reflection or inspection of returned data structures is not considered a vulnerability. - -Vulnerabilities resulting from compiler/assembler errors should be reported upstream. Depending on the severity this package may or may not implement a workaround. - -## Reporting a Vulnerability - -If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released. - -Please disclose it at [security advisory](https://github.com/klauspost/compress/security/advisories/new). If possible please provide a minimal reproducer. If the issue only applies to a single platform, it would be helpful to provide access to that. - -This project is maintained by a team of volunteers on a reasonable-effort basis. As such, vulnerabilities will be disclosed in a best effort base. diff --git a/vendor/github.com/klauspost/compress/compressible.go b/vendor/github.com/klauspost/compress/compressible.go deleted file mode 100644 index ea5a692d5..000000000 --- a/vendor/github.com/klauspost/compress/compressible.go +++ /dev/null @@ -1,85 +0,0 @@ -package compress - -import "math" - -// Estimate returns a normalized compressibility estimate of block b. -// Values close to zero are likely uncompressible. -// Values above 0.1 are likely to be compressible. -// Values above 0.5 are very compressible. -// Very small lengths will return 0. -func Estimate(b []byte) float64 { - if len(b) < 16 { - return 0 - } - - // Correctly predicted order 1 - hits := 0 - lastMatch := false - var o1 [256]byte - var hist [256]int - c1 := byte(0) - for _, c := range b { - if c == o1[c1] { - // We only count a hit if there was two correct predictions in a row. - if lastMatch { - hits++ - } - lastMatch = true - } else { - lastMatch = false - } - o1[c1] = c - c1 = c - hist[c]++ - } - - // Use x^0.6 to give better spread - prediction := math.Pow(float64(hits)/float64(len(b)), 0.6) - - // Calculate histogram distribution - variance := float64(0) - avg := float64(len(b)) / 256 - - for _, v := range hist { - Δ := float64(v) - avg - variance += Δ * Δ - } - - stddev := math.Sqrt(float64(variance)) / float64(len(b)) - exp := math.Sqrt(1 / float64(len(b))) - - // Subtract expected stddev - stddev -= exp - if stddev < 0 { - stddev = 0 - } - stddev *= 1 + exp - - // Use x^0.4 to give better spread - entropy := math.Pow(stddev, 0.4) - - // 50/50 weight between prediction and histogram distribution - return math.Pow((prediction+entropy)/2, 0.9) -} - -// ShannonEntropyBits returns the number of bits minimum required to represent -// an entropy encoding of the input bytes. -// https://en.wiktionary.org/wiki/Shannon_entropy -func ShannonEntropyBits(b []byte) int { - if len(b) == 0 { - return 0 - } - var hist [256]int - for _, c := range b { - hist[c]++ - } - shannon := float64(0) - invTotal := 1.0 / float64(len(b)) - for _, v := range hist[:] { - if v > 0 { - n := float64(v) - shannon += math.Ceil(-math.Log2(n*invTotal) * n) - } - } - return int(math.Ceil(shannon)) -} diff --git a/vendor/github.com/klauspost/compress/fse/README.md b/vendor/github.com/klauspost/compress/fse/README.md deleted file mode 100644 index ea7324da6..000000000 --- a/vendor/github.com/klauspost/compress/fse/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# Finite State Entropy - -This package provides Finite State Entropy encoding and decoding. - -Finite State Entropy (also referenced as [tANS](https://en.wikipedia.org/wiki/Asymmetric_numeral_systems#tANS)) -encoding provides a fast near-optimal symbol encoding/decoding -for byte blocks as implemented in [zstandard](https://github.com/facebook/zstd). - -This can be used for compressing input with a lot of similar input values to the smallest number of bytes. -This does not perform any multi-byte [dictionary coding](https://en.wikipedia.org/wiki/Dictionary_coder) as LZ coders, -but it can be used as a secondary step to compressors (like Snappy) that does not do entropy encoding. - -* [Godoc documentation](https://godoc.org/github.com/klauspost/compress/fse) - -## News - - * Feb 2018: First implementation released. Consider this beta software for now. - -# Usage - -This package provides a low level interface that allows to compress single independent blocks. - -Each block is separate, and there is no built in integrity checks. -This means that the caller should keep track of block sizes and also do checksums if needed. - -Compressing a block is done via the [`Compress`](https://godoc.org/github.com/klauspost/compress/fse#Compress) function. -You must provide input and will receive the output and maybe an error. - -These error values can be returned: - -| Error | Description | -|---------------------|-----------------------------------------------------------------------------| -| `` | Everything ok, output is returned | -| `ErrIncompressible` | Returned when input is judged to be too hard to compress | -| `ErrUseRLE` | Returned from the compressor when the input is a single byte value repeated | -| `(error)` | An internal error occurred. | - -As can be seen above there are errors that will be returned even under normal operation so it is important to handle these. - -To reduce allocations you can provide a [`Scratch`](https://godoc.org/github.com/klauspost/compress/fse#Scratch) object -that can be re-used for successive calls. Both compression and decompression accepts a `Scratch` object, and the same -object can be used for both. - -Be aware, that when re-using a `Scratch` object that the *output* buffer is also re-used, so if you are still using this -you must set the `Out` field in the scratch to nil. The same buffer is used for compression and decompression output. - -Decompressing is done by calling the [`Decompress`](https://godoc.org/github.com/klauspost/compress/fse#Decompress) function. -You must provide the output from the compression stage, at exactly the size you got back. If you receive an error back -your input was likely corrupted. - -It is important to note that a successful decoding does *not* mean your output matches your original input. -There are no integrity checks, so relying on errors from the decompressor does not assure your data is valid. - -For more detailed usage, see examples in the [godoc documentation](https://godoc.org/github.com/klauspost/compress/fse#pkg-examples). - -# Performance - -A lot of factors are affecting speed. Block sizes and compressibility of the material are primary factors. -All compression functions are currently only running on the calling goroutine so only one core will be used per block. - -The compressor is significantly faster if symbols are kept as small as possible. The highest byte value of the input -is used to reduce some of the processing, so if all your input is above byte value 64 for instance, it may be -beneficial to transpose all your input values down by 64. - -With moderate block sizes around 64k speed are typically 200MB/s per core for compression and -around 300MB/s decompression speed. - -The same hardware typically does Huffman (deflate) encoding at 125MB/s and decompression at 100MB/s. - -# Plans - -At one point, more internals will be exposed to facilitate more "expert" usage of the components. - -A streaming interface is also likely to be implemented. Likely compatible with [FSE stream format](https://github.com/Cyan4973/FiniteStateEntropy/blob/dev/programs/fileio.c#L261). - -# Contributing - -Contributions are always welcome. Be aware that adding public functions will require good justification and breaking -changes will likely not be accepted. If in doubt open an issue before writing the PR. \ No newline at end of file diff --git a/vendor/github.com/klauspost/compress/fse/bitreader.go b/vendor/github.com/klauspost/compress/fse/bitreader.go deleted file mode 100644 index f65eb3909..000000000 --- a/vendor/github.com/klauspost/compress/fse/bitreader.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package fse - -import ( - "encoding/binary" - "errors" - "io" -) - -// bitReader reads a bitstream in reverse. -// The last set bit indicates the start of the stream and is used -// for aligning the input. -type bitReader struct { - in []byte - off uint // next byte to read is at in[off - 1] - value uint64 - bitsRead uint8 -} - -// init initializes and resets the bit reader. -func (b *bitReader) init(in []byte) error { - if len(in) < 1 { - return errors.New("corrupt stream: too short") - } - b.in = in - b.off = uint(len(in)) - // The highest bit of the last byte indicates where to start - v := in[len(in)-1] - if v == 0 { - return errors.New("corrupt stream, did not find end of stream") - } - b.bitsRead = 64 - b.value = 0 - if len(in) >= 8 { - b.fillFastStart() - } else { - b.fill() - b.fill() - } - b.bitsRead += 8 - uint8(highBits(uint32(v))) - return nil -} - -// getBits will return n bits. n can be 0. -func (b *bitReader) getBits(n uint8) uint16 { - if n == 0 || b.bitsRead >= 64 { - return 0 - } - return b.getBitsFast(n) -} - -// getBitsFast requires that at least one bit is requested every time. -// There are no checks if the buffer is filled. -func (b *bitReader) getBitsFast(n uint8) uint16 { - const regMask = 64 - 1 - v := uint16((b.value << (b.bitsRead & regMask)) >> ((regMask + 1 - n) & regMask)) - b.bitsRead += n - return v -} - -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReader) fillFast() { - if b.bitsRead < 32 { - return - } - // 2 bounds checks. - v := b.in[b.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value = (b.value << 32) | uint64(low) - b.bitsRead -= 32 - b.off -= 4 -} - -// fill() will make sure at least 32 bits are available. -func (b *bitReader) fill() { - if b.bitsRead < 32 { - return - } - if b.off > 4 { - v := b.in[b.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value = (b.value << 32) | uint64(low) - b.bitsRead -= 32 - b.off -= 4 - return - } - for b.off > 0 { - b.value = (b.value << 8) | uint64(b.in[b.off-1]) - b.bitsRead -= 8 - b.off-- - } -} - -// fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read. -func (b *bitReader) fillFastStart() { - // Do single re-slice to avoid bounds checks. - b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) - b.bitsRead = 0 - b.off -= 8 -} - -// finished returns true if all bits have been read from the bit stream. -func (b *bitReader) finished() bool { - return b.bitsRead >= 64 && b.off == 0 -} - -// close the bitstream and returns an error if out-of-buffer reads occurred. -func (b *bitReader) close() error { - // Release reference. - b.in = nil - if b.bitsRead > 64 { - return io.ErrUnexpectedEOF - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/fse/bitwriter.go b/vendor/github.com/klauspost/compress/fse/bitwriter.go deleted file mode 100644 index e82fa3bb7..000000000 --- a/vendor/github.com/klauspost/compress/fse/bitwriter.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package fse - -import "fmt" - -// bitWriter will write bits. -// First bit will be LSB of the first byte of output. -type bitWriter struct { - bitContainer uint64 - nBits uint8 - out []byte -} - -// bitMask16 is bitmasks. Has extra to avoid bounds check. -var bitMask16 = [32]uint16{ - 0, 1, 3, 7, 0xF, 0x1F, - 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, - 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, - 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, - 0xFFFF, 0xFFFF} /* up to 16 bits */ - -// addBits16NC will add up to 16 bits. -// It will not check if there is space for them, -// so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16NC(value uint16, bits uint8) { - b.bitContainer |= uint64(value&bitMask16[bits&31]) << (b.nBits & 63) - b.nBits += bits -} - -// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// addBits16ZeroNC will add up to 16 bits. -// It will not check if there is space for them, -// so the caller must ensure that it has flushed recently. -// This is fastest if bits can be zero. -func (b *bitWriter) addBits16ZeroNC(value uint16, bits uint8) { - if bits == 0 { - return - } - value <<= (16 - bits) & 15 - value >>= (16 - bits) & 15 - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// flush will flush all pending full bytes. -// There will be at least 56 bits available for writing when this has been called. -// Using flush32 is faster, but leaves less space for writing. -func (b *bitWriter) flush() { - v := b.nBits >> 3 - switch v { - case 0: - case 1: - b.out = append(b.out, - byte(b.bitContainer), - ) - case 2: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - ) - case 3: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - ) - case 4: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - ) - case 5: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - byte(b.bitContainer>>32), - ) - case 6: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - byte(b.bitContainer>>32), - byte(b.bitContainer>>40), - ) - case 7: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - byte(b.bitContainer>>32), - byte(b.bitContainer>>40), - byte(b.bitContainer>>48), - ) - case 8: - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24), - byte(b.bitContainer>>32), - byte(b.bitContainer>>40), - byte(b.bitContainer>>48), - byte(b.bitContainer>>56), - ) - default: - panic(fmt.Errorf("bits (%d) > 64", b.nBits)) - } - b.bitContainer >>= v << 3 - b.nBits &= 7 -} - -// flush32 will flush out, so there are at least 32 bits available for writing. -func (b *bitWriter) flush32() { - if b.nBits < 32 { - return - } - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24)) - b.nBits -= 32 - b.bitContainer >>= 32 -} - -// flushAlign will flush remaining full bytes and align to next byte boundary. -func (b *bitWriter) flushAlign() { - nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { - b.out = append(b.out, byte(b.bitContainer>>(i*8))) - } - b.nBits = 0 - b.bitContainer = 0 -} - -// close will write the alignment bit and write the final byte(s) -// to the output. -func (b *bitWriter) close() { - // End mark - b.addBits16Clean(1, 1) - // flush until next byte. - b.flushAlign() -} - -// reset and continue writing by appending to out. -func (b *bitWriter) reset(out []byte) { - b.bitContainer = 0 - b.nBits = 0 - b.out = out -} diff --git a/vendor/github.com/klauspost/compress/fse/bytereader.go b/vendor/github.com/klauspost/compress/fse/bytereader.go deleted file mode 100644 index abade2d60..000000000 --- a/vendor/github.com/klauspost/compress/fse/bytereader.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package fse - -// byteReader provides a byte reader that reads -// little endian values from a byte stream. -// The input stream is manually advanced. -// The reader performs no bounds checks. -type byteReader struct { - b []byte - off int -} - -// init will initialize the reader and set the input. -func (b *byteReader) init(in []byte) { - b.b = in - b.off = 0 -} - -// advance the stream b n bytes. -func (b *byteReader) advance(n uint) { - b.off += int(n) -} - -// Uint32 returns a little endian uint32 starting at current offset. -func (b byteReader) Uint32() uint32 { - b2 := b.b[b.off:] - b2 = b2[:4] - v3 := uint32(b2[3]) - v2 := uint32(b2[2]) - v1 := uint32(b2[1]) - v0 := uint32(b2[0]) - return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) -} - -// unread returns the unread portion of the input. -func (b byteReader) unread() []byte { - return b.b[b.off:] -} - -// remain will return the number of bytes remaining. -func (b byteReader) remain() int { - return len(b.b) - b.off -} diff --git a/vendor/github.com/klauspost/compress/fse/compress.go b/vendor/github.com/klauspost/compress/fse/compress.go deleted file mode 100644 index 074018d8f..000000000 --- a/vendor/github.com/klauspost/compress/fse/compress.go +++ /dev/null @@ -1,683 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package fse - -import ( - "errors" - "fmt" -) - -// Compress the input bytes. Input must be < 2GB. -// Provide a Scratch buffer to avoid memory allocations. -// Note that the output is also kept in the scratch buffer. -// If input is too hard to compress, ErrIncompressible is returned. -// If input is a single byte value repeated ErrUseRLE is returned. -func Compress(in []byte, s *Scratch) ([]byte, error) { - if len(in) <= 1 { - return nil, ErrIncompressible - } - if len(in) > (2<<30)-1 { - return nil, errors.New("input too big, must be < 2GB") - } - s, err := s.prepare(in) - if err != nil { - return nil, err - } - - // Create histogram, if none was provided. - maxCount := s.maxCount - if maxCount == 0 { - maxCount = s.countSimple(in) - } - // Reset for next run. - s.clearCount = true - s.maxCount = 0 - if maxCount == len(in) { - // One symbol, use RLE - return nil, ErrUseRLE - } - if maxCount == 1 || maxCount < (len(in)>>7) { - // Each symbol present maximum once or too well distributed. - return nil, ErrIncompressible - } - s.optimalTableLog() - err = s.normalizeCount() - if err != nil { - return nil, err - } - err = s.writeCount() - if err != nil { - return nil, err - } - - if false { - err = s.validateNorm() - if err != nil { - return nil, err - } - } - - err = s.buildCTable() - if err != nil { - return nil, err - } - err = s.compress(in) - if err != nil { - return nil, err - } - s.Out = s.bw.out - // Check if we compressed. - if len(s.Out) >= len(in) { - return nil, ErrIncompressible - } - return s.Out, nil -} - -// cState contains the compression state of a stream. -type cState struct { - bw *bitWriter - stateTable []uint16 - state uint16 -} - -// init will initialize the compression state to the first symbol of the stream. -func (c *cState) init(bw *bitWriter, ct *cTable, tableLog uint8, first symbolTransform) { - c.bw = bw - c.stateTable = ct.stateTable - - nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16 - im := int32((nbBitsOut << 16) - first.deltaNbBits) - lu := (im >> nbBitsOut) + first.deltaFindState - c.state = c.stateTable[lu] -} - -// encode the output symbol provided and write it to the bitstream. -func (c *cState) encode(symbolTT symbolTransform) { - nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16 - dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState - c.bw.addBits16NC(c.state, uint8(nbBitsOut)) - c.state = c.stateTable[dstState] -} - -// encode the output symbol provided and write it to the bitstream. -func (c *cState) encodeZero(symbolTT symbolTransform) { - nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16 - dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState - c.bw.addBits16ZeroNC(c.state, uint8(nbBitsOut)) - c.state = c.stateTable[dstState] -} - -// flush will write the tablelog to the output and flush the remaining full bytes. -func (c *cState) flush(tableLog uint8) { - c.bw.flush32() - c.bw.addBits16NC(c.state, tableLog) - c.bw.flush() -} - -// compress is the main compression loop that will encode the input from the last byte to the first. -func (s *Scratch) compress(src []byte) error { - if len(src) <= 2 { - return errors.New("compress: src too small") - } - tt := s.ct.symbolTT[:256] - s.bw.reset(s.Out) - - // Our two states each encodes every second byte. - // Last byte encoded (first byte decoded) will always be encoded by c1. - var c1, c2 cState - - // Encode so remaining size is divisible by 4. - ip := len(src) - if ip&1 == 1 { - c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]]) - c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]]) - c1.encodeZero(tt[src[ip-3]]) - ip -= 3 - } else { - c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]]) - c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]]) - ip -= 2 - } - if ip&2 != 0 { - c2.encodeZero(tt[src[ip-1]]) - c1.encodeZero(tt[src[ip-2]]) - ip -= 2 - } - src = src[:ip] - - // Main compression loop. - switch { - case !s.zeroBits && s.actualTableLog <= 8: - // We can encode 4 symbols without requiring a flush. - // We do not need to check if any output is 0 bits. - for ; len(src) >= 4; src = src[:len(src)-4] { - s.bw.flush32() - v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] - c2.encode(tt[v0]) - c1.encode(tt[v1]) - c2.encode(tt[v2]) - c1.encode(tt[v3]) - } - case !s.zeroBits: - // We do not need to check if any output is 0 bits. - for ; len(src) >= 4; src = src[:len(src)-4] { - s.bw.flush32() - v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] - c2.encode(tt[v0]) - c1.encode(tt[v1]) - s.bw.flush32() - c2.encode(tt[v2]) - c1.encode(tt[v3]) - } - case s.actualTableLog <= 8: - // We can encode 4 symbols without requiring a flush - for ; len(src) >= 4; src = src[:len(src)-4] { - s.bw.flush32() - v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] - c2.encodeZero(tt[v0]) - c1.encodeZero(tt[v1]) - c2.encodeZero(tt[v2]) - c1.encodeZero(tt[v3]) - } - default: - for ; len(src) >= 4; src = src[:len(src)-4] { - s.bw.flush32() - v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1] - c2.encodeZero(tt[v0]) - c1.encodeZero(tt[v1]) - s.bw.flush32() - c2.encodeZero(tt[v2]) - c1.encodeZero(tt[v3]) - } - } - - // Flush final state. - // Used to initialize state when decoding. - c2.flush(s.actualTableLog) - c1.flush(s.actualTableLog) - - s.bw.close() - return nil -} - -// writeCount will write the normalized histogram count to header. -// This is read back by readNCount. -func (s *Scratch) writeCount() error { - var ( - tableLog = s.actualTableLog - tableSize = 1 << tableLog - previous0 bool - charnum uint16 - - maxHeaderSize = ((int(s.symbolLen)*int(tableLog) + 4 + 2) >> 3) + 3 - - // Write Table Size - bitStream = uint32(tableLog - minTablelog) - bitCount = uint(4) - remaining = int16(tableSize + 1) /* +1 for extra accuracy */ - threshold = int16(tableSize) - nbBits = uint(tableLog + 1) - ) - if cap(s.Out) < maxHeaderSize { - s.Out = make([]byte, 0, s.br.remain()+maxHeaderSize) - } - outP := uint(0) - out := s.Out[:maxHeaderSize] - - // stops at 1 - for remaining > 1 { - if previous0 { - start := charnum - for s.norm[charnum] == 0 { - charnum++ - } - for charnum >= start+24 { - start += 24 - bitStream += uint32(0xFFFF) << bitCount - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - } - for charnum >= start+3 { - start += 3 - bitStream += 3 << bitCount - bitCount += 2 - } - bitStream += uint32(charnum-start) << bitCount - bitCount += 2 - if bitCount > 16 { - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - bitCount -= 16 - } - } - - count := s.norm[charnum] - charnum++ - max := (2*threshold - 1) - remaining - if count < 0 { - remaining += count - } else { - remaining -= count - } - count++ // +1 for extra accuracy - if count >= threshold { - count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ - } - bitStream += uint32(count) << bitCount - bitCount += nbBits - if count < max { - bitCount-- - } - - previous0 = count == 1 - if remaining < 1 { - return errors.New("internal error: remaining<1") - } - for remaining < threshold { - nbBits-- - threshold >>= 1 - } - - if bitCount > 16 { - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - bitCount -= 16 - } - } - - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += (bitCount + 7) / 8 - - if charnum > s.symbolLen { - return errors.New("internal error: charnum > s.symbolLen") - } - s.Out = out[:outP] - return nil -} - -// symbolTransform contains the state transform for a symbol. -type symbolTransform struct { - deltaFindState int32 - deltaNbBits uint32 -} - -// String prints values as a human readable string. -func (s symbolTransform) String() string { - return fmt.Sprintf("dnbits: %08x, fs:%d", s.deltaNbBits, s.deltaFindState) -} - -// cTable contains tables used for compression. -type cTable struct { - tableSymbol []byte - stateTable []uint16 - symbolTT []symbolTransform -} - -// allocCtable will allocate tables needed for compression. -// If existing tables a re big enough, they are simply re-used. -func (s *Scratch) allocCtable() { - tableSize := 1 << s.actualTableLog - // get tableSymbol that is big enough. - if cap(s.ct.tableSymbol) < tableSize { - s.ct.tableSymbol = make([]byte, tableSize) - } - s.ct.tableSymbol = s.ct.tableSymbol[:tableSize] - - ctSize := tableSize - if cap(s.ct.stateTable) < ctSize { - s.ct.stateTable = make([]uint16, ctSize) - } - s.ct.stateTable = s.ct.stateTable[:ctSize] - - if cap(s.ct.symbolTT) < 256 { - s.ct.symbolTT = make([]symbolTransform, 256) - } - s.ct.symbolTT = s.ct.symbolTT[:256] -} - -// buildCTable will populate the compression table so it is ready to be used. -func (s *Scratch) buildCTable() error { - tableSize := uint32(1 << s.actualTableLog) - highThreshold := tableSize - 1 - var cumul [maxSymbolValue + 2]int16 - - s.allocCtable() - tableSymbol := s.ct.tableSymbol[:tableSize] - // symbol start positions - { - cumul[0] = 0 - for ui, v := range s.norm[:s.symbolLen-1] { - u := byte(ui) // one less than reference - if v == -1 { - // Low proba symbol - cumul[u+1] = cumul[u] + 1 - tableSymbol[highThreshold] = u - highThreshold-- - } else { - cumul[u+1] = cumul[u] + v - } - } - // Encode last symbol separately to avoid overflowing u - u := int(s.symbolLen - 1) - v := s.norm[s.symbolLen-1] - if v == -1 { - // Low proba symbol - cumul[u+1] = cumul[u] + 1 - tableSymbol[highThreshold] = byte(u) - highThreshold-- - } else { - cumul[u+1] = cumul[u] + v - } - if uint32(cumul[s.symbolLen]) != tableSize { - return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize) - } - cumul[s.symbolLen] = int16(tableSize) + 1 - } - // Spread symbols - s.zeroBits = false - { - step := tableStep(tableSize) - tableMask := tableSize - 1 - var position uint32 - // if any symbol > largeLimit, we may have 0 bits output. - largeLimit := int16(1 << (s.actualTableLog - 1)) - for ui, v := range s.norm[:s.symbolLen] { - symbol := byte(ui) - if v > largeLimit { - s.zeroBits = true - } - for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ { - tableSymbol[position] = symbol - position = (position + step) & tableMask - for position > highThreshold { - position = (position + step) & tableMask - } /* Low proba area */ - } - } - - // Check if we have gone through all positions - if position != 0 { - return errors.New("position!=0") - } - } - - // Build table - table := s.ct.stateTable - { - tsi := int(tableSize) - for u, v := range tableSymbol { - // TableU16 : sorted by symbol order; gives next state value - table[cumul[v]] = uint16(tsi + u) - cumul[v]++ - } - } - - // Build Symbol Transformation Table - { - total := int16(0) - symbolTT := s.ct.symbolTT[:s.symbolLen] - tableLog := s.actualTableLog - tl := (uint32(tableLog) << 16) - (1 << tableLog) - for i, v := range s.norm[:s.symbolLen] { - switch v { - case 0: - case -1, 1: - symbolTT[i].deltaNbBits = tl - symbolTT[i].deltaFindState = int32(total - 1) - total++ - default: - maxBitsOut := uint32(tableLog) - highBits(uint32(v-1)) - minStatePlus := uint32(v) << maxBitsOut - symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus - symbolTT[i].deltaFindState = int32(total - v) - total += v - } - } - if total != int16(tableSize) { - return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize) - } - } - return nil -} - -// countSimple will create a simple histogram in s.count. -// Returns the biggest count. -// Does not update s.clearCount. -func (s *Scratch) countSimple(in []byte) (max int) { - for _, v := range in { - s.count[v]++ - } - m, symlen := uint32(0), s.symbolLen - for i, v := range s.count[:] { - if v == 0 { - continue - } - if v > m { - m = v - } - symlen = uint16(i) + 1 - } - s.symbolLen = symlen - return int(m) -} - -// minTableLog provides the minimum logSize to safely represent a distribution. -func (s *Scratch) minTableLog() uint8 { - minBitsSrc := highBits(uint32(s.br.remain()-1)) + 1 - minBitsSymbols := highBits(uint32(s.symbolLen-1)) + 2 - if minBitsSrc < minBitsSymbols { - return uint8(minBitsSrc) - } - return uint8(minBitsSymbols) -} - -// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog -func (s *Scratch) optimalTableLog() { - tableLog := s.TableLog - minBits := s.minTableLog() - maxBitsSrc := uint8(highBits(uint32(s.br.remain()-1))) - 2 - if maxBitsSrc < tableLog { - // Accuracy can be reduced - tableLog = maxBitsSrc - } - if minBits > tableLog { - tableLog = minBits - } - // Need a minimum to safely represent all symbol values - if tableLog < minTablelog { - tableLog = minTablelog - } - if tableLog > maxTableLog { - tableLog = maxTableLog - } - s.actualTableLog = tableLog -} - -var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000} - -// normalizeCount will normalize the count of the symbols so -// the total is equal to the table size. -func (s *Scratch) normalizeCount() error { - var ( - tableLog = s.actualTableLog - scale = 62 - uint64(tableLog) - step = (1 << 62) / uint64(s.br.remain()) - vStep = uint64(1) << (scale - 20) - stillToDistribute = int16(1 << tableLog) - largest int - largestP int16 - lowThreshold = (uint32)(s.br.remain() >> tableLog) - ) - - for i, cnt := range s.count[:s.symbolLen] { - // already handled - // if (count[s] == s.length) return 0; /* rle special case */ - - if cnt == 0 { - s.norm[i] = 0 - continue - } - if cnt <= lowThreshold { - s.norm[i] = -1 - stillToDistribute-- - } else { - proba := (int16)((uint64(cnt) * step) >> scale) - if proba < 8 { - restToBeat := vStep * uint64(rtbTable[proba]) - v := uint64(cnt)*step - (uint64(proba) << scale) - if v > restToBeat { - proba++ - } - } - if proba > largestP { - largestP = proba - largest = i - } - s.norm[i] = proba - stillToDistribute -= proba - } - } - - if -stillToDistribute >= (s.norm[largest] >> 1) { - // corner case, need another normalization method - return s.normalizeCount2() - } - s.norm[largest] += stillToDistribute - return nil -} - -// Secondary normalization method. -// To be used when primary method fails. -func (s *Scratch) normalizeCount2() error { - const notYetAssigned = -2 - var ( - distributed uint32 - total = uint32(s.br.remain()) - tableLog = s.actualTableLog - lowThreshold = total >> tableLog - lowOne = (total * 3) >> (tableLog + 1) - ) - for i, cnt := range s.count[:s.symbolLen] { - if cnt == 0 { - s.norm[i] = 0 - continue - } - if cnt <= lowThreshold { - s.norm[i] = -1 - distributed++ - total -= cnt - continue - } - if cnt <= lowOne { - s.norm[i] = 1 - distributed++ - total -= cnt - continue - } - s.norm[i] = notYetAssigned - } - toDistribute := (1 << tableLog) - distributed - - if (total / toDistribute) > lowOne { - // risk of rounding to zero - lowOne = (total * 3) / (toDistribute * 2) - for i, cnt := range s.count[:s.symbolLen] { - if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) { - s.norm[i] = 1 - distributed++ - total -= cnt - continue - } - } - toDistribute = (1 << tableLog) - distributed - } - if distributed == uint32(s.symbolLen)+1 { - // all values are pretty poor; - // probably incompressible data (should have already been detected); - // find max, then give all remaining points to max - var maxV int - var maxC uint32 - for i, cnt := range s.count[:s.symbolLen] { - if cnt > maxC { - maxV = i - maxC = cnt - } - } - s.norm[maxV] += int16(toDistribute) - return nil - } - - if total == 0 { - // all of the symbols were low enough for the lowOne or lowThreshold - for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) { - if s.norm[i] > 0 { - toDistribute-- - s.norm[i]++ - } - } - return nil - } - - var ( - vStepLog = 62 - uint64(tableLog) - mid = uint64((1 << (vStepLog - 1)) - 1) - rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining - tmpTotal = mid - ) - for i, cnt := range s.count[:s.symbolLen] { - if s.norm[i] == notYetAssigned { - var ( - end = tmpTotal + uint64(cnt)*rStep - sStart = uint32(tmpTotal >> vStepLog) - sEnd = uint32(end >> vStepLog) - weight = sEnd - sStart - ) - if weight < 1 { - return errors.New("weight < 1") - } - s.norm[i] = int16(weight) - tmpTotal = end - } - } - return nil -} - -// validateNorm validates the normalized histogram table. -func (s *Scratch) validateNorm() (err error) { - var total int - for _, v := range s.norm[:s.symbolLen] { - if v >= 0 { - total += int(v) - } else { - total -= int(v) - } - } - defer func() { - if err == nil { - return - } - fmt.Printf("selected TableLog: %d, Symbol length: %d\n", s.actualTableLog, s.symbolLen) - for i, v := range s.norm[:s.symbolLen] { - fmt.Printf("%3d: %5d -> %4d \n", i, s.count[i], v) - } - }() - if total != (1 << s.actualTableLog) { - return fmt.Errorf("warning: Total == %d != %d", total, 1< tablelogAbsoluteMax { - return errors.New("tableLog too large") - } - bitStream >>= 4 - bitCount := uint(4) - - s.actualTableLog = uint8(nbBits) - remaining := int32((1 << nbBits) + 1) - threshold := int32(1 << nbBits) - gotTotal := int32(0) - nbBits++ - - for remaining > 1 { - if previous0 { - n0 := charnum - for (bitStream & 0xFFFF) == 0xFFFF { - n0 += 24 - if b.off < iend-5 { - b.advance(2) - bitStream = b.Uint32() >> bitCount - } else { - bitStream >>= 16 - bitCount += 16 - } - } - for (bitStream & 3) == 3 { - n0 += 3 - bitStream >>= 2 - bitCount += 2 - } - n0 += uint16(bitStream & 3) - bitCount += 2 - if n0 > maxSymbolValue { - return errors.New("maxSymbolValue too small") - } - for charnum < n0 { - s.norm[charnum&0xff] = 0 - charnum++ - } - - if b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 { - b.advance(bitCount >> 3) - bitCount &= 7 - bitStream = b.Uint32() >> bitCount - } else { - bitStream >>= 2 - } - } - - max := (2*(threshold) - 1) - (remaining) - var count int32 - - if (int32(bitStream) & (threshold - 1)) < max { - count = int32(bitStream) & (threshold - 1) - bitCount += nbBits - 1 - } else { - count = int32(bitStream) & (2*threshold - 1) - if count >= threshold { - count -= max - } - bitCount += nbBits - } - - count-- // extra accuracy - if count < 0 { - // -1 means +1 - remaining += count - gotTotal -= count - } else { - remaining -= count - gotTotal += count - } - s.norm[charnum&0xff] = int16(count) - charnum++ - previous0 = count == 0 - for remaining < threshold { - nbBits-- - threshold >>= 1 - } - if b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 { - b.advance(bitCount >> 3) - bitCount &= 7 - } else { - bitCount -= (uint)(8 * (len(b.b) - 4 - b.off)) - b.off = len(b.b) - 4 - } - bitStream = b.Uint32() >> (bitCount & 31) - } - s.symbolLen = charnum - - if s.symbolLen <= 1 { - return fmt.Errorf("symbolLen (%d) too small", s.symbolLen) - } - if s.symbolLen > maxSymbolValue+1 { - return fmt.Errorf("symbolLen (%d) too big", s.symbolLen) - } - if remaining != 1 { - return fmt.Errorf("corruption detected (remaining %d != 1)", remaining) - } - if bitCount > 32 { - return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount) - } - if gotTotal != 1<> 3) - return nil -} - -// decSymbol contains information about a state entry, -// Including the state offset base, the output symbol and -// the number of bits to read for the low part of the destination state. -type decSymbol struct { - newState uint16 - symbol uint8 - nbBits uint8 -} - -// allocDtable will allocate decoding tables if they are not big enough. -func (s *Scratch) allocDtable() { - tableSize := 1 << s.actualTableLog - if cap(s.decTable) < tableSize { - s.decTable = make([]decSymbol, tableSize) - } - s.decTable = s.decTable[:tableSize] - - if cap(s.ct.tableSymbol) < 256 { - s.ct.tableSymbol = make([]byte, 256) - } - s.ct.tableSymbol = s.ct.tableSymbol[:256] - - if cap(s.ct.stateTable) < 256 { - s.ct.stateTable = make([]uint16, 256) - } - s.ct.stateTable = s.ct.stateTable[:256] -} - -// buildDtable will build the decoding table. -func (s *Scratch) buildDtable() error { - tableSize := uint32(1 << s.actualTableLog) - highThreshold := tableSize - 1 - s.allocDtable() - symbolNext := s.ct.stateTable[:256] - - // Init, lay down lowprob symbols - s.zeroBits = false - { - largeLimit := int16(1 << (s.actualTableLog - 1)) - for i, v := range s.norm[:s.symbolLen] { - if v == -1 { - s.decTable[highThreshold].symbol = uint8(i) - highThreshold-- - symbolNext[i] = 1 - } else { - if v >= largeLimit { - s.zeroBits = true - } - symbolNext[i] = uint16(v) - } - } - } - // Spread symbols - { - tableMask := tableSize - 1 - step := tableStep(tableSize) - position := uint32(0) - for ss, v := range s.norm[:s.symbolLen] { - for i := 0; i < int(v); i++ { - s.decTable[position].symbol = uint8(ss) - position = (position + step) & tableMask - for position > highThreshold { - // lowprob area - position = (position + step) & tableMask - } - } - } - if position != 0 { - // position must reach all cells once, otherwise normalizedCounter is incorrect - return errors.New("corrupted input (position != 0)") - } - } - - // Build Decoding table - { - tableSize := uint16(1 << s.actualTableLog) - for u, v := range s.decTable { - symbol := v.symbol - nextState := symbolNext[symbol] - symbolNext[symbol] = nextState + 1 - nBits := s.actualTableLog - byte(highBits(uint32(nextState))) - s.decTable[u].nbBits = nBits - newState := (nextState << nBits) - tableSize - if newState >= tableSize { - return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize) - } - if newState == uint16(u) && nBits == 0 { - // Seems weird that this is possible with nbits > 0. - return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u) - } - s.decTable[u].newState = newState - } - } - return nil -} - -// decompress will decompress the bitstream. -// If the buffer is over-read an error is returned. -func (s *Scratch) decompress() error { - br := &s.bits - if err := br.init(s.br.unread()); err != nil { - return err - } - - var s1, s2 decoder - // Initialize and decode first state and symbol. - s1.init(br, s.decTable, s.actualTableLog) - s2.init(br, s.decTable, s.actualTableLog) - - // Use temp table to avoid bound checks/append penalty. - var tmp = s.ct.tableSymbol[:256] - var off uint8 - - // Main part - if !s.zeroBits { - for br.off >= 8 { - br.fillFast() - tmp[off+0] = s1.nextFast() - tmp[off+1] = s2.nextFast() - br.fillFast() - tmp[off+2] = s1.nextFast() - tmp[off+3] = s2.nextFast() - off += 4 - // When off is 0, we have overflowed and should write. - if off == 0 { - s.Out = append(s.Out, tmp...) - if len(s.Out) >= s.DecompressLimit { - return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) - } - } - } - } else { - for br.off >= 8 { - br.fillFast() - tmp[off+0] = s1.next() - tmp[off+1] = s2.next() - br.fillFast() - tmp[off+2] = s1.next() - tmp[off+3] = s2.next() - off += 4 - if off == 0 { - s.Out = append(s.Out, tmp...) - // When off is 0, we have overflowed and should write. - if len(s.Out) >= s.DecompressLimit { - return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) - } - } - } - } - s.Out = append(s.Out, tmp[:off]...) - - // Final bits, a bit more expensive check - for { - if s1.finished() { - s.Out = append(s.Out, s1.final(), s2.final()) - break - } - br.fill() - s.Out = append(s.Out, s1.next()) - if s2.finished() { - s.Out = append(s.Out, s2.final(), s1.final()) - break - } - s.Out = append(s.Out, s2.next()) - if len(s.Out) >= s.DecompressLimit { - return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit) - } - } - return br.close() -} - -// decoder keeps track of the current state and updates it from the bitstream. -type decoder struct { - state uint16 - br *bitReader - dt []decSymbol -} - -// init will initialize the decoder and read the first state from the stream. -func (d *decoder) init(in *bitReader, dt []decSymbol, tableLog uint8) { - d.dt = dt - d.br = in - d.state = in.getBits(tableLog) -} - -// next returns the next symbol and sets the next state. -// At least tablelog bits must be available in the bit reader. -func (d *decoder) next() uint8 { - n := &d.dt[d.state] - lowBits := d.br.getBits(n.nbBits) - d.state = n.newState + lowBits - return n.symbol -} - -// finished returns true if all bits have been read from the bitstream -// and the next state would require reading bits from the input. -func (d *decoder) finished() bool { - return d.br.finished() && d.dt[d.state].nbBits > 0 -} - -// final returns the current state symbol without decoding the next. -func (d *decoder) final() uint8 { - return d.dt[d.state].symbol -} - -// nextFast returns the next symbol and sets the next state. -// This can only be used if no symbols are 0 bits. -// At least tablelog bits must be available in the bit reader. -func (d *decoder) nextFast() uint8 { - n := d.dt[d.state] - lowBits := d.br.getBitsFast(n.nbBits) - d.state = n.newState + lowBits - return n.symbol -} diff --git a/vendor/github.com/klauspost/compress/fse/fse.go b/vendor/github.com/klauspost/compress/fse/fse.go deleted file mode 100644 index 535cbadfd..000000000 --- a/vendor/github.com/klauspost/compress/fse/fse.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -// Package fse provides Finite State Entropy encoding and decoding. -// -// Finite State Entropy encoding provides a fast near-optimal symbol encoding/decoding -// for byte blocks as implemented in zstd. -// -// See https://github.com/klauspost/compress/tree/master/fse for more information. -package fse - -import ( - "errors" - "fmt" - "math/bits" -) - -const ( - /*!MEMORY_USAGE : - * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - * Increasing memory usage improves compression ratio - * Reduced memory usage can improve speed, due to cache effect - * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ - maxMemoryUsage = 14 - defaultMemoryUsage = 13 - - maxTableLog = maxMemoryUsage - 2 - maxTablesize = 1 << maxTableLog - defaultTablelog = defaultMemoryUsage - 2 - minTablelog = 5 - maxSymbolValue = 255 -) - -var ( - // ErrIncompressible is returned when input is judged to be too hard to compress. - ErrIncompressible = errors.New("input is not compressible") - - // ErrUseRLE is returned from the compressor when the input is a single byte value repeated. - ErrUseRLE = errors.New("input is single value repeated") -) - -// Scratch provides temporary storage for compression and decompression. -type Scratch struct { - // Private - count [maxSymbolValue + 1]uint32 - norm [maxSymbolValue + 1]int16 - br byteReader - bits bitReader - bw bitWriter - ct cTable // Compression tables. - decTable []decSymbol // Decompression table. - maxCount int // count of the most probable symbol - - // Per block parameters. - // These can be used to override compression parameters of the block. - // Do not touch, unless you know what you are doing. - - // Out is output buffer. - // If the scratch is re-used before the caller is done processing the output, - // set this field to nil. - // Otherwise the output buffer will be re-used for next Compression/Decompression step - // and allocation will be avoided. - Out []byte - - // DecompressLimit limits the maximum decoded size acceptable. - // If > 0 decompression will stop when approximately this many bytes - // has been decoded. - // If 0, maximum size will be 2GB. - DecompressLimit int - - symbolLen uint16 // Length of active part of the symbol table. - actualTableLog uint8 // Selected tablelog. - zeroBits bool // no bits has prob > 50%. - clearCount bool // clear count - - // MaxSymbolValue will override the maximum symbol value of the next block. - MaxSymbolValue uint8 - - // TableLog will attempt to override the tablelog for the next block. - TableLog uint8 -} - -// Histogram allows to populate the histogram and skip that step in the compression, -// It otherwise allows to inspect the histogram when compression is done. -// To indicate that you have populated the histogram call HistogramFinished -// with the value of the highest populated symbol, as well as the number of entries -// in the most populated entry. These are accepted at face value. -// The returned slice will always be length 256. -func (s *Scratch) Histogram() []uint32 { - return s.count[:] -} - -// HistogramFinished can be called to indicate that the histogram has been populated. -// maxSymbol is the index of the highest set symbol of the next data segment. -// maxCount is the number of entries in the most populated entry. -// These are accepted at face value. -func (s *Scratch) HistogramFinished(maxSymbol uint8, maxCount int) { - s.maxCount = maxCount - s.symbolLen = uint16(maxSymbol) + 1 - s.clearCount = maxCount != 0 -} - -// prepare will prepare and allocate scratch tables used for both compression and decompression. -func (s *Scratch) prepare(in []byte) (*Scratch, error) { - if s == nil { - s = &Scratch{} - } - if s.MaxSymbolValue == 0 { - s.MaxSymbolValue = 255 - } - if s.TableLog == 0 { - s.TableLog = defaultTablelog - } - if s.TableLog > maxTableLog { - return nil, fmt.Errorf("tableLog (%d) > maxTableLog (%d)", s.TableLog, maxTableLog) - } - if cap(s.Out) == 0 { - s.Out = make([]byte, 0, len(in)) - } - if s.clearCount && s.maxCount == 0 { - for i := range s.count { - s.count[i] = 0 - } - s.clearCount = false - } - s.br.init(in) - if s.DecompressLimit == 0 { - // Max size 2GB. - s.DecompressLimit = (2 << 30) - 1 - } - - return s, nil -} - -// tableStep returns the next table index. -func tableStep(tableSize uint32) uint32 { - return (tableSize >> 1) + (tableSize >> 3) + 3 -} - -func highBits(val uint32) (n uint32) { - return uint32(bits.Len32(val) - 1) -} diff --git a/vendor/github.com/klauspost/compress/gen.sh b/vendor/github.com/klauspost/compress/gen.sh deleted file mode 100644 index aff942205..000000000 --- a/vendor/github.com/klauspost/compress/gen.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -cd s2/cmd/_s2sx/ || exit 1 -go generate . diff --git a/vendor/github.com/klauspost/compress/huff0/.gitignore b/vendor/github.com/klauspost/compress/huff0/.gitignore deleted file mode 100644 index b3d262958..000000000 --- a/vendor/github.com/klauspost/compress/huff0/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/huff0-fuzz.zip diff --git a/vendor/github.com/klauspost/compress/huff0/README.md b/vendor/github.com/klauspost/compress/huff0/README.md deleted file mode 100644 index 8b6e5c663..000000000 --- a/vendor/github.com/klauspost/compress/huff0/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# Huff0 entropy compression - -This package provides Huff0 encoding and decoding as used in zstd. - -[Huff0](https://github.com/Cyan4973/FiniteStateEntropy#new-generation-entropy-coders), -a Huffman codec designed for modern CPU, featuring OoO (Out of Order) operations on multiple ALU -(Arithmetic Logic Unit), achieving extremely fast compression and decompression speeds. - -This can be used for compressing input with a lot of similar input values to the smallest number of bytes. -This does not perform any multi-byte [dictionary coding](https://en.wikipedia.org/wiki/Dictionary_coder) as LZ coders, -but it can be used as a secondary step to compressors (like Snappy) that does not do entropy encoding. - -* [Godoc documentation](https://godoc.org/github.com/klauspost/compress/huff0) - -## News - -This is used as part of the [zstandard](https://github.com/klauspost/compress/tree/master/zstd#zstd) compression and decompression package. - -This ensures that most functionality is well tested. - -# Usage - -This package provides a low level interface that allows to compress single independent blocks. - -Each block is separate, and there is no built in integrity checks. -This means that the caller should keep track of block sizes and also do checksums if needed. - -Compressing a block is done via the [`Compress1X`](https://godoc.org/github.com/klauspost/compress/huff0#Compress1X) and -[`Compress4X`](https://godoc.org/github.com/klauspost/compress/huff0#Compress4X) functions. -You must provide input and will receive the output and maybe an error. - -These error values can be returned: - -| Error | Description | -|---------------------|-----------------------------------------------------------------------------| -| `` | Everything ok, output is returned | -| `ErrIncompressible` | Returned when input is judged to be too hard to compress | -| `ErrUseRLE` | Returned from the compressor when the input is a single byte value repeated | -| `ErrTooBig` | Returned if the input block exceeds the maximum allowed size (128 Kib) | -| `(error)` | An internal error occurred. | - - -As can be seen above some of there are errors that will be returned even under normal operation so it is important to handle these. - -To reduce allocations you can provide a [`Scratch`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch) object -that can be re-used for successive calls. Both compression and decompression accepts a `Scratch` object, and the same -object can be used for both. - -Be aware, that when re-using a `Scratch` object that the *output* buffer is also re-used, so if you are still using this -you must set the `Out` field in the scratch to nil. The same buffer is used for compression and decompression output. - -The `Scratch` object will retain state that allows to re-use previous tables for encoding and decoding. - -## Tables and re-use - -Huff0 allows for reusing tables from the previous block to save space if that is expected to give better/faster results. - -The Scratch object allows you to set a [`ReusePolicy`](https://godoc.org/github.com/klauspost/compress/huff0#ReusePolicy) -that controls this behaviour. See the documentation for details. This can be altered between each block. - -Do however note that this information is *not* stored in the output block and it is up to the users of the package to -record whether [`ReadTable`](https://godoc.org/github.com/klauspost/compress/huff0#ReadTable) should be called, -based on the boolean reported back from the CompressXX call. - -If you want to store the table separate from the data, you can access them as `OutData` and `OutTable` on the -[`Scratch`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch) object. - -## Decompressing - -The first part of decoding is to initialize the decoding table through [`ReadTable`](https://godoc.org/github.com/klauspost/compress/huff0#ReadTable). -This will initialize the decoding tables. -You can supply the complete block to `ReadTable` and it will return the data part of the block -which can be given to the decompressor. - -Decompressing is done by calling the [`Decompress1X`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch.Decompress1X) -or [`Decompress4X`](https://godoc.org/github.com/klauspost/compress/huff0#Scratch.Decompress4X) function. - -For concurrently decompressing content with a fixed table a stateless [`Decoder`](https://godoc.org/github.com/klauspost/compress/huff0#Decoder) can be requested which will remain correct as long as the scratch is unchanged. The capacity of the provided slice indicates the expected output size. - -You must provide the output from the compression stage, at exactly the size you got back. If you receive an error back -your input was likely corrupted. - -It is important to note that a successful decoding does *not* mean your output matches your original input. -There are no integrity checks, so relying on errors from the decompressor does not assure your data is valid. - -# Contributing - -Contributions are always welcome. Be aware that adding public functions will require good justification and breaking -changes will likely not be accepted. If in doubt open an issue before writing the PR. diff --git a/vendor/github.com/klauspost/compress/huff0/bitreader.go b/vendor/github.com/klauspost/compress/huff0/bitreader.go deleted file mode 100644 index e36d9742f..000000000 --- a/vendor/github.com/klauspost/compress/huff0/bitreader.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package huff0 - -import ( - "encoding/binary" - "errors" - "fmt" - "io" -) - -// bitReader reads a bitstream in reverse. -// The last set bit indicates the start of the stream and is used -// for aligning the input. -type bitReaderBytes struct { - in []byte - off uint // next byte to read is at in[off - 1] - value uint64 - bitsRead uint8 -} - -// init initializes and resets the bit reader. -func (b *bitReaderBytes) init(in []byte) error { - if len(in) < 1 { - return errors.New("corrupt stream: too short") - } - b.in = in - b.off = uint(len(in)) - // The highest bit of the last byte indicates where to start - v := in[len(in)-1] - if v == 0 { - return errors.New("corrupt stream, did not find end of stream") - } - b.bitsRead = 64 - b.value = 0 - if len(in) >= 8 { - b.fillFastStart() - } else { - b.fill() - b.fill() - } - b.advance(8 - uint8(highBit32(uint32(v)))) - return nil -} - -// peekBitsFast requires that at least one bit is requested every time. -// There are no checks if the buffer is filled. -func (b *bitReaderBytes) peekByteFast() uint8 { - got := uint8(b.value >> 56) - return got -} - -func (b *bitReaderBytes) advance(n uint8) { - b.bitsRead += n - b.value <<= n & 63 -} - -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReaderBytes) fillFast() { - if b.bitsRead < 32 { - return - } - - // 2 bounds checks. - v := b.in[b.off-4 : b.off] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value |= uint64(low) << (b.bitsRead - 32) - b.bitsRead -= 32 - b.off -= 4 -} - -// fillFastStart() assumes the bitReaderBytes is empty and there is at least 8 bytes to read. -func (b *bitReaderBytes) fillFastStart() { - // Do single re-slice to avoid bounds checks. - b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) - b.bitsRead = 0 - b.off -= 8 -} - -// fill() will make sure at least 32 bits are available. -func (b *bitReaderBytes) fill() { - if b.bitsRead < 32 { - return - } - if b.off > 4 { - v := b.in[b.off-4 : b.off] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value |= uint64(low) << (b.bitsRead - 32) - b.bitsRead -= 32 - b.off -= 4 - return - } - for b.off > 0 { - b.value |= uint64(b.in[b.off-1]) << (b.bitsRead - 8) - b.bitsRead -= 8 - b.off-- - } -} - -// finished returns true if all bits have been read from the bit stream. -func (b *bitReaderBytes) finished() bool { - return b.off == 0 && b.bitsRead >= 64 -} - -func (b *bitReaderBytes) remaining() uint { - return b.off*8 + uint(64-b.bitsRead) -} - -// close the bitstream and returns an error if out-of-buffer reads occurred. -func (b *bitReaderBytes) close() error { - // Release reference. - b.in = nil - if b.remaining() > 0 { - return fmt.Errorf("corrupt input: %d bits remain on stream", b.remaining()) - } - if b.bitsRead > 64 { - return io.ErrUnexpectedEOF - } - return nil -} - -// bitReaderShifted reads a bitstream in reverse. -// The last set bit indicates the start of the stream and is used -// for aligning the input. -type bitReaderShifted struct { - in []byte - off uint // next byte to read is at in[off - 1] - value uint64 - bitsRead uint8 -} - -// init initializes and resets the bit reader. -func (b *bitReaderShifted) init(in []byte) error { - if len(in) < 1 { - return errors.New("corrupt stream: too short") - } - b.in = in - b.off = uint(len(in)) - // The highest bit of the last byte indicates where to start - v := in[len(in)-1] - if v == 0 { - return errors.New("corrupt stream, did not find end of stream") - } - b.bitsRead = 64 - b.value = 0 - if len(in) >= 8 { - b.fillFastStart() - } else { - b.fill() - b.fill() - } - b.advance(8 - uint8(highBit32(uint32(v)))) - return nil -} - -// peekBitsFast requires that at least one bit is requested every time. -// There are no checks if the buffer is filled. -func (b *bitReaderShifted) peekBitsFast(n uint8) uint16 { - return uint16(b.value >> ((64 - n) & 63)) -} - -func (b *bitReaderShifted) advance(n uint8) { - b.bitsRead += n - b.value <<= n & 63 -} - -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReaderShifted) fillFast() { - if b.bitsRead < 32 { - return - } - - // 2 bounds checks. - v := b.in[b.off-4 : b.off] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value |= uint64(low) << ((b.bitsRead - 32) & 63) - b.bitsRead -= 32 - b.off -= 4 -} - -// fillFastStart() assumes the bitReaderShifted is empty and there is at least 8 bytes to read. -func (b *bitReaderShifted) fillFastStart() { - // Do single re-slice to avoid bounds checks. - b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) - b.bitsRead = 0 - b.off -= 8 -} - -// fill() will make sure at least 32 bits are available. -func (b *bitReaderShifted) fill() { - if b.bitsRead < 32 { - return - } - if b.off > 4 { - v := b.in[b.off-4 : b.off] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value |= uint64(low) << ((b.bitsRead - 32) & 63) - b.bitsRead -= 32 - b.off -= 4 - return - } - for b.off > 0 { - b.value |= uint64(b.in[b.off-1]) << ((b.bitsRead - 8) & 63) - b.bitsRead -= 8 - b.off-- - } -} - -func (b *bitReaderShifted) remaining() uint { - return b.off*8 + uint(64-b.bitsRead) -} - -// close the bitstream and returns an error if out-of-buffer reads occurred. -func (b *bitReaderShifted) close() error { - // Release reference. - b.in = nil - if b.remaining() > 0 { - return fmt.Errorf("corrupt input: %d bits remain on stream", b.remaining()) - } - if b.bitsRead > 64 { - return io.ErrUnexpectedEOF - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/huff0/bitwriter.go b/vendor/github.com/klauspost/compress/huff0/bitwriter.go deleted file mode 100644 index 0ebc9aaac..000000000 --- a/vendor/github.com/klauspost/compress/huff0/bitwriter.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package huff0 - -// bitWriter will write bits. -// First bit will be LSB of the first byte of output. -type bitWriter struct { - bitContainer uint64 - nBits uint8 - out []byte -} - -// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// encSymbol will add up to 16 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) encSymbol(ct cTable, symbol byte) { - enc := ct[symbol] - b.bitContainer |= uint64(enc.val) << (b.nBits & 63) - if false { - if enc.nBits == 0 { - panic("nbits 0") - } - } - b.nBits += enc.nBits -} - -// encTwoSymbols will add up to 32 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) encTwoSymbols(ct cTable, av, bv byte) { - encA := ct[av] - encB := ct[bv] - sh := b.nBits & 63 - combined := uint64(encA.val) | (uint64(encB.val) << (encA.nBits & 63)) - b.bitContainer |= combined << sh - if false { - if encA.nBits == 0 { - panic("nbitsA 0") - } - if encB.nBits == 0 { - panic("nbitsB 0") - } - } - b.nBits += encA.nBits + encB.nBits -} - -// encFourSymbols adds up to 32 bits from four symbols. -// It will not check if there is space for them, -// so the caller must ensure that b has been flushed recently. -func (b *bitWriter) encFourSymbols(encA, encB, encC, encD cTableEntry) { - bitsA := encA.nBits - bitsB := bitsA + encB.nBits - bitsC := bitsB + encC.nBits - bitsD := bitsC + encD.nBits - combined := uint64(encA.val) | - (uint64(encB.val) << (bitsA & 63)) | - (uint64(encC.val) << (bitsB & 63)) | - (uint64(encD.val) << (bitsC & 63)) - b.bitContainer |= combined << (b.nBits & 63) - b.nBits += bitsD -} - -// flush32 will flush out, so there are at least 32 bits available for writing. -func (b *bitWriter) flush32() { - if b.nBits < 32 { - return - } - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24)) - b.nBits -= 32 - b.bitContainer >>= 32 -} - -// flushAlign will flush remaining full bytes and align to next byte boundary. -func (b *bitWriter) flushAlign() { - nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { - b.out = append(b.out, byte(b.bitContainer>>(i*8))) - } - b.nBits = 0 - b.bitContainer = 0 -} - -// close will write the alignment bit and write the final byte(s) -// to the output. -func (b *bitWriter) close() { - // End mark - b.addBits16Clean(1, 1) - // flush until next byte. - b.flushAlign() -} diff --git a/vendor/github.com/klauspost/compress/huff0/compress.go b/vendor/github.com/klauspost/compress/huff0/compress.go deleted file mode 100644 index 84aa3d12f..000000000 --- a/vendor/github.com/klauspost/compress/huff0/compress.go +++ /dev/null @@ -1,742 +0,0 @@ -package huff0 - -import ( - "fmt" - "math" - "runtime" - "sync" -) - -// Compress1X will compress the input. -// The output can be decoded using Decompress1X. -// Supply a Scratch object. The scratch object contains state about re-use, -// So when sharing across independent encodes, be sure to set the re-use policy. -func Compress1X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) { - s, err = s.prepare(in) - if err != nil { - return nil, false, err - } - return compress(in, s, s.compress1X) -} - -// Compress4X will compress the input. The input is split into 4 independent blocks -// and compressed similar to Compress1X. -// The output can be decoded using Decompress4X. -// Supply a Scratch object. The scratch object contains state about re-use, -// So when sharing across independent encodes, be sure to set the re-use policy. -func Compress4X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) { - s, err = s.prepare(in) - if err != nil { - return nil, false, err - } - if false { - // TODO: compress4Xp only slightly faster. - const parallelThreshold = 8 << 10 - if len(in) < parallelThreshold || runtime.GOMAXPROCS(0) == 1 { - return compress(in, s, s.compress4X) - } - return compress(in, s, s.compress4Xp) - } - return compress(in, s, s.compress4X) -} - -func compress(in []byte, s *Scratch, compressor func(src []byte) ([]byte, error)) (out []byte, reUsed bool, err error) { - // Nuke previous table if we cannot reuse anyway. - if s.Reuse == ReusePolicyNone { - s.prevTable = s.prevTable[:0] - } - - // Create histogram, if none was provided. - maxCount := s.maxCount - var canReuse = false - if maxCount == 0 { - maxCount, canReuse = s.countSimple(in) - } else { - canReuse = s.canUseTable(s.prevTable) - } - - // We want the output size to be less than this: - wantSize := len(in) - if s.WantLogLess > 0 { - wantSize -= wantSize >> s.WantLogLess - } - - // Reset for next run. - s.clearCount = true - s.maxCount = 0 - if maxCount >= len(in) { - if maxCount > len(in) { - return nil, false, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in)) - } - if len(in) == 1 { - return nil, false, ErrIncompressible - } - // One symbol, use RLE - return nil, false, ErrUseRLE - } - if maxCount == 1 || maxCount < (len(in)>>7) { - // Each symbol present maximum once or too well distributed. - return nil, false, ErrIncompressible - } - if s.Reuse == ReusePolicyMust && !canReuse { - // We must reuse, but we can't. - return nil, false, ErrIncompressible - } - if (s.Reuse == ReusePolicyPrefer || s.Reuse == ReusePolicyMust) && canReuse { - keepTable := s.cTable - keepTL := s.actualTableLog - s.cTable = s.prevTable - s.actualTableLog = s.prevTableLog - s.Out, err = compressor(in) - s.cTable = keepTable - s.actualTableLog = keepTL - if err == nil && len(s.Out) < wantSize { - s.OutData = s.Out - return s.Out, true, nil - } - if s.Reuse == ReusePolicyMust { - return nil, false, ErrIncompressible - } - // Do not attempt to re-use later. - s.prevTable = s.prevTable[:0] - } - - // Calculate new table. - err = s.buildCTable() - if err != nil { - return nil, false, err - } - - if false && !s.canUseTable(s.cTable) { - panic("invalid table generated") - } - - if s.Reuse == ReusePolicyAllow && canReuse { - hSize := len(s.Out) - oldSize := s.prevTable.estimateSize(s.count[:s.symbolLen]) - newSize := s.cTable.estimateSize(s.count[:s.symbolLen]) - if oldSize <= hSize+newSize || hSize+12 >= wantSize { - // Retain cTable even if we re-use. - keepTable := s.cTable - keepTL := s.actualTableLog - - s.cTable = s.prevTable - s.actualTableLog = s.prevTableLog - s.Out, err = compressor(in) - - // Restore ctable. - s.cTable = keepTable - s.actualTableLog = keepTL - if err != nil { - return nil, false, err - } - if len(s.Out) >= wantSize { - return nil, false, ErrIncompressible - } - s.OutData = s.Out - return s.Out, true, nil - } - } - - // Use new table - err = s.cTable.write(s) - if err != nil { - s.OutTable = nil - return nil, false, err - } - s.OutTable = s.Out - - // Compress using new table - s.Out, err = compressor(in) - if err != nil { - s.OutTable = nil - return nil, false, err - } - if len(s.Out) >= wantSize { - s.OutTable = nil - return nil, false, ErrIncompressible - } - // Move current table into previous. - s.prevTable, s.prevTableLog, s.cTable = s.cTable, s.actualTableLog, s.prevTable[:0] - s.OutData = s.Out[len(s.OutTable):] - return s.Out, false, nil -} - -// EstimateSizes will estimate the data sizes -func EstimateSizes(in []byte, s *Scratch) (tableSz, dataSz, reuseSz int, err error) { - s, err = s.prepare(in) - if err != nil { - return 0, 0, 0, err - } - - // Create histogram, if none was provided. - tableSz, dataSz, reuseSz = -1, -1, -1 - maxCount := s.maxCount - var canReuse = false - if maxCount == 0 { - maxCount, canReuse = s.countSimple(in) - } else { - canReuse = s.canUseTable(s.prevTable) - } - - // We want the output size to be less than this: - wantSize := len(in) - if s.WantLogLess > 0 { - wantSize -= wantSize >> s.WantLogLess - } - - // Reset for next run. - s.clearCount = true - s.maxCount = 0 - if maxCount >= len(in) { - if maxCount > len(in) { - return 0, 0, 0, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in)) - } - if len(in) == 1 { - return 0, 0, 0, ErrIncompressible - } - // One symbol, use RLE - return 0, 0, 0, ErrUseRLE - } - if maxCount == 1 || maxCount < (len(in)>>7) { - // Each symbol present maximum once or too well distributed. - return 0, 0, 0, ErrIncompressible - } - - // Calculate new table. - err = s.buildCTable() - if err != nil { - return 0, 0, 0, err - } - - if false && !s.canUseTable(s.cTable) { - panic("invalid table generated") - } - - tableSz, err = s.cTable.estTableSize(s) - if err != nil { - return 0, 0, 0, err - } - if canReuse { - reuseSz = s.prevTable.estimateSize(s.count[:s.symbolLen]) - } - dataSz = s.cTable.estimateSize(s.count[:s.symbolLen]) - - // Restore - return tableSz, dataSz, reuseSz, nil -} - -func (s *Scratch) compress1X(src []byte) ([]byte, error) { - return s.compress1xDo(s.Out, src), nil -} - -func (s *Scratch) compress1xDo(dst, src []byte) []byte { - var bw = bitWriter{out: dst} - - // N is length divisible by 4. - n := len(src) - n -= n & 3 - cTable := s.cTable[:256] - - // Encode last bytes. - for i := len(src) & 3; i > 0; i-- { - bw.encSymbol(cTable, src[n+i-1]) - } - n -= 4 - if s.actualTableLog <= 8 { - for ; n >= 0; n -= 4 { - tmp := src[n : n+4] - // tmp should be len 4 - bw.flush32() - bw.encFourSymbols(cTable[tmp[3]], cTable[tmp[2]], cTable[tmp[1]], cTable[tmp[0]]) - } - } else { - for ; n >= 0; n -= 4 { - tmp := src[n : n+4] - // tmp should be len 4 - bw.flush32() - bw.encTwoSymbols(cTable, tmp[3], tmp[2]) - bw.flush32() - bw.encTwoSymbols(cTable, tmp[1], tmp[0]) - } - } - bw.close() - return bw.out -} - -var sixZeros [6]byte - -func (s *Scratch) compress4X(src []byte) ([]byte, error) { - if len(src) < 12 { - return nil, ErrIncompressible - } - segmentSize := (len(src) + 3) / 4 - - // Add placeholder for output length - offsetIdx := len(s.Out) - s.Out = append(s.Out, sixZeros[:]...) - - for i := 0; i < 4; i++ { - toDo := src - if len(toDo) > segmentSize { - toDo = toDo[:segmentSize] - } - src = src[len(toDo):] - - idx := len(s.Out) - s.Out = s.compress1xDo(s.Out, toDo) - if len(s.Out)-idx > math.MaxUint16 { - // We cannot store the size in the jump table - return nil, ErrIncompressible - } - // Write compressed length as little endian before block. - if i < 3 { - // Last length is not written. - length := len(s.Out) - idx - s.Out[i*2+offsetIdx] = byte(length) - s.Out[i*2+offsetIdx+1] = byte(length >> 8) - } - } - - return s.Out, nil -} - -// compress4Xp will compress 4 streams using separate goroutines. -func (s *Scratch) compress4Xp(src []byte) ([]byte, error) { - if len(src) < 12 { - return nil, ErrIncompressible - } - // Add placeholder for output length - s.Out = s.Out[:6] - - segmentSize := (len(src) + 3) / 4 - var wg sync.WaitGroup - wg.Add(4) - for i := 0; i < 4; i++ { - toDo := src - if len(toDo) > segmentSize { - toDo = toDo[:segmentSize] - } - src = src[len(toDo):] - - // Separate goroutine for each block. - go func(i int) { - s.tmpOut[i] = s.compress1xDo(s.tmpOut[i][:0], toDo) - wg.Done() - }(i) - } - wg.Wait() - for i := 0; i < 4; i++ { - o := s.tmpOut[i] - if len(o) > math.MaxUint16 { - // We cannot store the size in the jump table - return nil, ErrIncompressible - } - // Write compressed length as little endian before block. - if i < 3 { - // Last length is not written. - s.Out[i*2] = byte(len(o)) - s.Out[i*2+1] = byte(len(o) >> 8) - } - - // Write output. - s.Out = append(s.Out, o...) - } - return s.Out, nil -} - -// countSimple will create a simple histogram in s.count. -// Returns the biggest count. -// Does not update s.clearCount. -func (s *Scratch) countSimple(in []byte) (max int, reuse bool) { - reuse = true - _ = s.count // Assert that s != nil to speed up the following loop. - for _, v := range in { - s.count[v]++ - } - m := uint32(0) - if len(s.prevTable) > 0 { - for i, v := range s.count[:] { - if v == 0 { - continue - } - if v > m { - m = v - } - s.symbolLen = uint16(i) + 1 - if i >= len(s.prevTable) { - reuse = false - } else if s.prevTable[i].nBits == 0 { - reuse = false - } - } - return int(m), reuse - } - for i, v := range s.count[:] { - if v == 0 { - continue - } - if v > m { - m = v - } - s.symbolLen = uint16(i) + 1 - } - return int(m), false -} - -func (s *Scratch) canUseTable(c cTable) bool { - if len(c) < int(s.symbolLen) { - return false - } - for i, v := range s.count[:s.symbolLen] { - if v != 0 && c[i].nBits == 0 { - return false - } - } - return true -} - -//lint:ignore U1000 used for debugging -func (s *Scratch) validateTable(c cTable) bool { - if len(c) < int(s.symbolLen) { - return false - } - for i, v := range s.count[:s.symbolLen] { - if v != 0 { - if c[i].nBits == 0 { - return false - } - if c[i].nBits > s.actualTableLog { - return false - } - } - } - return true -} - -// minTableLog provides the minimum logSize to safely represent a distribution. -func (s *Scratch) minTableLog() uint8 { - minBitsSrc := highBit32(uint32(s.srcLen)) + 1 - minBitsSymbols := highBit32(uint32(s.symbolLen-1)) + 2 - if minBitsSrc < minBitsSymbols { - return uint8(minBitsSrc) - } - return uint8(minBitsSymbols) -} - -// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog -func (s *Scratch) optimalTableLog() { - tableLog := s.TableLog - minBits := s.minTableLog() - maxBitsSrc := uint8(highBit32(uint32(s.srcLen-1))) - 1 - if maxBitsSrc < tableLog { - // Accuracy can be reduced - tableLog = maxBitsSrc - } - if minBits > tableLog { - tableLog = minBits - } - // Need a minimum to safely represent all symbol values - if tableLog < minTablelog { - tableLog = minTablelog - } - if tableLog > tableLogMax { - tableLog = tableLogMax - } - s.actualTableLog = tableLog -} - -type cTableEntry struct { - val uint16 - nBits uint8 - // We have 8 bits extra -} - -const huffNodesMask = huffNodesLen - 1 - -func (s *Scratch) buildCTable() error { - s.optimalTableLog() - s.huffSort() - if cap(s.cTable) < maxSymbolValue+1 { - s.cTable = make([]cTableEntry, s.symbolLen, maxSymbolValue+1) - } else { - s.cTable = s.cTable[:s.symbolLen] - for i := range s.cTable { - s.cTable[i] = cTableEntry{} - } - } - - var startNode = int16(s.symbolLen) - nonNullRank := s.symbolLen - 1 - - nodeNb := startNode - huffNode := s.nodes[1 : huffNodesLen+1] - - // This overlays the slice above, but allows "-1" index lookups. - // Different from reference implementation. - huffNode0 := s.nodes[0 : huffNodesLen+1] - - for huffNode[nonNullRank].count() == 0 { - nonNullRank-- - } - - lowS := int16(nonNullRank) - nodeRoot := nodeNb + lowS - 1 - lowN := nodeNb - huffNode[nodeNb].setCount(huffNode[lowS].count() + huffNode[lowS-1].count()) - huffNode[lowS].setParent(nodeNb) - huffNode[lowS-1].setParent(nodeNb) - nodeNb++ - lowS -= 2 - for n := nodeNb; n <= nodeRoot; n++ { - huffNode[n].setCount(1 << 30) - } - // fake entry, strong barrier - huffNode0[0].setCount(1 << 31) - - // create parents - for nodeNb <= nodeRoot { - var n1, n2 int16 - if huffNode0[lowS+1].count() < huffNode0[lowN+1].count() { - n1 = lowS - lowS-- - } else { - n1 = lowN - lowN++ - } - if huffNode0[lowS+1].count() < huffNode0[lowN+1].count() { - n2 = lowS - lowS-- - } else { - n2 = lowN - lowN++ - } - - huffNode[nodeNb].setCount(huffNode0[n1+1].count() + huffNode0[n2+1].count()) - huffNode0[n1+1].setParent(nodeNb) - huffNode0[n2+1].setParent(nodeNb) - nodeNb++ - } - - // distribute weights (unlimited tree height) - huffNode[nodeRoot].setNbBits(0) - for n := nodeRoot - 1; n >= startNode; n-- { - huffNode[n].setNbBits(huffNode[huffNode[n].parent()].nbBits() + 1) - } - for n := uint16(0); n <= nonNullRank; n++ { - huffNode[n].setNbBits(huffNode[huffNode[n].parent()].nbBits() + 1) - } - s.actualTableLog = s.setMaxHeight(int(nonNullRank)) - maxNbBits := s.actualTableLog - - // fill result into tree (val, nbBits) - if maxNbBits > tableLogMax { - return fmt.Errorf("internal error: maxNbBits (%d) > tableLogMax (%d)", maxNbBits, tableLogMax) - } - var nbPerRank [tableLogMax + 1]uint16 - var valPerRank [16]uint16 - for _, v := range huffNode[:nonNullRank+1] { - nbPerRank[v.nbBits()]++ - } - // determine stating value per rank - { - min := uint16(0) - for n := maxNbBits; n > 0; n-- { - // get starting value within each rank - valPerRank[n] = min - min += nbPerRank[n] - min >>= 1 - } - } - - // push nbBits per symbol, symbol order - for _, v := range huffNode[:nonNullRank+1] { - s.cTable[v.symbol()].nBits = v.nbBits() - } - - // assign value within rank, symbol order - t := s.cTable[:s.symbolLen] - for n, val := range t { - nbits := val.nBits & 15 - v := valPerRank[nbits] - t[n].val = v - valPerRank[nbits] = v + 1 - } - - return nil -} - -// huffSort will sort symbols, decreasing order. -func (s *Scratch) huffSort() { - type rankPos struct { - base uint32 - current uint32 - } - - // Clear nodes - nodes := s.nodes[:huffNodesLen+1] - s.nodes = nodes - nodes = nodes[1 : huffNodesLen+1] - - // Sort into buckets based on length of symbol count. - var rank [32]rankPos - for _, v := range s.count[:s.symbolLen] { - r := highBit32(v+1) & 31 - rank[r].base++ - } - // maxBitLength is log2(BlockSizeMax) + 1 - const maxBitLength = 18 + 1 - for n := maxBitLength; n > 0; n-- { - rank[n-1].base += rank[n].base - } - for n := range rank[:maxBitLength] { - rank[n].current = rank[n].base - } - for n, c := range s.count[:s.symbolLen] { - r := (highBit32(c+1) + 1) & 31 - pos := rank[r].current - rank[r].current++ - prev := nodes[(pos-1)&huffNodesMask] - for pos > rank[r].base && c > prev.count() { - nodes[pos&huffNodesMask] = prev - pos-- - prev = nodes[(pos-1)&huffNodesMask] - } - nodes[pos&huffNodesMask] = makeNodeElt(c, byte(n)) - } -} - -func (s *Scratch) setMaxHeight(lastNonNull int) uint8 { - maxNbBits := s.actualTableLog - huffNode := s.nodes[1 : huffNodesLen+1] - //huffNode = huffNode[: huffNodesLen] - - largestBits := huffNode[lastNonNull].nbBits() - - // early exit : no elt > maxNbBits - if largestBits <= maxNbBits { - return largestBits - } - totalCost := int(0) - baseCost := int(1) << (largestBits - maxNbBits) - n := uint32(lastNonNull) - - for huffNode[n].nbBits() > maxNbBits { - totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits())) - huffNode[n].setNbBits(maxNbBits) - n-- - } - // n stops at huffNode[n].nbBits <= maxNbBits - - for huffNode[n].nbBits() == maxNbBits { - n-- - } - // n end at index of smallest symbol using < maxNbBits - - // renorm totalCost - totalCost >>= largestBits - maxNbBits /* note : totalCost is necessarily a multiple of baseCost */ - - // repay normalized cost - { - const noSymbol = 0xF0F0F0F0 - var rankLast [tableLogMax + 2]uint32 - - for i := range rankLast[:] { - rankLast[i] = noSymbol - } - - // Get pos of last (smallest) symbol per rank - { - currentNbBits := maxNbBits - for pos := int(n); pos >= 0; pos-- { - if huffNode[pos].nbBits() >= currentNbBits { - continue - } - currentNbBits = huffNode[pos].nbBits() // < maxNbBits - rankLast[maxNbBits-currentNbBits] = uint32(pos) - } - } - - for totalCost > 0 { - nBitsToDecrease := uint8(highBit32(uint32(totalCost))) + 1 - - for ; nBitsToDecrease > 1; nBitsToDecrease-- { - highPos := rankLast[nBitsToDecrease] - lowPos := rankLast[nBitsToDecrease-1] - if highPos == noSymbol { - continue - } - if lowPos == noSymbol { - break - } - highTotal := huffNode[highPos].count() - lowTotal := 2 * huffNode[lowPos].count() - if highTotal <= lowTotal { - break - } - } - // only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) - // HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary - // FIXME: try to remove - for (nBitsToDecrease <= tableLogMax) && (rankLast[nBitsToDecrease] == noSymbol) { - nBitsToDecrease++ - } - totalCost -= 1 << (nBitsToDecrease - 1) - if rankLast[nBitsToDecrease-1] == noSymbol { - // this rank is no longer empty - rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease] - } - huffNode[rankLast[nBitsToDecrease]].setNbBits(1 + - huffNode[rankLast[nBitsToDecrease]].nbBits()) - if rankLast[nBitsToDecrease] == 0 { - /* special case, reached largest symbol */ - rankLast[nBitsToDecrease] = noSymbol - } else { - rankLast[nBitsToDecrease]-- - if huffNode[rankLast[nBitsToDecrease]].nbBits() != maxNbBits-nBitsToDecrease { - rankLast[nBitsToDecrease] = noSymbol /* this rank is now empty */ - } - } - } - - for totalCost < 0 { /* Sometimes, cost correction overshoot */ - if rankLast[1] == noSymbol { /* special case : no rank 1 symbol (using maxNbBits-1); let's create one from largest rank 0 (using maxNbBits) */ - for huffNode[n].nbBits() == maxNbBits { - n-- - } - huffNode[n+1].setNbBits(huffNode[n+1].nbBits() - 1) - rankLast[1] = n + 1 - totalCost++ - continue - } - huffNode[rankLast[1]+1].setNbBits(huffNode[rankLast[1]+1].nbBits() - 1) - rankLast[1]++ - totalCost++ - } - } - return maxNbBits -} - -// A nodeElt is the fields -// -// count uint32 -// parent uint16 -// symbol byte -// nbBits uint8 -// -// in some order, all squashed into an integer so that the compiler -// always loads and stores entire nodeElts instead of separate fields. -type nodeElt uint64 - -func makeNodeElt(count uint32, symbol byte) nodeElt { - return nodeElt(count) | nodeElt(symbol)<<48 -} - -func (e *nodeElt) count() uint32 { return uint32(*e) } -func (e *nodeElt) parent() uint16 { return uint16(*e >> 32) } -func (e *nodeElt) symbol() byte { return byte(*e >> 48) } -func (e *nodeElt) nbBits() uint8 { return uint8(*e >> 56) } - -func (e *nodeElt) setCount(c uint32) { *e = (*e)&0xffffffff00000000 | nodeElt(c) } -func (e *nodeElt) setParent(p int16) { *e = (*e)&0xffff0000ffffffff | nodeElt(uint16(p))<<32 } -func (e *nodeElt) setNbBits(n uint8) { *e = (*e)&0x00ffffffffffffff | nodeElt(n)<<56 } diff --git a/vendor/github.com/klauspost/compress/huff0/decompress.go b/vendor/github.com/klauspost/compress/huff0/decompress.go deleted file mode 100644 index 54bd08b25..000000000 --- a/vendor/github.com/klauspost/compress/huff0/decompress.go +++ /dev/null @@ -1,1167 +0,0 @@ -package huff0 - -import ( - "errors" - "fmt" - "io" - "sync" - - "github.com/klauspost/compress/fse" -) - -type dTable struct { - single []dEntrySingle -} - -// single-symbols decoding -type dEntrySingle struct { - entry uint16 -} - -// Uses special code for all tables that are < 8 bits. -const use8BitTables = true - -// ReadTable will read a table from the input. -// The size of the input may be larger than the table definition. -// Any content remaining after the table definition will be returned. -// If no Scratch is provided a new one is allocated. -// The returned Scratch can be used for encoding or decoding input using this table. -func ReadTable(in []byte, s *Scratch) (s2 *Scratch, remain []byte, err error) { - s, err = s.prepare(nil) - if err != nil { - return s, nil, err - } - if len(in) <= 1 { - return s, nil, errors.New("input too small for table") - } - iSize := in[0] - in = in[1:] - if iSize >= 128 { - // Uncompressed - oSize := iSize - 127 - iSize = (oSize + 1) / 2 - if int(iSize) > len(in) { - return s, nil, errors.New("input too small for table") - } - for n := uint8(0); n < oSize; n += 2 { - v := in[n/2] - s.huffWeight[n] = v >> 4 - s.huffWeight[n+1] = v & 15 - } - s.symbolLen = uint16(oSize) - in = in[iSize:] - } else { - if len(in) < int(iSize) { - return s, nil, fmt.Errorf("input too small for table, want %d bytes, have %d", iSize, len(in)) - } - // FSE compressed weights - s.fse.DecompressLimit = 255 - hw := s.huffWeight[:] - s.fse.Out = hw - b, err := fse.Decompress(in[:iSize], s.fse) - s.fse.Out = nil - if err != nil { - return s, nil, fmt.Errorf("fse decompress returned: %w", err) - } - if len(b) > 255 { - return s, nil, errors.New("corrupt input: output table too large") - } - s.symbolLen = uint16(len(b)) - in = in[iSize:] - } - - // collect weight stats - var rankStats [16]uint32 - weightTotal := uint32(0) - for _, v := range s.huffWeight[:s.symbolLen] { - if v > tableLogMax { - return s, nil, errors.New("corrupt input: weight too large") - } - v2 := v & 15 - rankStats[v2]++ - // (1 << (v2-1)) is slower since the compiler cannot prove that v2 isn't 0. - weightTotal += (1 << v2) >> 1 - } - if weightTotal == 0 { - return s, nil, errors.New("corrupt input: weights zero") - } - - // get last non-null symbol weight (implied, total must be 2^n) - { - tableLog := highBit32(weightTotal) + 1 - if tableLog > tableLogMax { - return s, nil, errors.New("corrupt input: tableLog too big") - } - s.actualTableLog = uint8(tableLog) - // determine last weight - { - total := uint32(1) << tableLog - rest := total - weightTotal - verif := uint32(1) << highBit32(rest) - lastWeight := highBit32(rest) + 1 - if verif != rest { - // last value must be a clean power of 2 - return s, nil, errors.New("corrupt input: last value not power of two") - } - s.huffWeight[s.symbolLen] = uint8(lastWeight) - s.symbolLen++ - rankStats[lastWeight]++ - } - } - - if (rankStats[1] < 2) || (rankStats[1]&1 != 0) { - // by construction : at least 2 elts of rank 1, must be even - return s, nil, errors.New("corrupt input: min elt size, even check failed ") - } - - // TODO: Choose between single/double symbol decoding - - // Calculate starting value for each rank - { - var nextRankStart uint32 - for n := uint8(1); n < s.actualTableLog+1; n++ { - current := nextRankStart - nextRankStart += rankStats[n] << (n - 1) - rankStats[n] = current - } - } - - // fill DTable (always full size) - tSize := 1 << tableLogMax - if len(s.dt.single) != tSize { - s.dt.single = make([]dEntrySingle, tSize) - } - cTable := s.prevTable - if cap(cTable) < maxSymbolValue+1 { - cTable = make([]cTableEntry, 0, maxSymbolValue+1) - } - cTable = cTable[:maxSymbolValue+1] - s.prevTable = cTable[:s.symbolLen] - s.prevTableLog = s.actualTableLog - - for n, w := range s.huffWeight[:s.symbolLen] { - if w == 0 { - cTable[n] = cTableEntry{ - val: 0, - nBits: 0, - } - continue - } - length := (uint32(1) << w) >> 1 - d := dEntrySingle{ - entry: uint16(s.actualTableLog+1-w) | (uint16(n) << 8), - } - - rank := &rankStats[w] - cTable[n] = cTableEntry{ - val: uint16(*rank >> (w - 1)), - nBits: uint8(d.entry), - } - - single := s.dt.single[*rank : *rank+length] - for i := range single { - single[i] = d - } - *rank += length - } - - return s, in, nil -} - -// Decompress1X will decompress a 1X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// Before this is called, the table must be initialized with ReadTable unless -// the encoder re-used the table. -// deprecated: Use the stateless Decoder() to get a concurrent version. -func (s *Scratch) Decompress1X(in []byte) (out []byte, err error) { - if cap(s.Out) < s.MaxDecodedSize { - s.Out = make([]byte, s.MaxDecodedSize) - } - s.Out = s.Out[:0:s.MaxDecodedSize] - s.Out, err = s.Decoder().Decompress1X(s.Out, in) - return s.Out, err -} - -// Decompress4X will decompress a 4X encoded stream. -// Before this is called, the table must be initialized with ReadTable unless -// the encoder re-used the table. -// The length of the supplied input must match the end of a block exactly. -// The destination size of the uncompressed data must be known and provided. -// deprecated: Use the stateless Decoder() to get a concurrent version. -func (s *Scratch) Decompress4X(in []byte, dstSize int) (out []byte, err error) { - if dstSize > s.MaxDecodedSize { - return nil, ErrMaxDecodedSizeExceeded - } - if cap(s.Out) < dstSize { - s.Out = make([]byte, s.MaxDecodedSize) - } - s.Out = s.Out[:0:dstSize] - s.Out, err = s.Decoder().Decompress4X(s.Out, in) - return s.Out, err -} - -// Decoder will return a stateless decoder that can be used by multiple -// decompressors concurrently. -// Before this is called, the table must be initialized with ReadTable. -// The Decoder is still linked to the scratch buffer so that cannot be reused. -// However, it is safe to discard the scratch. -func (s *Scratch) Decoder() *Decoder { - return &Decoder{ - dt: s.dt, - actualTableLog: s.actualTableLog, - bufs: &s.decPool, - } -} - -// Decoder provides stateless decoding. -type Decoder struct { - dt dTable - actualTableLog uint8 - bufs *sync.Pool -} - -func (d *Decoder) buffer() *[4][256]byte { - buf, ok := d.bufs.Get().(*[4][256]byte) - if ok { - return buf - } - return &[4][256]byte{} -} - -// decompress1X8Bit will decompress a 1X encoded stream with tablelog <= 8. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) decompress1X8Bit(dst, src []byte) ([]byte, error) { - if d.actualTableLog == 8 { - return d.decompress1X8BitExactly(dst, src) - } - var br bitReaderBytes - err := br.init(src) - if err != nil { - return dst, err - } - maxDecodedSize := cap(dst) - dst = dst[:0] - - // Avoid bounds check by always having full sized table. - dt := d.dt.single[:256] - - // Use temp table to avoid bound checks/append penalty. - bufs := d.buffer() - buf := &bufs[0] - var off uint8 - - switch d.actualTableLog { - case 8: - const shift = 0 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - br.close() - d.bufs.Put(bufs) - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 7: - const shift = 8 - 7 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - br.close() - d.bufs.Put(bufs) - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 6: - const shift = 8 - 6 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 5: - const shift = 8 - 5 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 4: - const shift = 8 - 4 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 3: - const shift = 8 - 3 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 2: - const shift = 8 - 2 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - case 1: - const shift = 8 - 1 - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>(56+shift))] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - default: - d.bufs.Put(bufs) - return nil, fmt.Errorf("invalid tablelog: %d", d.actualTableLog) - } - - if len(dst)+int(off) > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:off]...) - - // br < 4, so uint8 is fine - bitsLeft := int8(uint8(br.off)*8 + (64 - br.bitsRead)) - shift := (8 - d.actualTableLog) & 7 - - for bitsLeft > 0 { - if br.bitsRead >= 64-8 { - for br.off > 0 { - br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) - br.bitsRead -= 8 - br.off-- - } - } - if len(dst) >= maxDecodedSize { - br.close() - d.bufs.Put(bufs) - return nil, ErrMaxDecodedSizeExceeded - } - v := dt[br.peekByteFast()>>shift] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= int8(nBits) - dst = append(dst, uint8(v.entry>>8)) - } - d.bufs.Put(bufs) - return dst, br.close() -} - -// decompress1X8Bit will decompress a 1X encoded stream with tablelog <= 8. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) decompress1X8BitExactly(dst, src []byte) ([]byte, error) { - var br bitReaderBytes - err := br.init(src) - if err != nil { - return dst, err - } - maxDecodedSize := cap(dst) - dst = dst[:0] - - // Avoid bounds check by always having full sized table. - dt := d.dt.single[:256] - - // Use temp table to avoid bound checks/append penalty. - bufs := d.buffer() - buf := &bufs[0] - var off uint8 - - const shift = 56 - - //fmt.Printf("mask: %b, tl:%d\n", mask, d.actualTableLog) - for br.off >= 4 { - br.fillFast() - v := dt[uint8(br.value>>shift)] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>shift)] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>shift)] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[uint8(br.value>>shift)] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - - if len(dst)+int(off) > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:off]...) - - // br < 4, so uint8 is fine - bitsLeft := int8(uint8(br.off)*8 + (64 - br.bitsRead)) - for bitsLeft > 0 { - if br.bitsRead >= 64-8 { - for br.off > 0 { - br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) - br.bitsRead -= 8 - br.off-- - } - } - if len(dst) >= maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - v := dt[br.peekByteFast()] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= int8(nBits) - dst = append(dst, uint8(v.entry>>8)) - } - d.bufs.Put(bufs) - return dst, br.close() -} - -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) decompress4X8bit(dst, src []byte) ([]byte, error) { - if d.actualTableLog == 8 { - return d.decompress4X8bitExactly(dst, src) - } - - var br [4]bitReaderBytes - start := 6 - for i := 0; i < 3; i++ { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } - - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - shift := (56 + (8 - d.actualTableLog)) & 63 - - const tlSize = 1 << 8 - single := d.dt.single[:tlSize] - - // Use temp table to avoid bound checks/append penalty. - buf := d.buffer() - var off uint8 - var decoded int - - // Decode 4 values from each decoder/loop. - const bufoff = 256 - for { - if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { - break - } - - { - // Interleave 2 decodes. - const stream = 0 - const stream2 = 1 - br1 := &br[stream] - br2 := &br[stream2] - br1.fillFast() - br2.fillFast() - - v := single[uint8(br1.value>>shift)].entry - v2 := single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off] = uint8(v >> 8) - buf[stream2][off] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+1] = uint8(v >> 8) - buf[stream2][off+1] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+2] = uint8(v >> 8) - buf[stream2][off+2] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+3] = uint8(v >> 8) - buf[stream2][off+3] = uint8(v2 >> 8) - } - - { - const stream = 2 - const stream2 = 3 - br1 := &br[stream] - br2 := &br[stream2] - br1.fillFast() - br2.fillFast() - - v := single[uint8(br1.value>>shift)].entry - v2 := single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off] = uint8(v >> 8) - buf[stream2][off] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+1] = uint8(v >> 8) - buf[stream2][off+1] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+2] = uint8(v >> 8) - buf[stream2][off+2] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+3] = uint8(v >> 8) - buf[stream2][off+3] = uint8(v2 >> 8) - } - - off += 4 - - if off == 0 { - if bufoff > dstEvery { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 1") - } - // There must at least be 3 buffers left. - if len(out)-bufoff < dstEvery*3 { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 2") - } - //copy(out, buf[0][:]) - //copy(out[dstEvery:], buf[1][:]) - //copy(out[dstEvery*2:], buf[2][:]) - *(*[bufoff]byte)(out) = buf[0] - *(*[bufoff]byte)(out[dstEvery:]) = buf[1] - *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] - *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] - out = out[bufoff:] - decoded += bufoff * 4 - } - } - if off > 0 { - ioff := int(off) - if len(out) < dstEvery*3+ioff { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 3") - } - copy(out, buf[0][:off]) - copy(out[dstEvery:], buf[1][:off]) - copy(out[dstEvery*2:], buf[2][:off]) - copy(out[dstEvery*3:], buf[3][:off]) - decoded += int(off) * 4 - out = out[off:] - } - - // Decode remaining. - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - if br.finished() { - d.bufs.Put(buf) - return nil, io.ErrUnexpectedEOF - } - if br.bitsRead >= 56 { - if br.off >= 4 { - v := br.in[br.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - br.value |= uint64(low) << (br.bitsRead - 32) - br.bitsRead -= 32 - br.off -= 4 - } else { - for br.off > 0 { - br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) - br.bitsRead -= 8 - br.off-- - } - } - } - // end inline... - if offset >= endsAt { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - v := single[uint8(br.value>>shift)].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - d.bufs.Put(buf) - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - d.bufs.Put(buf) - return nil, err - } - } - d.bufs.Put(buf) - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} - -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) decompress4X8bitExactly(dst, src []byte) ([]byte, error) { - var br [4]bitReaderBytes - start := 6 - for i := 0; i < 3; i++ { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } - - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - const shift = 56 - const tlSize = 1 << 8 - single := d.dt.single[:tlSize] - - // Use temp table to avoid bound checks/append penalty. - buf := d.buffer() - var off uint8 - var decoded int - - // Decode 4 values from each decoder/loop. - const bufoff = 256 - for { - if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { - break - } - - { - // Interleave 2 decodes. - const stream = 0 - const stream2 = 1 - br1 := &br[stream] - br2 := &br[stream2] - br1.fillFast() - br2.fillFast() - - v := single[uint8(br1.value>>shift)].entry - v2 := single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off] = uint8(v >> 8) - buf[stream2][off] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+1] = uint8(v >> 8) - buf[stream2][off+1] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+2] = uint8(v >> 8) - buf[stream2][off+2] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+3] = uint8(v >> 8) - buf[stream2][off+3] = uint8(v2 >> 8) - } - - { - const stream = 2 - const stream2 = 3 - br1 := &br[stream] - br2 := &br[stream2] - br1.fillFast() - br2.fillFast() - - v := single[uint8(br1.value>>shift)].entry - v2 := single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off] = uint8(v >> 8) - buf[stream2][off] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+1] = uint8(v >> 8) - buf[stream2][off+1] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+2] = uint8(v >> 8) - buf[stream2][off+2] = uint8(v2 >> 8) - - v = single[uint8(br1.value>>shift)].entry - v2 = single[uint8(br2.value>>shift)].entry - br1.bitsRead += uint8(v) - br1.value <<= v & 63 - br2.bitsRead += uint8(v2) - br2.value <<= v2 & 63 - buf[stream][off+3] = uint8(v >> 8) - buf[stream2][off+3] = uint8(v2 >> 8) - } - - off += 4 - - if off == 0 { - if bufoff > dstEvery { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 1") - } - // There must at least be 3 buffers left. - if len(out)-bufoff < dstEvery*3 { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 2") - } - - //copy(out, buf[0][:]) - //copy(out[dstEvery:], buf[1][:]) - //copy(out[dstEvery*2:], buf[2][:]) - // copy(out[dstEvery*3:], buf[3][:]) - *(*[bufoff]byte)(out) = buf[0] - *(*[bufoff]byte)(out[dstEvery:]) = buf[1] - *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] - *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] - out = out[bufoff:] - decoded += bufoff * 4 - } - } - if off > 0 { - ioff := int(off) - if len(out) < dstEvery*3+ioff { - return nil, errors.New("corruption detected: stream overrun 3") - } - copy(out, buf[0][:off]) - copy(out[dstEvery:], buf[1][:off]) - copy(out[dstEvery*2:], buf[2][:off]) - copy(out[dstEvery*3:], buf[3][:off]) - decoded += int(off) * 4 - out = out[off:] - } - - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - if br.finished() { - d.bufs.Put(buf) - return nil, io.ErrUnexpectedEOF - } - if br.bitsRead >= 56 { - if br.off >= 4 { - v := br.in[br.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - br.value |= uint64(low) << (br.bitsRead - 32) - br.bitsRead -= 32 - br.off -= 4 - } else { - for br.off > 0 { - br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) - br.bitsRead -= 8 - br.off-- - } - } - } - // end inline... - if offset >= endsAt { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - v := single[br.peekByteFast()].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - d.bufs.Put(buf) - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - d.bufs.Put(buf) - return nil, err - } - } - d.bufs.Put(buf) - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} - -// matches will compare a decoding table to a coding table. -// Errors are written to the writer. -// Nothing will be written if table is ok. -func (s *Scratch) matches(ct cTable, w io.Writer) { - if s == nil || len(s.dt.single) == 0 { - return - } - dt := s.dt.single[:1<>8) == byte(sym) { - fmt.Fprintf(w, "symbol %x has decoder, but no encoder\n", sym) - errs++ - break - } - } - if errs == 0 { - broken-- - } - continue - } - // Unused bits in input - ub := tablelog - enc.nBits - top := enc.val << ub - // decoder looks at top bits. - dec := dt[top] - if uint8(dec.entry) != enc.nBits { - fmt.Fprintf(w, "symbol 0x%x bit size mismatch (enc: %d, dec:%d).\n", sym, enc.nBits, uint8(dec.entry)) - errs++ - } - if uint8(dec.entry>>8) != uint8(sym) { - fmt.Fprintf(w, "symbol 0x%x decoder output mismatch (enc: %d, dec:%d).\n", sym, sym, uint8(dec.entry>>8)) - errs++ - } - if errs > 0 { - fmt.Fprintf(w, "%d errros in base, stopping\n", errs) - continue - } - // Ensure that all combinations are covered. - for i := uint16(0); i < (1 << ub); i++ { - vval := top | i - dec := dt[vval] - if uint8(dec.entry) != enc.nBits { - fmt.Fprintf(w, "symbol 0x%x bit size mismatch (enc: %d, dec:%d).\n", vval, enc.nBits, uint8(dec.entry)) - errs++ - } - if uint8(dec.entry>>8) != uint8(sym) { - fmt.Fprintf(w, "symbol 0x%x decoder output mismatch (enc: %d, dec:%d).\n", vval, sym, uint8(dec.entry>>8)) - errs++ - } - if errs > 20 { - fmt.Fprintf(w, "%d errros, stopping\n", errs) - break - } - } - if errs == 0 { - ok++ - broken-- - } - } - if broken > 0 { - fmt.Fprintf(w, "%d broken, %d ok\n", broken, ok) - } -} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go deleted file mode 100644 index ba7e8e6b0..000000000 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go +++ /dev/null @@ -1,226 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -// This file contains the specialisation of Decoder.Decompress4X -// and Decoder.Decompress1X that use an asm implementation of thir main loops. -package huff0 - -import ( - "errors" - "fmt" - - "github.com/klauspost/compress/internal/cpuinfo" -) - -// decompress4x_main_loop_x86 is an x86 assembler implementation -// of Decompress4X when tablelog > 8. -// -//go:noescape -func decompress4x_main_loop_amd64(ctx *decompress4xContext) - -// decompress4x_8b_loop_x86 is an x86 assembler implementation -// of Decompress4X when tablelog <= 8 which decodes 4 entries -// per loop. -// -//go:noescape -func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) - -// fallback8BitSize is the size where using Go version is faster. -const fallback8BitSize = 800 - -type decompress4xContext struct { - pbr *[4]bitReaderShifted - peekBits uint8 - out *byte - dstEvery int - tbl *dEntrySingle - decoded int - limit *byte -} - -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - if len(src) < 6+(4*1) { - return nil, errors.New("input too small") - } - - use8BitTables := d.actualTableLog <= 8 - if cap(dst) < fallback8BitSize && use8BitTables { - return d.decompress4X8bit(dst, src) - } - - var br [4]bitReaderShifted - // Decode "jump table" - start := 6 - for i := 0; i < 3; i++ { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } - - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - single := d.dt.single[:tlSize] - - var decoded int - - if len(out) > 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) { - ctx := decompress4xContext{ - pbr: &br, - peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() - out: &out[0], - dstEvery: dstEvery, - tbl: &single[0], - limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last. - } - if use8BitTables { - decompress4x_8b_main_loop_amd64(&ctx) - } else { - decompress4x_main_loop_amd64(&ctx) - } - - decoded = ctx.decoded - out = out[decoded/4:] - } - - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - br.fill() - if offset >= endsAt { - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - val := br.peekBitsFast(d.actualTableLog) - v := single[val&tlMask].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - return nil, err - } - } - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} - -// decompress4x_main_loop_x86 is an x86 assembler implementation -// of Decompress1X when tablelog > 8. -// -//go:noescape -func decompress1x_main_loop_amd64(ctx *decompress1xContext) - -// decompress4x_main_loop_x86 is an x86 with BMI2 assembler implementation -// of Decompress1X when tablelog > 8. -// -//go:noescape -func decompress1x_main_loop_bmi2(ctx *decompress1xContext) - -type decompress1xContext struct { - pbr *bitReaderShifted - peekBits uint8 - out *byte - outCap int - tbl *dEntrySingle - decoded int -} - -// Error reported by asm implementations -const error_max_decoded_size_exeeded = -1 - -// Decompress1X will decompress a 1X encoded stream. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - var br bitReaderShifted - err := br.init(src) - if err != nil { - return dst, err - } - maxDecodedSize := cap(dst) - dst = dst[:maxDecodedSize] - - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - - if maxDecodedSize >= 4 { - ctx := decompress1xContext{ - pbr: &br, - out: &dst[0], - outCap: maxDecodedSize, - peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast() - tbl: &d.dt.single[0], - } - - if cpuinfo.HasBMI2() { - decompress1x_main_loop_bmi2(&ctx) - } else { - decompress1x_main_loop_amd64(&ctx) - } - if ctx.decoded == error_max_decoded_size_exeeded { - return nil, ErrMaxDecodedSizeExceeded - } - - dst = dst[:ctx.decoded] - } - - // br < 8, so uint8 is fine - bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead - for bitsLeft > 0 { - br.fill() - if len(dst) >= maxDecodedSize { - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= nBits - dst = append(dst, uint8(v.entry>>8)) - } - return dst, br.close() -} diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s deleted file mode 100644 index c4c7ab2d1..000000000 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.s +++ /dev/null @@ -1,830 +0,0 @@ -// Code generated by command: go run gen.go -out ../decompress_amd64.s -pkg=huff0. DO NOT EDIT. - -//go:build amd64 && !appengine && !noasm && gc - -// func decompress4x_main_loop_amd64(ctx *decompress4xContext) -TEXT ·decompress4x_main_loop_amd64(SB), $0-8 - // Preload values - MOVQ ctx+0(FP), AX - MOVBQZX 8(AX), DI - MOVQ 16(AX), BX - MOVQ 48(AX), SI - MOVQ 24(AX), R8 - MOVQ 32(AX), R9 - MOVQ (AX), R10 - - // Main loop -main_loop: - XORL DX, DX - CMPQ BX, SI - SETGE DL - - // br0.fillFast32() - MOVQ 32(R10), R11 - MOVBQZX 40(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill0 - MOVQ 24(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ (R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 24(R10) - ORQ R13, R11 - - // exhausted += (br0.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill0: - // val0 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br0.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX) - - // update the bitreader structure - MOVQ R11, 32(R10) - MOVB R12, 40(R10) - - // br1.fillFast32() - MOVQ 80(R10), R11 - MOVBQZX 88(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill1 - MOVQ 72(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 48(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 72(R10) - ORQ R13, R11 - - // exhausted += (br1.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br1.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX)(R8*1) - - // update the bitreader structure - MOVQ R11, 80(R10) - MOVB R12, 88(R10) - - // br2.fillFast32() - MOVQ 128(R10), R11 - MOVBQZX 136(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill2 - MOVQ 120(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 96(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 120(R10) - ORQ R13, R11 - - // exhausted += (br2.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br2.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - MOVW AX, (BX)(R8*2) - - // update the bitreader structure - MOVQ R11, 128(R10) - MOVB R12, 136(R10) - - // br3.fillFast32() - MOVQ 176(R10), R11 - MOVBQZX 184(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill3 - MOVQ 168(R10), AX - SUBQ $0x20, R12 - SUBQ $0x04, AX - MOVQ 144(R10), R13 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (AX)(R13*1), R13 - MOVQ R12, CX - SHLQ CL, R13 - MOVQ AX, 168(R10) - ORQ R13, R11 - - // exhausted += (br3.off < 4) - CMPQ AX, $0x04 - ADCB $+0, DL - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br3.peekTopBits(peekBits) - MOVQ DI, CX - MOVQ R11, R13 - SHRQ CL, R13 - - // v1 := table[val1&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v1.entry)) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // these two writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - LEAQ (R8)(R8*2), CX - MOVW AX, (BX)(CX*1) - - // update the bitreader structure - MOVQ R11, 176(R10) - MOVB R12, 184(R10) - ADDQ $0x02, BX - TESTB DL, DL - JZ main_loop - MOVQ ctx+0(FP), AX - SUBQ 16(AX), BX - SHLQ $0x02, BX - MOVQ BX, 40(AX) - RET - -// func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext) -TEXT ·decompress4x_8b_main_loop_amd64(SB), $0-8 - // Preload values - MOVQ ctx+0(FP), CX - MOVBQZX 8(CX), DI - MOVQ 16(CX), BX - MOVQ 48(CX), SI - MOVQ 24(CX), R8 - MOVQ 32(CX), R9 - MOVQ (CX), R10 - - // Main loop -main_loop: - XORL DX, DX - CMPQ BX, SI - SETGE DL - - // br0.fillFast32() - MOVQ 32(R10), R11 - MOVBQZX 40(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill0 - MOVQ 24(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ (R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 24(R10) - ORQ R14, R11 - - // exhausted += (br0.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill0: - // val0 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br0.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br0.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX) - - // update the bitreader structure - MOVQ R11, 32(R10) - MOVB R12, 40(R10) - - // br1.fillFast32() - MOVQ 80(R10), R11 - MOVBQZX 88(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill1 - MOVQ 72(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 48(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 72(R10) - ORQ R14, R11 - - // exhausted += (br1.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill1: - // val0 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br1.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br1.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX)(R8*1) - - // update the bitreader structure - MOVQ R11, 80(R10) - MOVB R12, 88(R10) - - // br2.fillFast32() - MOVQ 128(R10), R11 - MOVBQZX 136(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill2 - MOVQ 120(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 96(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 120(R10) - ORQ R14, R11 - - // exhausted += (br2.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill2: - // val0 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br2.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br2.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - MOVL AX, (BX)(R8*2) - - // update the bitreader structure - MOVQ R11, 128(R10) - MOVB R12, 136(R10) - - // br3.fillFast32() - MOVQ 176(R10), R11 - MOVBQZX 184(R10), R12 - CMPQ R12, $0x20 - JBE skip_fill3 - MOVQ 168(R10), R13 - SUBQ $0x20, R12 - SUBQ $0x04, R13 - MOVQ 144(R10), R14 - - // b.value |= uint64(low) << (b.bitsRead & 63) - MOVL (R13)(R14*1), R14 - MOVQ R12, CX - SHLQ CL, R14 - MOVQ R13, 168(R10) - ORQ R14, R11 - - // exhausted += (br3.off < 4) - CMPQ R13, $0x04 - ADCB $+0, DL - -skip_fill3: - // val0 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v0 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v0.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - - // val1 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v1 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v1.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // val2 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v2 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v2.entry) - MOVB CH, AH - SHLQ CL, R11 - ADDB CL, R12 - - // val3 := br3.peekTopBits(peekBits) - MOVQ R11, R13 - MOVQ DI, CX - SHRQ CL, R13 - - // v3 := table[val0&mask] - MOVW (R9)(R13*2), CX - - // br3.advance(uint8(v3.entry) - MOVB CH, AL - SHLQ CL, R11 - ADDB CL, R12 - BSWAPL AX - - // these four writes get coalesced - // out[id * dstEvery + 0] = uint8(v0.entry >> 8) - // out[id * dstEvery + 1] = uint8(v1.entry >> 8) - // out[id * dstEvery + 3] = uint8(v2.entry >> 8) - // out[id * dstEvery + 4] = uint8(v3.entry >> 8) - LEAQ (R8)(R8*2), CX - MOVL AX, (BX)(CX*1) - - // update the bitreader structure - MOVQ R11, 176(R10) - MOVB R12, 184(R10) - ADDQ $0x04, BX - TESTB DL, DL - JZ main_loop - MOVQ ctx+0(FP), AX - SUBQ 16(AX), BX - SHLQ $0x02, BX - MOVQ BX, 40(AX) - RET - -// func decompress1x_main_loop_amd64(ctx *decompress1xContext) -TEXT ·decompress1x_main_loop_amd64(SB), $0-8 - MOVQ ctx+0(FP), CX - MOVQ 16(CX), DX - MOVQ 24(CX), BX - CMPQ BX, $0x04 - JB error_max_decoded_size_exceeded - LEAQ (DX)(BX*1), BX - MOVQ (CX), SI - MOVQ (SI), R8 - MOVQ 24(SI), R9 - MOVQ 32(SI), R10 - MOVBQZX 40(SI), R11 - MOVQ 32(CX), SI - MOVBQZX 8(CX), DI - JMP loop_condition - -main_loop: - // Check if we have room for 4 bytes in the output buffer - LEAQ 4(DX), CX - CMPQ CX, BX - JGE error_max_decoded_size_exceeded - - // Decode 4 values - CMPQ R11, $0x20 - JL bitReader_fillFast_1_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), R12 - MOVQ R11, CX - SHLQ CL, R12 - ORQ R12, R10 - -bitReader_fillFast_1_end: - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AL - MOVBQZX CL, CX - ADDQ CX, R11 - SHLQ CL, R10 - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AH - MOVBQZX CL, CX - ADDQ CX, R11 - SHLQ CL, R10 - BSWAPL AX - CMPQ R11, $0x20 - JL bitReader_fillFast_2_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), R12 - MOVQ R11, CX - SHLQ CL, R12 - ORQ R12, R10 - -bitReader_fillFast_2_end: - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AH - MOVBQZX CL, CX - ADDQ CX, R11 - SHLQ CL, R10 - MOVQ DI, CX - MOVQ R10, R12 - SHRQ CL, R12 - MOVW (SI)(R12*2), CX - MOVB CH, AL - MOVBQZX CL, CX - ADDQ CX, R11 - SHLQ CL, R10 - BSWAPL AX - - // Store the decoded values - MOVL AX, (DX) - ADDQ $0x04, DX - -loop_condition: - CMPQ R9, $0x08 - JGE main_loop - - // Update ctx structure - MOVQ ctx+0(FP), AX - SUBQ 16(AX), DX - MOVQ DX, 40(AX) - MOVQ (AX), AX - MOVQ R9, 24(AX) - MOVQ R10, 32(AX) - MOVB R11, 40(AX) - RET - - // Report error -error_max_decoded_size_exceeded: - MOVQ ctx+0(FP), AX - MOVQ $-1, CX - MOVQ CX, 40(AX) - RET - -// func decompress1x_main_loop_bmi2(ctx *decompress1xContext) -// Requires: BMI2 -TEXT ·decompress1x_main_loop_bmi2(SB), $0-8 - MOVQ ctx+0(FP), CX - MOVQ 16(CX), DX - MOVQ 24(CX), BX - CMPQ BX, $0x04 - JB error_max_decoded_size_exceeded - LEAQ (DX)(BX*1), BX - MOVQ (CX), SI - MOVQ (SI), R8 - MOVQ 24(SI), R9 - MOVQ 32(SI), R10 - MOVBQZX 40(SI), R11 - MOVQ 32(CX), SI - MOVBQZX 8(CX), DI - JMP loop_condition - -main_loop: - // Check if we have room for 4 bytes in the output buffer - LEAQ 4(DX), CX - CMPQ CX, BX - JGE error_max_decoded_size_exceeded - - // Decode 4 values - CMPQ R11, $0x20 - JL bitReader_fillFast_1_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), CX - SHLXQ R11, CX, CX - ORQ CX, R10 - -bitReader_fillFast_1_end: - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AL - MOVBQZX CL, CX - ADDQ CX, R11 - SHLXQ CX, R10, R10 - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AH - MOVBQZX CL, CX - ADDQ CX, R11 - SHLXQ CX, R10, R10 - BSWAPL AX - CMPQ R11, $0x20 - JL bitReader_fillFast_2_end - SUBQ $0x20, R11 - SUBQ $0x04, R9 - MOVL (R8)(R9*1), CX - SHLXQ R11, CX, CX - ORQ CX, R10 - -bitReader_fillFast_2_end: - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AH - MOVBQZX CL, CX - ADDQ CX, R11 - SHLXQ CX, R10, R10 - SHRXQ DI, R10, CX - MOVW (SI)(CX*2), CX - MOVB CH, AL - MOVBQZX CL, CX - ADDQ CX, R11 - SHLXQ CX, R10, R10 - BSWAPL AX - - // Store the decoded values - MOVL AX, (DX) - ADDQ $0x04, DX - -loop_condition: - CMPQ R9, $0x08 - JGE main_loop - - // Update ctx structure - MOVQ ctx+0(FP), AX - SUBQ 16(AX), DX - MOVQ DX, 40(AX) - MOVQ (AX), AX - MOVQ R9, 24(AX) - MOVQ R10, 32(AX) - MOVB R11, 40(AX) - RET - - // Report error -error_max_decoded_size_exceeded: - MOVQ ctx+0(FP), AX - MOVQ $-1, CX - MOVQ CX, 40(AX) - RET diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go b/vendor/github.com/klauspost/compress/huff0/decompress_generic.go deleted file mode 100644 index 908c17de6..000000000 --- a/vendor/github.com/klauspost/compress/huff0/decompress_generic.go +++ /dev/null @@ -1,299 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -// This file contains a generic implementation of Decoder.Decompress4X. -package huff0 - -import ( - "errors" - "fmt" -) - -// Decompress4X will decompress a 4X encoded stream. -// The length of the supplied input must match the end of a block exactly. -// The *capacity* of the dst slice must match the destination size of -// the uncompressed data exactly. -func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - if len(src) < 6+(4*1) { - return nil, errors.New("input too small") - } - if use8BitTables && d.actualTableLog <= 8 { - return d.decompress4X8bit(dst, src) - } - - var br [4]bitReaderShifted - // Decode "jump table" - start := 6 - for i := 0; i < 3; i++ { - length := int(src[i*2]) | (int(src[i*2+1]) << 8) - if start+length >= len(src) { - return nil, errors.New("truncated input (or invalid offset)") - } - err := br[i].init(src[start : start+length]) - if err != nil { - return nil, err - } - start += length - } - err := br[3].init(src[start:]) - if err != nil { - return nil, err - } - - // destination, offset to match first output - dstSize := cap(dst) - dst = dst[:dstSize] - out := dst - dstEvery := (dstSize + 3) / 4 - - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - single := d.dt.single[:tlSize] - - // Use temp table to avoid bound checks/append penalty. - buf := d.buffer() - var off uint8 - var decoded int - - // Decode 2 values from each decoder/loop. - const bufoff = 256 - for { - if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { - break - } - - { - const stream = 0 - const stream2 = 1 - br[stream].fillFast() - br[stream2].fillFast() - - val := br[stream].peekBitsFast(d.actualTableLog) - val2 := br[stream2].peekBitsFast(d.actualTableLog) - v := single[val&tlMask] - v2 := single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off] = uint8(v.entry >> 8) - buf[stream2][off] = uint8(v2.entry >> 8) - - val = br[stream].peekBitsFast(d.actualTableLog) - val2 = br[stream2].peekBitsFast(d.actualTableLog) - v = single[val&tlMask] - v2 = single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off+1] = uint8(v.entry >> 8) - buf[stream2][off+1] = uint8(v2.entry >> 8) - } - - { - const stream = 2 - const stream2 = 3 - br[stream].fillFast() - br[stream2].fillFast() - - val := br[stream].peekBitsFast(d.actualTableLog) - val2 := br[stream2].peekBitsFast(d.actualTableLog) - v := single[val&tlMask] - v2 := single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off] = uint8(v.entry >> 8) - buf[stream2][off] = uint8(v2.entry >> 8) - - val = br[stream].peekBitsFast(d.actualTableLog) - val2 = br[stream2].peekBitsFast(d.actualTableLog) - v = single[val&tlMask] - v2 = single[val2&tlMask] - br[stream].advance(uint8(v.entry)) - br[stream2].advance(uint8(v2.entry)) - buf[stream][off+1] = uint8(v.entry >> 8) - buf[stream2][off+1] = uint8(v2.entry >> 8) - } - - off += 2 - - if off == 0 { - if bufoff > dstEvery { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 1") - } - // There must at least be 3 buffers left. - if len(out)-bufoff < dstEvery*3 { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 2") - } - //copy(out, buf[0][:]) - //copy(out[dstEvery:], buf[1][:]) - //copy(out[dstEvery*2:], buf[2][:]) - //copy(out[dstEvery*3:], buf[3][:]) - *(*[bufoff]byte)(out) = buf[0] - *(*[bufoff]byte)(out[dstEvery:]) = buf[1] - *(*[bufoff]byte)(out[dstEvery*2:]) = buf[2] - *(*[bufoff]byte)(out[dstEvery*3:]) = buf[3] - out = out[bufoff:] - decoded += bufoff * 4 - } - } - if off > 0 { - ioff := int(off) - if len(out) < dstEvery*3+ioff { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 3") - } - copy(out, buf[0][:off]) - copy(out[dstEvery:], buf[1][:off]) - copy(out[dstEvery*2:], buf[2][:off]) - copy(out[dstEvery*3:], buf[3][:off]) - decoded += int(off) * 4 - out = out[off:] - } - - // Decode remaining. - remainBytes := dstEvery - (decoded / 4) - for i := range br { - offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } - br := &br[i] - bitsLeft := br.remaining() - for bitsLeft > 0 { - br.fill() - if offset >= endsAt { - d.bufs.Put(buf) - return nil, errors.New("corruption detected: stream overrun 4") - } - - // Read value and increment offset. - val := br.peekBitsFast(d.actualTableLog) - v := single[val&tlMask].entry - nBits := uint8(v) - br.advance(nBits) - bitsLeft -= uint(nBits) - out[offset] = uint8(v >> 8) - offset++ - } - if offset != endsAt { - d.bufs.Put(buf) - return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt) - } - decoded += offset - dstEvery*i - err = br.close() - if err != nil { - return nil, err - } - } - d.bufs.Put(buf) - if dstSize != decoded { - return nil, errors.New("corruption detected: short output block") - } - return dst, nil -} - -// Decompress1X will decompress a 1X encoded stream. -// The cap of the output buffer will be the maximum decompressed size. -// The length of the supplied input must match the end of a block exactly. -func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { - if len(d.dt.single) == 0 { - return nil, errors.New("no table loaded") - } - if use8BitTables && d.actualTableLog <= 8 { - return d.decompress1X8Bit(dst, src) - } - var br bitReaderShifted - err := br.init(src) - if err != nil { - return dst, err - } - maxDecodedSize := cap(dst) - dst = dst[:0] - - // Avoid bounds check by always having full sized table. - const tlSize = 1 << tableLogMax - const tlMask = tlSize - 1 - dt := d.dt.single[:tlSize] - - // Use temp table to avoid bound checks/append penalty. - bufs := d.buffer() - buf := &bufs[0] - var off uint8 - - for br.off >= 8 { - br.fillFast() - v := dt[br.peekBitsFast(d.actualTableLog)&tlMask] - br.advance(uint8(v.entry)) - buf[off+0] = uint8(v.entry >> 8) - - v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] - br.advance(uint8(v.entry)) - buf[off+1] = uint8(v.entry >> 8) - - // Refill - br.fillFast() - - v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] - br.advance(uint8(v.entry)) - buf[off+2] = uint8(v.entry >> 8) - - v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] - br.advance(uint8(v.entry)) - buf[off+3] = uint8(v.entry >> 8) - - off += 4 - if off == 0 { - if len(dst)+256 > maxDecodedSize { - br.close() - d.bufs.Put(bufs) - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:]...) - } - } - - if len(dst)+int(off) > maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - dst = append(dst, buf[:off]...) - - // br < 8, so uint8 is fine - bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead - for bitsLeft > 0 { - br.fill() - if false && br.bitsRead >= 32 { - if br.off >= 4 { - v := br.in[br.off-4:] - v = v[:4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - br.value = (br.value << 32) | uint64(low) - br.bitsRead -= 32 - br.off -= 4 - } else { - for br.off > 0 { - br.value = (br.value << 8) | uint64(br.in[br.off-1]) - br.bitsRead -= 8 - br.off-- - } - } - } - if len(dst) >= maxDecodedSize { - d.bufs.Put(bufs) - br.close() - return nil, ErrMaxDecodedSizeExceeded - } - v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] - nBits := uint8(v.entry) - br.advance(nBits) - bitsLeft -= nBits - dst = append(dst, uint8(v.entry>>8)) - } - d.bufs.Put(bufs) - return dst, br.close() -} diff --git a/vendor/github.com/klauspost/compress/huff0/huff0.go b/vendor/github.com/klauspost/compress/huff0/huff0.go deleted file mode 100644 index 77ecd68e0..000000000 --- a/vendor/github.com/klauspost/compress/huff0/huff0.go +++ /dev/null @@ -1,337 +0,0 @@ -// Package huff0 provides fast huffman encoding as used in zstd. -// -// See README.md at https://github.com/klauspost/compress/tree/master/huff0 for details. -package huff0 - -import ( - "errors" - "fmt" - "math" - "math/bits" - "sync" - - "github.com/klauspost/compress/fse" -) - -const ( - maxSymbolValue = 255 - - // zstandard limits tablelog to 11, see: - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#huffman-tree-description - tableLogMax = 11 - tableLogDefault = 11 - minTablelog = 5 - huffNodesLen = 512 - - // BlockSizeMax is maximum input size for a single block uncompressed. - BlockSizeMax = 1<<18 - 1 -) - -var ( - // ErrIncompressible is returned when input is judged to be too hard to compress. - ErrIncompressible = errors.New("input is not compressible") - - // ErrUseRLE is returned from the compressor when the input is a single byte value repeated. - ErrUseRLE = errors.New("input is single value repeated") - - // ErrTooBig is return if input is too large for a single block. - ErrTooBig = errors.New("input too big") - - // ErrMaxDecodedSizeExceeded is return if input is too large for a single block. - ErrMaxDecodedSizeExceeded = errors.New("maximum output size exceeded") -) - -type ReusePolicy uint8 - -const ( - // ReusePolicyAllow will allow reuse if it produces smaller output. - ReusePolicyAllow ReusePolicy = iota - - // ReusePolicyPrefer will re-use aggressively if possible. - // This will not check if a new table will produce smaller output, - // except if the current table is impossible to use or - // compressed output is bigger than input. - ReusePolicyPrefer - - // ReusePolicyNone will disable re-use of tables. - // This is slightly faster than ReusePolicyAllow but may produce larger output. - ReusePolicyNone - - // ReusePolicyMust must allow reuse and produce smaller output. - ReusePolicyMust -) - -type Scratch struct { - count [maxSymbolValue + 1]uint32 - - // Per block parameters. - // These can be used to override compression parameters of the block. - // Do not touch, unless you know what you are doing. - - // Out is output buffer. - // If the scratch is re-used before the caller is done processing the output, - // set this field to nil. - // Otherwise the output buffer will be re-used for next Compression/Decompression step - // and allocation will be avoided. - Out []byte - - // OutTable will contain the table data only, if a new table has been generated. - // Slice of the returned data. - OutTable []byte - - // OutData will contain the compressed data. - // Slice of the returned data. - OutData []byte - - // MaxDecodedSize will set the maximum allowed output size. - // This value will automatically be set to BlockSizeMax if not set. - // Decoders will return ErrMaxDecodedSizeExceeded is this limit is exceeded. - MaxDecodedSize int - - srcLen int - - // MaxSymbolValue will override the maximum symbol value of the next block. - MaxSymbolValue uint8 - - // TableLog will attempt to override the tablelog for the next block. - // Must be <= 11 and >= 5. - TableLog uint8 - - // Reuse will specify the reuse policy - Reuse ReusePolicy - - // WantLogLess allows to specify a log 2 reduction that should at least be achieved, - // otherwise the block will be returned as incompressible. - // The reduction should then at least be (input size >> WantLogLess) - // If WantLogLess == 0 any improvement will do. - WantLogLess uint8 - - symbolLen uint16 // Length of active part of the symbol table. - maxCount int // count of the most probable symbol - clearCount bool // clear count - actualTableLog uint8 // Selected tablelog. - prevTableLog uint8 // Tablelog for previous table - prevTable cTable // Table used for previous compression. - cTable cTable // compression table - dt dTable // decompression table - nodes []nodeElt - tmpOut [4][]byte - fse *fse.Scratch - decPool sync.Pool // *[4][256]byte buffers. - huffWeight [maxSymbolValue + 1]byte -} - -// TransferCTable will transfer the previously used compression table. -func (s *Scratch) TransferCTable(src *Scratch) { - if cap(s.prevTable) < len(src.prevTable) { - s.prevTable = make(cTable, 0, maxSymbolValue+1) - } - s.prevTable = s.prevTable[:len(src.prevTable)] - copy(s.prevTable, src.prevTable) - s.prevTableLog = src.prevTableLog -} - -func (s *Scratch) prepare(in []byte) (*Scratch, error) { - if len(in) > BlockSizeMax { - return nil, ErrTooBig - } - if s == nil { - s = &Scratch{} - } - if s.MaxSymbolValue == 0 { - s.MaxSymbolValue = maxSymbolValue - } - if s.TableLog == 0 { - s.TableLog = tableLogDefault - } - if s.TableLog > tableLogMax || s.TableLog < minTablelog { - return nil, fmt.Errorf(" invalid tableLog %d (%d -> %d)", s.TableLog, minTablelog, tableLogMax) - } - if s.MaxDecodedSize <= 0 || s.MaxDecodedSize > BlockSizeMax { - s.MaxDecodedSize = BlockSizeMax - } - if s.clearCount && s.maxCount == 0 { - for i := range s.count { - s.count[i] = 0 - } - s.clearCount = false - } - if cap(s.Out) == 0 { - s.Out = make([]byte, 0, len(in)) - } - s.Out = s.Out[:0] - - s.OutTable = nil - s.OutData = nil - if cap(s.nodes) < huffNodesLen+1 { - s.nodes = make([]nodeElt, 0, huffNodesLen+1) - } - s.nodes = s.nodes[:0] - if s.fse == nil { - s.fse = &fse.Scratch{} - } - s.srcLen = len(in) - - return s, nil -} - -type cTable []cTableEntry - -func (c cTable) write(s *Scratch) error { - var ( - // precomputed conversion table - bitsToWeight [tableLogMax + 1]byte - huffLog = s.actualTableLog - // last weight is not saved. - maxSymbolValue = uint8(s.symbolLen - 1) - huffWeight = s.huffWeight[:256] - ) - const ( - maxFSETableLog = 6 - ) - // convert to weight - bitsToWeight[0] = 0 - for n := uint8(1); n < huffLog+1; n++ { - bitsToWeight[n] = huffLog + 1 - n - } - - // Acquire histogram for FSE. - hist := s.fse.Histogram() - hist = hist[:256] - for i := range hist[:16] { - hist[i] = 0 - } - for n := uint8(0); n < maxSymbolValue; n++ { - v := bitsToWeight[c[n].nBits] & 15 - huffWeight[n] = v - hist[v]++ - } - - // FSE compress if feasible. - if maxSymbolValue >= 2 { - huffMaxCnt := uint32(0) - huffMax := uint8(0) - for i, v := range hist[:16] { - if v == 0 { - continue - } - huffMax = byte(i) - if v > huffMaxCnt { - huffMaxCnt = v - } - } - s.fse.HistogramFinished(huffMax, int(huffMaxCnt)) - s.fse.TableLog = maxFSETableLog - b, err := fse.Compress(huffWeight[:maxSymbolValue], s.fse) - if err == nil && len(b) < int(s.symbolLen>>1) { - s.Out = append(s.Out, uint8(len(b))) - s.Out = append(s.Out, b...) - return nil - } - // Unable to compress (RLE/uncompressible) - } - // write raw values as 4-bits (max : 15) - if maxSymbolValue > (256 - 128) { - // should not happen : likely means source cannot be compressed - return ErrIncompressible - } - op := s.Out - // special case, pack weights 4 bits/weight. - op = append(op, 128|(maxSymbolValue-1)) - // be sure it doesn't cause msan issue in final combination - huffWeight[maxSymbolValue] = 0 - for n := uint16(0); n < uint16(maxSymbolValue); n += 2 { - op = append(op, (huffWeight[n]<<4)|huffWeight[n+1]) - } - s.Out = op - return nil -} - -func (c cTable) estTableSize(s *Scratch) (sz int, err error) { - var ( - // precomputed conversion table - bitsToWeight [tableLogMax + 1]byte - huffLog = s.actualTableLog - // last weight is not saved. - maxSymbolValue = uint8(s.symbolLen - 1) - huffWeight = s.huffWeight[:256] - ) - const ( - maxFSETableLog = 6 - ) - // convert to weight - bitsToWeight[0] = 0 - for n := uint8(1); n < huffLog+1; n++ { - bitsToWeight[n] = huffLog + 1 - n - } - - // Acquire histogram for FSE. - hist := s.fse.Histogram() - hist = hist[:256] - for i := range hist[:16] { - hist[i] = 0 - } - for n := uint8(0); n < maxSymbolValue; n++ { - v := bitsToWeight[c[n].nBits] & 15 - huffWeight[n] = v - hist[v]++ - } - - // FSE compress if feasible. - if maxSymbolValue >= 2 { - huffMaxCnt := uint32(0) - huffMax := uint8(0) - for i, v := range hist[:16] { - if v == 0 { - continue - } - huffMax = byte(i) - if v > huffMaxCnt { - huffMaxCnt = v - } - } - s.fse.HistogramFinished(huffMax, int(huffMaxCnt)) - s.fse.TableLog = maxFSETableLog - b, err := fse.Compress(huffWeight[:maxSymbolValue], s.fse) - if err == nil && len(b) < int(s.symbolLen>>1) { - sz += 1 + len(b) - return sz, nil - } - // Unable to compress (RLE/uncompressible) - } - // write raw values as 4-bits (max : 15) - if maxSymbolValue > (256 - 128) { - // should not happen : likely means source cannot be compressed - return 0, ErrIncompressible - } - // special case, pack weights 4 bits/weight. - sz += 1 + int(maxSymbolValue/2) - return sz, nil -} - -// estimateSize returns the estimated size in bytes of the input represented in the -// histogram supplied. -func (c cTable) estimateSize(hist []uint32) int { - nbBits := uint32(7) - for i, v := range c[:len(hist)] { - nbBits += uint32(v.nBits) * hist[i] - } - return int(nbBits >> 3) -} - -// minSize returns the minimum possible size considering the shannon limit. -func (s *Scratch) minSize(total int) int { - nbBits := float64(7) - fTotal := float64(total) - for _, v := range s.count[:s.symbolLen] { - n := float64(v) - if n > 0 { - nbBits += math.Log2(fTotal/n) * n - } - } - return int(nbBits) >> 3 -} - -func highBit32(val uint32) (n uint32) { - return uint32(bits.Len32(val) - 1) -} diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go deleted file mode 100644 index 3954c5121..000000000 --- a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo.go +++ /dev/null @@ -1,34 +0,0 @@ -// Package cpuinfo gives runtime info about the current CPU. -// -// This is a very limited module meant for use internally -// in this project. For more versatile solution check -// https://github.com/klauspost/cpuid. -package cpuinfo - -// HasBMI1 checks whether an x86 CPU supports the BMI1 extension. -func HasBMI1() bool { - return hasBMI1 -} - -// HasBMI2 checks whether an x86 CPU supports the BMI2 extension. -func HasBMI2() bool { - return hasBMI2 -} - -// DisableBMI2 will disable BMI2, for testing purposes. -// Call returned function to restore previous state. -func DisableBMI2() func() { - old := hasBMI2 - hasBMI2 = false - return func() { - hasBMI2 = old - } -} - -// HasBMI checks whether an x86 CPU supports both BMI1 and BMI2 extensions. -func HasBMI() bool { - return HasBMI1() && HasBMI2() -} - -var hasBMI1 bool -var hasBMI2 bool diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go deleted file mode 100644 index e802579c4..000000000 --- a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -package cpuinfo - -// go:noescape -func x86extensions() (bmi1, bmi2 bool) - -func init() { - hasBMI1, hasBMI2 = x86extensions() -} diff --git a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s b/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s deleted file mode 100644 index 4465fbe9e..000000000 --- a/vendor/github.com/klauspost/compress/internal/cpuinfo/cpuinfo_amd64.s +++ /dev/null @@ -1,36 +0,0 @@ -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" -#include "funcdata.h" -#include "go_asm.h" - -TEXT ·x86extensions(SB), NOSPLIT, $0 - // 1. determine max EAX value - XORQ AX, AX - CPUID - - CMPQ AX, $7 - JB unsupported - - // 2. EAX = 7, ECX = 0 --- see Table 3-8 "Information Returned by CPUID Instruction" - MOVQ $7, AX - MOVQ $0, CX - CPUID - - BTQ $3, BX // bit 3 = BMI1 - SETCS AL - - BTQ $8, BX // bit 8 = BMI2 - SETCS AH - - MOVB AL, bmi1+0(FP) - MOVB AH, bmi2+1(FP) - RET - -unsupported: - XORQ AX, AX - MOVB AL, bmi1+0(FP) - MOVB AL, bmi2+1(FP) - RET diff --git a/vendor/github.com/klauspost/compress/internal/snapref/LICENSE b/vendor/github.com/klauspost/compress/internal/snapref/LICENSE deleted file mode 100644 index 6050c10f4..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2011 The Snappy-Go Authors. 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 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/vendor/github.com/klauspost/compress/internal/snapref/decode.go b/vendor/github.com/klauspost/compress/internal/snapref/decode.go deleted file mode 100644 index 40796a49d..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/decode.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright 2011 The Snappy-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 snapref - -import ( - "encoding/binary" - "errors" - "io" -) - -var ( - // ErrCorrupt reports that the input is invalid. - ErrCorrupt = errors.New("snappy: corrupt input") - // ErrTooLarge reports that the uncompressed length is too large. - ErrTooLarge = errors.New("snappy: decoded block is too large") - // ErrUnsupported reports that the input isn't supported. - ErrUnsupported = errors.New("snappy: unsupported input") - - errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") -) - -// DecodedLen returns the length of the decoded block. -func DecodedLen(src []byte) (int, error) { - v, _, err := decodedLen(src) - return v, err -} - -// decodedLen returns the length of the decoded block and the number of bytes -// that the length header occupied. -func decodedLen(src []byte) (blockLen, headerLen int, err error) { - v, n := binary.Uvarint(src) - if n <= 0 || v > 0xffffffff { - return 0, 0, ErrCorrupt - } - - const wordSize = 32 << (^uint(0) >> 32 & 1) - if wordSize == 32 && v > 0x7fffffff { - return 0, 0, ErrTooLarge - } - return int(v), n, nil -} - -const ( - decodeErrCodeCorrupt = 1 - decodeErrCodeUnsupportedLiteralLength = 2 -) - -// Decode returns the decoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire decoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -// -// Decode handles the Snappy block format, not the Snappy stream format. -func Decode(dst, src []byte) ([]byte, error) { - dLen, s, err := decodedLen(src) - if err != nil { - return nil, err - } - if dLen <= len(dst) { - dst = dst[:dLen] - } else { - dst = make([]byte, dLen) - } - switch decode(dst, src[s:]) { - case 0: - return dst, nil - case decodeErrCodeUnsupportedLiteralLength: - return nil, errUnsupportedLiteralLength - } - return nil, ErrCorrupt -} - -// NewReader returns a new Reader that decompresses from r, using the framing -// format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -func NewReader(r io.Reader) *Reader { - return &Reader{ - r: r, - decoded: make([]byte, maxBlockSize), - buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize), - } -} - -// Reader is an io.Reader that can read Snappy-compressed bytes. -// -// Reader handles the Snappy stream format, not the Snappy block format. -type Reader struct { - r io.Reader - err error - decoded []byte - buf []byte - // decoded[i:j] contains decoded bytes that have not yet been passed on. - i, j int - readHeader bool -} - -// Reset discards any buffered data, resets all state, and switches the Snappy -// reader to read from r. This permits reusing a Reader rather than allocating -// a new one. -func (r *Reader) Reset(reader io.Reader) { - r.r = reader - r.err = nil - r.i = 0 - r.j = 0 - r.readHeader = false -} - -func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) { - if _, r.err = io.ReadFull(r.r, p); r.err != nil { - if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { - r.err = ErrCorrupt - } - return false - } - return true -} - -func (r *Reader) fill() error { - for r.i >= r.j { - if !r.readFull(r.buf[:4], true) { - return r.err - } - chunkType := r.buf[0] - if !r.readHeader { - if chunkType != chunkTypeStreamIdentifier { - r.err = ErrCorrupt - return r.err - } - r.readHeader = true - } - chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 - if chunkLen > len(r.buf) { - r.err = ErrUnsupported - return r.err - } - - // The chunk types are specified at - // https://github.com/google/snappy/blob/master/framing_format.txt - switch chunkType { - case chunkTypeCompressedData: - // Section 4.2. Compressed data (chunk type 0x00). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf, false) { - return r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - buf = buf[checksumSize:] - - n, err := DecodedLen(buf) - if err != nil { - r.err = err - return r.err - } - if n > len(r.decoded) { - r.err = ErrCorrupt - return r.err - } - if _, err := Decode(r.decoded, buf); err != nil { - r.err = err - return r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeUncompressedData: - // Section 4.3. Uncompressed data (chunk type 0x01). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return r.err - } - buf := r.buf[:checksumSize] - if !r.readFull(buf, false) { - return r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - // Read directly into r.decoded instead of via r.buf. - n := chunkLen - checksumSize - if n > len(r.decoded) { - r.err = ErrCorrupt - return r.err - } - if !r.readFull(r.decoded[:n], false) { - return r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeStreamIdentifier: - // Section 4.1. Stream identifier (chunk type 0xff). - if chunkLen != len(magicBody) { - r.err = ErrCorrupt - return r.err - } - if !r.readFull(r.buf[:len(magicBody)], false) { - return r.err - } - for i := 0; i < len(magicBody); i++ { - if r.buf[i] != magicBody[i] { - r.err = ErrCorrupt - return r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - r.err = ErrUnsupported - return r.err - } - // Section 4.4 Padding (chunk type 0xfe). - // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). - if !r.readFull(r.buf[:chunkLen], false) { - return r.err - } - } - - return nil -} - -// Read satisfies the io.Reader interface. -func (r *Reader) Read(p []byte) (int, error) { - if r.err != nil { - return 0, r.err - } - - if err := r.fill(); err != nil { - return 0, err - } - - n := copy(p, r.decoded[r.i:r.j]) - r.i += n - return n, nil -} - -// ReadByte satisfies the io.ByteReader interface. -func (r *Reader) ReadByte() (byte, error) { - if r.err != nil { - return 0, r.err - } - - if err := r.fill(); err != nil { - return 0, err - } - - c := r.decoded[r.i] - r.i++ - return c, nil -} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go b/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go deleted file mode 100644 index 77395a6b8..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/decode_other.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2016 The Snappy-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 snapref - -// decode writes the decoding of src to dst. It assumes that the varint-encoded -// length of the decompressed bytes has already been read, and that len(dst) -// equals that length. -// -// It returns 0 on success or a decodeErrCodeXxx error code on failure. -func decode(dst, src []byte) int { - var d, s, offset, length int - for s < len(src) { - switch src[s] & 0x03 { - case tagLiteral: - x := uint32(src[s] >> 2) - switch { - case x < 60: - s++ - case x == 60: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-1]) - case x == 61: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-2]) | uint32(src[s-1])<<8 - case x == 62: - s += 4 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - case x == 63: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - length = int(x) + 1 - if length <= 0 { - return decodeErrCodeUnsupportedLiteralLength - } - if length > len(dst)-d || length > len(src)-s { - return decodeErrCodeCorrupt - } - copy(dst[d:], src[s:s+length]) - d += length - s += length - continue - - case tagCopy1: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 4 + int(src[s-2])>>2&0x7 - offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - - case tagCopy2: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-3])>>2 - offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - - case tagCopy4: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-5])>>2 - offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - } - - if offset <= 0 || d < offset || length > len(dst)-d { - return decodeErrCodeCorrupt - } - // Copy from an earlier sub-slice of dst to a later sub-slice. - // If no overlap, use the built-in copy: - if offset >= length { - copy(dst[d:d+length], dst[d-offset:]) - d += length - continue - } - - // Unlike the built-in copy function, this byte-by-byte copy always runs - // forwards, even if the slices overlap. Conceptually, this is: - // - // d += forwardCopy(dst[d:d+length], dst[d-offset:]) - // - // We align the slices into a and b and show the compiler they are the same size. - // This allows the loop to run without bounds checks. - a := dst[d : d+length] - b := dst[d-offset:] - b = b[:len(a)] - for i := range a { - a[i] = b[i] - } - d += length - } - if d != len(dst) { - return decodeErrCodeCorrupt - } - return 0 -} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/encode.go b/vendor/github.com/klauspost/compress/internal/snapref/encode.go deleted file mode 100644 index 13c6040a5..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/encode.go +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright 2011 The Snappy-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 snapref - -import ( - "encoding/binary" - "errors" - "io" -) - -// Encode returns the encoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire encoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -// -// Encode handles the Snappy block format, not the Snappy stream format. -func Encode(dst, src []byte) []byte { - if n := MaxEncodedLen(len(src)); n < 0 { - panic(ErrTooLarge) - } else if len(dst) < n { - dst = make([]byte, n) - } - - // The block starts with the varint-encoded length of the decompressed bytes. - d := binary.PutUvarint(dst, uint64(len(src))) - - for len(src) > 0 { - p := src - src = nil - if len(p) > maxBlockSize { - p, src = p[:maxBlockSize], p[maxBlockSize:] - } - if len(p) < minNonLiteralBlockSize { - d += emitLiteral(dst[d:], p) - } else { - d += encodeBlock(dst[d:], p) - } - } - return dst[:d] -} - -// inputMargin is the minimum number of extra input bytes to keep, inside -// encodeBlock's inner loop. On some architectures, this margin lets us -// implement a fast path for emitLiteral, where the copy of short (<= 16 byte) -// literals can be implemented as a single load to and store from a 16-byte -// register. That literal's actual length can be as short as 1 byte, so this -// can copy up to 15 bytes too much, but that's OK as subsequent iterations of -// the encoding loop will fix up the copy overrun, and this inputMargin ensures -// that we don't overrun the dst and src buffers. -const inputMargin = 16 - 1 - -// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that -// could be encoded with a copy tag. This is the minimum with respect to the -// algorithm used by encodeBlock, not a minimum enforced by the file format. -// -// The encoded output must start with at least a 1 byte literal, as there are -// no previous bytes to copy. A minimal (1 byte) copy after that, generated -// from an emitCopy call in encodeBlock's main loop, would require at least -// another inputMargin bytes, for the reason above: we want any emitLiteral -// calls inside encodeBlock's main loop to use the fast path if possible, which -// requires being able to overrun by inputMargin bytes. Thus, -// minNonLiteralBlockSize equals 1 + 1 + inputMargin. -// -// The C++ code doesn't use this exact threshold, but it could, as discussed at -// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion -// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an -// optimization. It should not affect the encoded form. This is tested by -// TestSameEncodingAsCppShortCopies. -const minNonLiteralBlockSize = 1 + 1 + inputMargin - -// MaxEncodedLen returns the maximum length of a snappy block, given its -// uncompressed length. -// -// It will return a negative value if srcLen is too large to encode. -func MaxEncodedLen(srcLen int) int { - n := uint64(srcLen) - if n > 0xffffffff { - return -1 - } - // Compressed data can be defined as: - // compressed := item* literal* - // item := literal* copy - // - // The trailing literal sequence has a space blowup of at most 62/60 - // since a literal of length 60 needs one tag byte + one extra byte - // for length information. - // - // Item blowup is trickier to measure. Suppose the "copy" op copies - // 4 bytes of data. Because of a special check in the encoding code, - // we produce a 4-byte copy only if the offset is < 65536. Therefore - // the copy op takes 3 bytes to encode, and this type of item leads - // to at most the 62/60 blowup for representing literals. - // - // Suppose the "copy" op copies 5 bytes of data. If the offset is big - // enough, it will take 5 bytes to encode the copy op. Therefore the - // worst case here is a one-byte literal followed by a five-byte copy. - // That is, 6 bytes of input turn into 7 bytes of "compressed" data. - // - // This last factor dominates the blowup, so the final estimate is: - n = 32 + n + n/6 - if n > 0xffffffff { - return -1 - } - return int(n) -} - -var errClosed = errors.New("snappy: Writer is closed") - -// NewWriter returns a new Writer that compresses to w. -// -// The Writer returned does not buffer writes. There is no need to Flush or -// Close such a Writer. -// -// Deprecated: the Writer returned is not suitable for many small writes, only -// for few large writes. Use NewBufferedWriter instead, which is efficient -// regardless of the frequency and shape of the writes, and remember to Close -// that Writer when done. -func NewWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - obuf: make([]byte, obufLen), - } -} - -// NewBufferedWriter returns a new Writer that compresses to w, using the -// framing format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -// -// The Writer returned buffers writes. Users must call Close to guarantee all -// data has been forwarded to the underlying io.Writer. They may also call -// Flush zero or more times before calling Close. -func NewBufferedWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - ibuf: make([]byte, 0, maxBlockSize), - obuf: make([]byte, obufLen), - } -} - -// Writer is an io.Writer that can write Snappy-compressed bytes. -// -// Writer handles the Snappy stream format, not the Snappy block format. -type Writer struct { - w io.Writer - err error - - // ibuf is a buffer for the incoming (uncompressed) bytes. - // - // Its use is optional. For backwards compatibility, Writers created by the - // NewWriter function have ibuf == nil, do not buffer incoming bytes, and - // therefore do not need to be Flush'ed or Close'd. - ibuf []byte - - // obuf is a buffer for the outgoing (compressed) bytes. - obuf []byte - - // wroteStreamHeader is whether we have written the stream header. - wroteStreamHeader bool -} - -// Reset discards the writer's state and switches the Snappy writer to write to -// w. This permits reusing a Writer rather than allocating a new one. -func (w *Writer) Reset(writer io.Writer) { - w.w = writer - w.err = nil - if w.ibuf != nil { - w.ibuf = w.ibuf[:0] - } - w.wroteStreamHeader = false -} - -// Write satisfies the io.Writer interface. -func (w *Writer) Write(p []byte) (nRet int, errRet error) { - if w.ibuf == nil { - // Do not buffer incoming bytes. This does not perform or compress well - // if the caller of Writer.Write writes many small slices. This - // behavior is therefore deprecated, but still supported for backwards - // compatibility with code that doesn't explicitly Flush or Close. - return w.write(p) - } - - // The remainder of this method is based on bufio.Writer.Write from the - // standard library. - - for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil { - var n int - if len(w.ibuf) == 0 { - // Large write, empty buffer. - // Write directly from p to avoid copy. - n, _ = w.write(p) - } else { - n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - w.Flush() - } - nRet += n - p = p[n:] - } - if w.err != nil { - return nRet, w.err - } - n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - nRet += n - return nRet, nil -} - -func (w *Writer) write(p []byte) (nRet int, errRet error) { - if w.err != nil { - return 0, w.err - } - for len(p) > 0 { - obufStart := len(magicChunk) - if !w.wroteStreamHeader { - w.wroteStreamHeader = true - copy(w.obuf, magicChunk) - obufStart = 0 - } - - var uncompressed []byte - if len(p) > maxBlockSize { - uncompressed, p = p[:maxBlockSize], p[maxBlockSize:] - } else { - uncompressed, p = p, nil - } - checksum := crc(uncompressed) - - // Compress the buffer, discarding the result if the improvement - // isn't at least 12.5%. - compressed := Encode(w.obuf[obufHeaderLen:], uncompressed) - chunkType := uint8(chunkTypeCompressedData) - chunkLen := 4 + len(compressed) - obufEnd := obufHeaderLen + len(compressed) - if len(compressed) >= len(uncompressed)-len(uncompressed)/8 { - chunkType = chunkTypeUncompressedData - chunkLen = 4 + len(uncompressed) - obufEnd = obufHeaderLen - } - - // Fill in the per-chunk header that comes before the body. - w.obuf[len(magicChunk)+0] = chunkType - w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0) - w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8) - w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16) - w.obuf[len(magicChunk)+4] = uint8(checksum >> 0) - w.obuf[len(magicChunk)+5] = uint8(checksum >> 8) - w.obuf[len(magicChunk)+6] = uint8(checksum >> 16) - w.obuf[len(magicChunk)+7] = uint8(checksum >> 24) - - if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil { - w.err = err - return nRet, err - } - if chunkType == chunkTypeUncompressedData { - if _, err := w.w.Write(uncompressed); err != nil { - w.err = err - return nRet, err - } - } - nRet += len(uncompressed) - } - return nRet, nil -} - -// Flush flushes the Writer to its underlying io.Writer. -func (w *Writer) Flush() error { - if w.err != nil { - return w.err - } - if len(w.ibuf) == 0 { - return nil - } - w.write(w.ibuf) - w.ibuf = w.ibuf[:0] - return w.err -} - -// Close calls Flush and then closes the Writer. -func (w *Writer) Close() error { - w.Flush() - ret := w.err - if w.err == nil { - w.err = errClosed - } - return ret -} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go b/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go deleted file mode 100644 index 2754bac6f..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/encode_other.go +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright 2016 The Snappy-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 snapref - -func load32(b []byte, i int) uint32 { - b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func load64(b []byte, i int) uint64 { - b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return 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 -} - -// emitLiteral writes a literal chunk and returns the number of bytes written. -// -// It assumes that: -// -// dst is long enough to hold the encoded bytes -// 1 <= len(lit) && len(lit) <= 65536 -func emitLiteral(dst, lit []byte) int { - i, n := 0, uint(len(lit)-1) - switch { - case n < 60: - dst[0] = uint8(n)<<2 | tagLiteral - i = 1 - case n < 1<<8: - dst[0] = 60<<2 | tagLiteral - dst[1] = uint8(n) - i = 2 - default: - dst[0] = 61<<2 | tagLiteral - dst[1] = uint8(n) - dst[2] = uint8(n >> 8) - i = 3 - } - return i + copy(dst[i:], lit) -} - -// emitCopy writes a copy chunk and returns the number of bytes written. -// -// It assumes that: -// -// dst is long enough to hold the encoded bytes -// 1 <= offset && offset <= 65535 -// 4 <= length && length <= 65535 -func emitCopy(dst []byte, offset, length int) int { - i := 0 - // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The - // threshold for this loop is a little higher (at 68 = 64 + 4), and the - // length emitted down below is a little lower (at 60 = 64 - 4), because - // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed - // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as - // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as - // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a - // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an - // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1. - for length >= 68 { - // Emit a length 64 copy, encoded as 3 bytes. - dst[i+0] = 63<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 64 - } - if length > 64 { - // Emit a length 60 copy, encoded as 3 bytes. - dst[i+0] = 59<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 60 - } - if length >= 12 || offset >= 2048 { - // Emit the remaining copy, encoded as 3 bytes. - dst[i+0] = uint8(length-1)<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - return i + 3 - } - // Emit the remaining copy, encoded as 2 bytes. - dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 - dst[i+1] = uint8(offset) - return i + 2 -} - -func hash(u, shift uint32) uint32 { - return (u * 0x1e35a7bd) >> shift -} - -// EncodeBlockInto exposes encodeBlock but checks dst size. -func EncodeBlockInto(dst, src []byte) (d int) { - if MaxEncodedLen(len(src)) > len(dst) { - return 0 - } - - // encodeBlock breaks on too big blocks, so split. - for len(src) > 0 { - p := src - src = nil - if len(p) > maxBlockSize { - p, src = p[:maxBlockSize], p[maxBlockSize:] - } - if len(p) < minNonLiteralBlockSize { - d += emitLiteral(dst[d:], p) - } else { - d += encodeBlock(dst[d:], p) - } - } - return d -} - -// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It -// assumes that the varint-encoded length of the decompressed bytes has already -// been written. -// -// It also assumes that: -// -// len(dst) >= MaxEncodedLen(len(src)) && -// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize -func encodeBlock(dst, src []byte) (d int) { - // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. - // The table element type is uint16, as s < sLimit and sLimit < len(src) - // and len(src) <= maxBlockSize and maxBlockSize == 65536. - const ( - maxTableSize = 1 << 14 - // tableMask is redundant, but helps the compiler eliminate bounds - // checks. - tableMask = maxTableSize - 1 - ) - shift := uint32(32 - 8) - for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - shift-- - } - // In Go, all array elements are zero-initialized, so there is no advantage - // to a smaller tableSize per se. However, it matches the C++ algorithm, - // and in the asm versions of this code, we can get away with zeroing only - // the first tableSize elements. - var table [maxTableSize]uint16 - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := len(src) - inputMargin - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := 0 - - // The encoded form must start with a literal, as there are no previous - // bytes to copy, so we start looking for hash matches at s == 1. - s := 1 - nextHash := hash(load32(src, s), shift) - - for { - // Copied from the C++ snappy implementation: - // - // Heuristic match skipping: If 32 bytes are scanned with no matches - // found, start looking only at every other byte. If 32 more bytes are - // scanned (or skipped), look at every third byte, etc.. When a match - // is found, immediately go back to looking at every byte. This is a - // small loss (~5% performance, ~0.1% density) for compressible data - // due to more bookkeeping, but for non-compressible data (such as - // JPEG) it's a huge win since the compressor quickly "realizes" the - // data is incompressible and doesn't bother looking for matches - // everywhere. - // - // The "skip" variable keeps track of how many bytes there are since - // the last match; dividing it by 32 (ie. right-shifting by five) gives - // the number of bytes to move ahead for each iteration. - skip := 32 - - nextS := s - candidate := 0 - for { - s = nextS - bytesBetweenHashLookups := skip >> 5 - nextS = s + bytesBetweenHashLookups - skip += bytesBetweenHashLookups - if nextS > sLimit { - goto emitRemainder - } - candidate = int(table[nextHash&tableMask]) - table[nextHash&tableMask] = uint16(s) - nextHash = hash(load32(src, nextS), shift) - if load32(src, s) == load32(src, candidate) { - break - } - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - d += emitLiteral(dst[d:], src[nextEmit:s]) - - // Call emitCopy, and then see if another emitCopy could be our next - // move. Repeat until we find no match for the input immediately after - // what was consumed by the last emitCopy call. - // - // If we exit this loop normally then we need to call emitLiteral next, - // though we don't yet know how big the literal will be. We handle that - // by proceeding to the next iteration of the main loop. We also can - // exit this loop via goto if we get close to exhausting the input. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - base := s - - // Extend the 4-byte match as long as possible. - // - // This is an inlined version of: - // s = extendMatch(src, candidate+4, s+4) - s += 4 - for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 { - } - - d += emitCopy(dst[d:], base-candidate, s-base) - nextEmit = s - if s >= sLimit { - goto emitRemainder - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. If - // another emitCopy is not our next move, also calculate nextHash - // at s+1. At least on GOARCH=amd64, these three hash calculations - // are faster as one load64 call (with some shifts) instead of - // three load32 calls. - x := load64(src, s-1) - prevHash := hash(uint32(x>>0), shift) - table[prevHash&tableMask] = uint16(s - 1) - currHash := hash(uint32(x>>8), shift) - candidate = int(table[currHash&tableMask]) - table[currHash&tableMask] = uint16(s) - if uint32(x>>8) != load32(src, candidate) { - nextHash = hash(uint32(x>>16), shift) - s++ - break - } - } - } - -emitRemainder: - if nextEmit < len(src) { - d += emitLiteral(dst[d:], src[nextEmit:]) - } - return d -} diff --git a/vendor/github.com/klauspost/compress/internal/snapref/snappy.go b/vendor/github.com/klauspost/compress/internal/snapref/snappy.go deleted file mode 100644 index 34d01f4aa..000000000 --- a/vendor/github.com/klauspost/compress/internal/snapref/snappy.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2011 The Snappy-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 snapref implements the Snappy compression format. It aims for very -// high speeds and reasonable compression. -// -// There are actually two Snappy formats: block and stream. They are related, -// but different: trying to decompress block-compressed data as a Snappy stream -// will fail, and vice versa. The block format is the Decode and Encode -// functions and the stream format is the Reader and Writer types. -// -// The block format, the more common case, is used when the complete size (the -// number of bytes) of the original data is known upfront, at the time -// compression starts. The stream format, also known as the framing format, is -// for when that isn't always true. -// -// The canonical, C++ implementation is at https://github.com/google/snappy and -// it only implements the block format. -package snapref - -import ( - "hash/crc32" -) - -/* -Each encoded block begins with the varint-encoded length of the decoded data, -followed by a sequence of chunks. Chunks begin and end on byte boundaries. The -first byte of each chunk is broken into its 2 least and 6 most significant bits -called l and m: l ranges in [0, 4) and m ranges in [0, 64). l is the chunk tag. -Zero means a literal tag. All other values mean a copy tag. - -For literal tags: - - If m < 60, the next 1 + m bytes are literal bytes. - - Otherwise, let n be the little-endian unsigned integer denoted by the next - m - 59 bytes. The next 1 + n bytes after that are literal bytes. - -For copy tags, length bytes are copied from offset bytes ago, in the style of -Lempel-Ziv compression algorithms. In particular: - - For l == 1, the offset ranges in [0, 1<<11) and the length in [4, 12). - The length is 4 + the low 3 bits of m. The high 3 bits of m form bits 8-10 - of the offset. The next byte is bits 0-7 of the offset. - - For l == 2, the offset ranges in [0, 1<<16) and the length in [1, 65). - The length is 1 + m. The offset is the little-endian unsigned integer - denoted by the next 2 bytes. - - For l == 3, this tag is a legacy format that is no longer issued by most - encoders. Nonetheless, the offset ranges in [0, 1<<32) and the length in - [1, 65). The length is 1 + m. The offset is the little-endian unsigned - integer denoted by the next 4 bytes. -*/ -const ( - tagLiteral = 0x00 - tagCopy1 = 0x01 - tagCopy2 = 0x02 - tagCopy4 = 0x03 -) - -const ( - checksumSize = 4 - chunkHeaderSize = 4 - magicChunk = "\xff\x06\x00\x00" + magicBody - magicBody = "sNaPpY" - - // maxBlockSize is the maximum size of the input to encodeBlock. It is not - // part of the wire format per se, but some parts of the encoder assume - // that an offset fits into a uint16. - // - // Also, for the framing format (Writer type instead of Encode function), - // https://github.com/google/snappy/blob/master/framing_format.txt says - // that "the uncompressed data in a chunk must be no longer than 65536 - // bytes". - maxBlockSize = 65536 - - // maxEncodedLenOfMaxBlockSize equals MaxEncodedLen(maxBlockSize), but is - // hard coded to be a const instead of a variable, so that obufLen can also - // be a const. Their equivalence is confirmed by - // TestMaxEncodedLenOfMaxBlockSize. - maxEncodedLenOfMaxBlockSize = 76490 - - obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize - obufLen = obufHeaderLen + maxEncodedLenOfMaxBlockSize -) - -const ( - chunkTypeCompressedData = 0x00 - chunkTypeUncompressedData = 0x01 - chunkTypePadding = 0xfe - chunkTypeStreamIdentifier = 0xff -) - -var crcTable = crc32.MakeTable(crc32.Castagnoli) - -// crc implements the checksum specified in section 3 of -// https://github.com/google/snappy/blob/master/framing_format.txt -func crc(b []byte) uint32 { - c := crc32.Update(0, crcTable, b) - return uint32(c>>15|c<<17) + 0xa282ead8 -} diff --git a/vendor/github.com/klauspost/compress/s2sx.mod b/vendor/github.com/klauspost/compress/s2sx.mod deleted file mode 100644 index 5a4412f90..000000000 --- a/vendor/github.com/klauspost/compress/s2sx.mod +++ /dev/null @@ -1,4 +0,0 @@ -module github.com/klauspost/compress - -go 1.19 - diff --git a/vendor/github.com/klauspost/compress/s2sx.sum b/vendor/github.com/klauspost/compress/s2sx.sum deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/klauspost/compress/zstd/README.md b/vendor/github.com/klauspost/compress/zstd/README.md deleted file mode 100644 index 92e2347bb..000000000 --- a/vendor/github.com/klauspost/compress/zstd/README.md +++ /dev/null @@ -1,441 +0,0 @@ -# zstd - -[Zstandard](https://facebook.github.io/zstd/) is a real-time compression algorithm, providing high compression ratios. -It offers a very wide range of compression / speed trade-off, while being backed by a very fast decoder. -A high performance compression algorithm is implemented. For now focused on speed. - -This package provides [compression](#Compressor) to and [decompression](#Decompressor) of Zstandard content. - -This package is pure Go and without use of "unsafe". - -The `zstd` package is provided as open source software using a Go standard license. - -Currently the package is heavily optimized for 64 bit processors and will be significantly slower on 32 bit processors. - -For seekable zstd streams, see [this excellent package](https://github.com/SaveTheRbtz/zstd-seekable-format-go). - -## Installation - -Install using `go get -u github.com/klauspost/compress`. The package is located in `github.com/klauspost/compress/zstd`. - -[![Go Reference](https://pkg.go.dev/badge/github.com/klauspost/compress/zstd.svg)](https://pkg.go.dev/github.com/klauspost/compress/zstd) - -## Compressor - -### Status: - -STABLE - there may always be subtle bugs, a wide variety of content has been tested and the library is actively -used by several projects. This library is being [fuzz-tested](https://github.com/klauspost/compress-fuzz) for all updates. - -There may still be specific combinations of data types/size/settings that could lead to edge cases, -so as always, testing is recommended. - -For now, a high speed (fastest) and medium-fast (default) compressor has been implemented. - -* The "Fastest" compression ratio is roughly equivalent to zstd level 1. -* The "Default" compression ratio is roughly equivalent to zstd level 3 (default). -* The "Better" compression ratio is roughly equivalent to zstd level 7. -* The "Best" compression ratio is roughly equivalent to zstd level 11. - -In terms of speed, it is typically 2x as fast as the stdlib deflate/gzip in its fastest mode. -The compression ratio compared to stdlib is around level 3, but usually 3x as fast. - - -### Usage - -An Encoder can be used for either compressing a stream via the -`io.WriteCloser` interface supported by the Encoder or as multiple independent -tasks via the `EncodeAll` function. -Smaller encodes are encouraged to use the EncodeAll function. -Use `NewWriter` to create a new instance that can be used for both. - -To create a writer with default options, do like this: - -```Go -// Compress input to output. -func Compress(in io.Reader, out io.Writer) error { - enc, err := zstd.NewWriter(out) - if err != nil { - return err - } - _, err = io.Copy(enc, in) - if err != nil { - enc.Close() - return err - } - return enc.Close() -} -``` - -Now you can encode by writing data to `enc`. The output will be finished writing when `Close()` is called. -Even if your encode fails, you should still call `Close()` to release any resources that may be held up. - -The above is fine for big encodes. However, whenever possible try to *reuse* the writer. - -To reuse the encoder, you can use the `Reset(io.Writer)` function to change to another output. -This will allow the encoder to reuse all resources and avoid wasteful allocations. - -Currently stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part -of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change -in the future. So if you want to limit concurrency for future updates, specify the concurrency -you would like. - -If you would like stream encoding to be done without spawning async goroutines, use `WithEncoderConcurrency(1)` -which will compress input as each block is completed, blocking on writes until each has completed. - -You can specify your desired compression level using `WithEncoderLevel()` option. Currently only pre-defined -compression settings can be specified. - -#### Future Compatibility Guarantees - -This will be an evolving project. When using this package it is important to note that both the compression efficiency and speed may change. - -The goal will be to keep the default efficiency at the default zstd (level 3). -However the encoding should never be assumed to remain the same, -and you should not use hashes of compressed output for similarity checks. - -The Encoder can be assumed to produce the same output from the exact same code version. -However, the may be modes in the future that break this, -although they will not be enabled without an explicit option. - -This encoder is not designed to (and will probably never) output the exact same bitstream as the reference encoder. - -Also note, that the cgo decompressor currently does not [report all errors on invalid input](https://github.com/DataDog/zstd/issues/59), -[omits error checks](https://github.com/DataDog/zstd/issues/61), [ignores checksums](https://github.com/DataDog/zstd/issues/43) -and seems to ignore concatenated streams, even though [it is part of the spec](https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frames). - -#### Blocks - -For compressing small blocks, the returned encoder has a function called `EncodeAll(src, dst []byte) []byte`. - -`EncodeAll` will encode all input in src and append it to dst. -This function can be called concurrently. -Each call will only run on a same goroutine as the caller. - -Encoded blocks can be concatenated and the result will be the combined input stream. -Data compressed with EncodeAll can be decoded with the Decoder, using either a stream or `DecodeAll`. - -Especially when encoding blocks you should take special care to reuse the encoder. -This will effectively make it run without allocations after a warmup period. -To make it run completely without allocations, supply a destination buffer with space for all content. - -```Go -import "github.com/klauspost/compress/zstd" - -// Create a writer that caches compressors. -// For this operation type we supply a nil Reader. -var encoder, _ = zstd.NewWriter(nil) - -// Compress a buffer. -// If you have a destination buffer, the allocation in the call can also be eliminated. -func Compress(src []byte) []byte { - return encoder.EncodeAll(src, make([]byte, 0, len(src))) -} -``` - -You can control the maximum number of concurrent encodes using the `WithEncoderConcurrency(n)` -option when creating the writer. - -Using the Encoder for both a stream and individual blocks concurrently is safe. - -### Performance - -I have collected some speed examples to compare speed and compression against other compressors. - -* `file` is the input file. -* `out` is the compressor used. `zskp` is this package. `zstd` is the Datadog cgo library. `gzstd/gzkp` is gzip standard and this library. -* `level` is the compression level used. For `zskp` level 1 is "fastest", level 2 is "default"; 3 is "better", 4 is "best". -* `insize`/`outsize` is the input/output size. -* `millis` is the number of milliseconds used for compression. -* `mb/s` is megabytes (2^20 bytes) per second. - -``` -Silesia Corpus: -http://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip - -This package: -file out level insize outsize millis mb/s -silesia.tar zskp 1 211947520 73821326 634 318.47 -silesia.tar zskp 2 211947520 67655404 1508 133.96 -silesia.tar zskp 3 211947520 64746933 3000 67.37 -silesia.tar zskp 4 211947520 60073508 16926 11.94 - -cgo zstd: -silesia.tar zstd 1 211947520 73605392 543 371.56 -silesia.tar zstd 3 211947520 66793289 864 233.68 -silesia.tar zstd 6 211947520 62916450 1913 105.66 -silesia.tar zstd 9 211947520 60212393 5063 39.92 - -gzip, stdlib/this package: -silesia.tar gzstd 1 211947520 80007735 1498 134.87 -silesia.tar gzkp 1 211947520 80088272 1009 200.31 - -GOB stream of binary data. Highly compressible. -https://files.klauspost.com/compress/gob-stream.7z - -file out level insize outsize millis mb/s -gob-stream zskp 1 1911399616 233948096 3230 564.34 -gob-stream zskp 2 1911399616 203997694 4997 364.73 -gob-stream zskp 3 1911399616 173526523 13435 135.68 -gob-stream zskp 4 1911399616 162195235 47559 38.33 - -gob-stream zstd 1 1911399616 249810424 2637 691.26 -gob-stream zstd 3 1911399616 208192146 3490 522.31 -gob-stream zstd 6 1911399616 193632038 6687 272.56 -gob-stream zstd 9 1911399616 177620386 16175 112.70 - -gob-stream gzstd 1 1911399616 357382013 9046 201.49 -gob-stream gzkp 1 1911399616 359136669 4885 373.08 - -The test data for the Large Text Compression Benchmark is the first -10^9 bytes of the English Wikipedia dump on Mar. 3, 2006. -http://mattmahoney.net/dc/textdata.html - -file out level insize outsize millis mb/s -enwik9 zskp 1 1000000000 343833605 3687 258.64 -enwik9 zskp 2 1000000000 317001237 7672 124.29 -enwik9 zskp 3 1000000000 291915823 15923 59.89 -enwik9 zskp 4 1000000000 261710291 77697 12.27 - -enwik9 zstd 1 1000000000 358072021 3110 306.65 -enwik9 zstd 3 1000000000 313734672 4784 199.35 -enwik9 zstd 6 1000000000 295138875 10290 92.68 -enwik9 zstd 9 1000000000 278348700 28549 33.40 - -enwik9 gzstd 1 1000000000 382578136 8608 110.78 -enwik9 gzkp 1 1000000000 382781160 5628 169.45 - -Highly compressible JSON file. -https://files.klauspost.com/compress/github-june-2days-2019.json.zst - -file out level insize outsize millis mb/s -github-june-2days-2019.json zskp 1 6273951764 697439532 9789 611.17 -github-june-2days-2019.json zskp 2 6273951764 610876538 18553 322.49 -github-june-2days-2019.json zskp 3 6273951764 517662858 44186 135.41 -github-june-2days-2019.json zskp 4 6273951764 464617114 165373 36.18 - -github-june-2days-2019.json zstd 1 6273951764 766284037 8450 708.00 -github-june-2days-2019.json zstd 3 6273951764 661889476 10927 547.57 -github-june-2days-2019.json zstd 6 6273951764 642756859 22996 260.18 -github-june-2days-2019.json zstd 9 6273951764 601974523 52413 114.16 - -github-june-2days-2019.json gzstd 1 6273951764 1164397768 26793 223.32 -github-june-2days-2019.json gzkp 1 6273951764 1120631856 17693 338.16 - -VM Image, Linux mint with a few installed applications: -https://files.klauspost.com/compress/rawstudio-mint14.7z - -file out level insize outsize millis mb/s -rawstudio-mint14.tar zskp 1 8558382592 3718400221 18206 448.29 -rawstudio-mint14.tar zskp 2 8558382592 3326118337 37074 220.15 -rawstudio-mint14.tar zskp 3 8558382592 3163842361 87306 93.49 -rawstudio-mint14.tar zskp 4 8558382592 2970480650 783862 10.41 - -rawstudio-mint14.tar zstd 1 8558382592 3609250104 17136 476.27 -rawstudio-mint14.tar zstd 3 8558382592 3341679997 29262 278.92 -rawstudio-mint14.tar zstd 6 8558382592 3235846406 77904 104.77 -rawstudio-mint14.tar zstd 9 8558382592 3160778861 140946 57.91 - -rawstudio-mint14.tar gzstd 1 8558382592 3926234992 51345 158.96 -rawstudio-mint14.tar gzkp 1 8558382592 3960117298 36722 222.26 - -CSV data: -https://files.klauspost.com/compress/nyc-taxi-data-10M.csv.zst - -file out level insize outsize millis mb/s -nyc-taxi-data-10M.csv zskp 1 3325605752 641319332 9462 335.17 -nyc-taxi-data-10M.csv zskp 2 3325605752 588976126 17570 180.50 -nyc-taxi-data-10M.csv zskp 3 3325605752 529329260 32432 97.79 -nyc-taxi-data-10M.csv zskp 4 3325605752 474949772 138025 22.98 - -nyc-taxi-data-10M.csv zstd 1 3325605752 687399637 8233 385.18 -nyc-taxi-data-10M.csv zstd 3 3325605752 598514411 10065 315.07 -nyc-taxi-data-10M.csv zstd 6 3325605752 570522953 20038 158.27 -nyc-taxi-data-10M.csv zstd 9 3325605752 517554797 64565 49.12 - -nyc-taxi-data-10M.csv gzstd 1 3325605752 928654908 21270 149.11 -nyc-taxi-data-10M.csv gzkp 1 3325605752 922273214 13929 227.68 -``` - -## Decompressor - -Status: STABLE - there may still be subtle bugs, but a wide variety of content has been tested. - -This library is being continuously [fuzz-tested](https://github.com/klauspost/compress-fuzz), -kindly supplied by [fuzzit.dev](https://fuzzit.dev/). -The main purpose of the fuzz testing is to ensure that it is not possible to crash the decoder, -or run it past its limits with ANY input provided. - -### Usage - -The package has been designed for two main usages, big streams of data and smaller in-memory buffers. -There are two main usages of the package for these. Both of them are accessed by creating a `Decoder`. - -For streaming use a simple setup could look like this: - -```Go -import "github.com/klauspost/compress/zstd" - -func Decompress(in io.Reader, out io.Writer) error { - d, err := zstd.NewReader(in) - if err != nil { - return err - } - defer d.Close() - - // Copy content... - _, err = io.Copy(out, d) - return err -} -``` - -It is important to use the "Close" function when you no longer need the Reader to stop running goroutines, -when running with default settings. -Goroutines will exit once an error has been returned, including `io.EOF` at the end of a stream. - -Streams are decoded concurrently in 4 asynchronous stages to give the best possible throughput. -However, if you prefer synchronous decompression, use `WithDecoderConcurrency(1)` which will decompress data -as it is being requested only. - -For decoding buffers, it could look something like this: - -```Go -import "github.com/klauspost/compress/zstd" - -// Create a reader that caches decompressors. -// For this operation type we supply a nil Reader. -var decoder, _ = zstd.NewReader(nil, zstd.WithDecoderConcurrency(0)) - -// Decompress a buffer. We don't supply a destination buffer, -// so it will be allocated by the decoder. -func Decompress(src []byte) ([]byte, error) { - return decoder.DecodeAll(src, nil) -} -``` - -Both of these cases should provide the functionality needed. -The decoder can be used for *concurrent* decompression of multiple buffers. -By default 4 decompressors will be created. - -It will only allow a certain number of concurrent operations to run. -To tweak that yourself use the `WithDecoderConcurrency(n)` option when creating the decoder. -It is possible to use `WithDecoderConcurrency(0)` to create GOMAXPROCS decoders. - -### Dictionaries - -Data compressed with [dictionaries](https://github.com/facebook/zstd#the-case-for-small-data-compression) can be decompressed. - -Dictionaries are added individually to Decoders. -Dictionaries are generated by the `zstd --train` command and contains an initial state for the decoder. -To add a dictionary use the `WithDecoderDicts(dicts ...[]byte)` option with the dictionary data. -Several dictionaries can be added at once. - -The dictionary will be used automatically for the data that specifies them. -A re-used Decoder will still contain the dictionaries registered. - -When registering multiple dictionaries with the same ID, the last one will be used. - -It is possible to use dictionaries when compressing data. - -To enable a dictionary use `WithEncoderDict(dict []byte)`. Here only one dictionary will be used -and it will likely be used even if it doesn't improve compression. - -The used dictionary must be used to decompress the content. - -For any real gains, the dictionary should be built with similar data. -If an unsuitable dictionary is used the output may be slightly larger than using no dictionary. -Use the [zstd commandline tool](https://github.com/facebook/zstd/releases) to build a dictionary from sample data. -For information see [zstd dictionary information](https://github.com/facebook/zstd#the-case-for-small-data-compression). - -For now there is a fixed startup performance penalty for compressing content with dictionaries. -This will likely be improved over time. Just be aware to test performance when implementing. - -### Allocation-less operation - -The decoder has been designed to operate without allocations after a warmup. - -This means that you should *store* the decoder for best performance. -To re-use a stream decoder, use the `Reset(r io.Reader) error` to switch to another stream. -A decoder can safely be re-used even if the previous stream failed. - -To release the resources, you must call the `Close()` function on a decoder. -After this it can *no longer be reused*, but all running goroutines will be stopped. -So you *must* use this if you will no longer need the Reader. - -For decompressing smaller buffers a single decoder can be used. -When decoding buffers, you can supply a destination slice with length 0 and your expected capacity. -In this case no unneeded allocations should be made. - -### Concurrency - -The buffer decoder does everything on the same goroutine and does nothing concurrently. -It can however decode several buffers concurrently. Use `WithDecoderConcurrency(n)` to limit that. - -The stream decoder will create goroutines that: - -1) Reads input and splits the input into blocks. -2) Decompression of literals. -3) Decompression of sequences. -4) Reconstruction of output stream. - -So effectively this also means the decoder will "read ahead" and prepare data to always be available for output. - -The concurrency level will, for streams, determine how many blocks ahead the compression will start. - -Since "blocks" are quite dependent on the output of the previous block stream decoding will only have limited concurrency. - -In practice this means that concurrency is often limited to utilizing about 3 cores effectively. - -### Benchmarks - -The first two are streaming decodes and the last are smaller inputs. - -Running on AMD Ryzen 9 3950X 16-Core Processor. AMD64 assembly used. - -``` -BenchmarkDecoderSilesia-32 5 206878840 ns/op 1024.50 MB/s 49808 B/op 43 allocs/op -BenchmarkDecoderEnwik9-32 1 1271809000 ns/op 786.28 MB/s 72048 B/op 52 allocs/op - -Concurrent blocks, performance: - -BenchmarkDecoder_DecodeAllParallel/kppkn.gtb.zst-32 67356 17857 ns/op 10321.96 MB/s 22.48 pct 102 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/geo.protodata.zst-32 266656 4421 ns/op 26823.21 MB/s 11.89 pct 19 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/plrabn12.txt.zst-32 20992 56842 ns/op 8477.17 MB/s 39.90 pct 754 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/lcet10.txt.zst-32 27456 43932 ns/op 9714.01 MB/s 33.27 pct 524 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/asyoulik.txt.zst-32 78432 15047 ns/op 8319.15 MB/s 40.34 pct 66 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/alice29.txt.zst-32 65800 18436 ns/op 8249.63 MB/s 37.75 pct 88 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/html_x_4.zst-32 102993 11523 ns/op 35546.09 MB/s 3.637 pct 143 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/paper-100k.pdf.zst-32 1000000 1070 ns/op 95720.98 MB/s 80.53 pct 3 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/fireworks.jpeg.zst-32 749802 1752 ns/op 70272.35 MB/s 100.0 pct 5 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/urls.10K.zst-32 22640 52934 ns/op 13263.37 MB/s 26.25 pct 1014 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/html.zst-32 226412 5232 ns/op 19572.27 MB/s 14.49 pct 20 B/op 0 allocs/op -BenchmarkDecoder_DecodeAllParallel/comp-data.bin.zst-32 923041 1276 ns/op 3194.71 MB/s 31.26 pct 0 B/op 0 allocs/op -``` - -This reflects the performance around May 2022, but this may be out of date. - -## Zstd inside ZIP files - -It is possible to use zstandard to compress individual files inside zip archives. -While this isn't widely supported it can be useful for internal files. - -To support the compression and decompression of these files you must register a compressor and decompressor. - -It is highly recommended registering the (de)compressors on individual zip Reader/Writer and NOT -use the global registration functions. The main reason for this is that 2 registrations from -different packages will result in a panic. - -It is a good idea to only have a single compressor and decompressor, since they can be used for multiple zip -files concurrently, and using a single instance will allow reusing some resources. - -See [this example](https://pkg.go.dev/github.com/klauspost/compress/zstd#example-ZipCompressor) for -how to compress and decompress files inside zip archives. - -# Contributions - -Contributions are always welcome. -For new features/fixes, remember to add tests and for performance enhancements include benchmarks. - -For general feedback and experience reports, feel free to open an issue or write me on [Twitter](https://twitter.com/sh0dan). - -This package includes the excellent [`github.com/cespare/xxhash`](https://github.com/cespare/xxhash) package Copyright (c) 2016 Caleb Spare. diff --git a/vendor/github.com/klauspost/compress/zstd/bitreader.go b/vendor/github.com/klauspost/compress/zstd/bitreader.go deleted file mode 100644 index 25ca98394..000000000 --- a/vendor/github.com/klauspost/compress/zstd/bitreader.go +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "math/bits" -) - -// bitReader reads a bitstream in reverse. -// The last set bit indicates the start of the stream and is used -// for aligning the input. -type bitReader struct { - in []byte - value uint64 // Maybe use [16]byte, but shifting is awkward. - bitsRead uint8 -} - -// init initializes and resets the bit reader. -func (b *bitReader) init(in []byte) error { - if len(in) < 1 { - return errors.New("corrupt stream: too short") - } - b.in = in - // The highest bit of the last byte indicates where to start - v := in[len(in)-1] - if v == 0 { - return errors.New("corrupt stream, did not find end of stream") - } - b.bitsRead = 64 - b.value = 0 - if len(in) >= 8 { - b.fillFastStart() - } else { - b.fill() - b.fill() - } - b.bitsRead += 8 - uint8(highBits(uint32(v))) - return nil -} - -// getBits will return n bits. n can be 0. -func (b *bitReader) getBits(n uint8) int { - if n == 0 /*|| b.bitsRead >= 64 */ { - return 0 - } - return int(b.get32BitsFast(n)) -} - -// get32BitsFast requires that at least one bit is requested every time. -// There are no checks if the buffer is filled. -func (b *bitReader) get32BitsFast(n uint8) uint32 { - const regMask = 64 - 1 - v := uint32((b.value << (b.bitsRead & regMask)) >> ((regMask + 1 - n) & regMask)) - b.bitsRead += n - return v -} - -// fillFast() will make sure at least 32 bits are available. -// There must be at least 4 bytes available. -func (b *bitReader) fillFast() { - if b.bitsRead < 32 { - return - } - v := b.in[len(b.in)-4:] - b.in = b.in[:len(b.in)-4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value = (b.value << 32) | uint64(low) - b.bitsRead -= 32 -} - -// fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read. -func (b *bitReader) fillFastStart() { - v := b.in[len(b.in)-8:] - b.in = b.in[:len(b.in)-8] - b.value = binary.LittleEndian.Uint64(v) - b.bitsRead = 0 -} - -// fill() will make sure at least 32 bits are available. -func (b *bitReader) fill() { - if b.bitsRead < 32 { - return - } - if len(b.in) >= 4 { - v := b.in[len(b.in)-4:] - b.in = b.in[:len(b.in)-4] - low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) - b.value = (b.value << 32) | uint64(low) - b.bitsRead -= 32 - return - } - - b.bitsRead -= uint8(8 * len(b.in)) - for len(b.in) > 0 { - b.value = (b.value << 8) | uint64(b.in[len(b.in)-1]) - b.in = b.in[:len(b.in)-1] - } -} - -// finished returns true if all bits have been read from the bit stream. -func (b *bitReader) finished() bool { - return len(b.in) == 0 && b.bitsRead >= 64 -} - -// overread returns true if more bits have been requested than is on the stream. -func (b *bitReader) overread() bool { - return b.bitsRead > 64 -} - -// remain returns the number of bits remaining. -func (b *bitReader) remain() uint { - return 8*uint(len(b.in)) + 64 - uint(b.bitsRead) -} - -// close the bitstream and returns an error if out-of-buffer reads occurred. -func (b *bitReader) close() error { - // Release reference. - b.in = nil - if !b.finished() { - return fmt.Errorf("%d extra bits on block, should be 0", b.remain()) - } - if b.bitsRead > 64 { - return io.ErrUnexpectedEOF - } - return nil -} - -func highBits(val uint32) (n uint32) { - return uint32(bits.Len32(val) - 1) -} diff --git a/vendor/github.com/klauspost/compress/zstd/bitwriter.go b/vendor/github.com/klauspost/compress/zstd/bitwriter.go deleted file mode 100644 index 1952f175b..000000000 --- a/vendor/github.com/klauspost/compress/zstd/bitwriter.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2018 Klaus Post. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// Based on work Copyright (c) 2013, Yann Collet, released under BSD License. - -package zstd - -// bitWriter will write bits. -// First bit will be LSB of the first byte of output. -type bitWriter struct { - bitContainer uint64 - nBits uint8 - out []byte -} - -// bitMask16 is bitmasks. Has extra to avoid bounds check. -var bitMask16 = [32]uint16{ - 0, 1, 3, 7, 0xF, 0x1F, - 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, - 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0xFFFF, - 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, - 0xFFFF, 0xFFFF} /* up to 16 bits */ - -var bitMask32 = [32]uint32{ - 0, 1, 3, 7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF, - 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, - 0x1ffff, 0x3ffff, 0x7FFFF, 0xfFFFF, 0x1fFFFF, 0x3fFFFF, 0x7fFFFF, 0xffFFFF, - 0x1ffFFFF, 0x3ffFFFF, 0x7ffFFFF, 0xfffFFFF, 0x1fffFFFF, 0x3fffFFFF, 0x7fffFFFF, -} // up to 32 bits - -// addBits16NC will add up to 16 bits. -// It will not check if there is space for them, -// so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16NC(value uint16, bits uint8) { - b.bitContainer |= uint64(value&bitMask16[bits&31]) << (b.nBits & 63) - b.nBits += bits -} - -// addBits32NC will add up to 31 bits. -// It will not check if there is space for them, -// so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits32NC(value uint32, bits uint8) { - b.bitContainer |= uint64(value&bitMask32[bits&31]) << (b.nBits & 63) - b.nBits += bits -} - -// addBits64NC will add up to 64 bits. -// There must be space for 32 bits. -func (b *bitWriter) addBits64NC(value uint64, bits uint8) { - if bits <= 31 { - b.addBits32Clean(uint32(value), bits) - return - } - b.addBits32Clean(uint32(value), 32) - b.flush32() - b.addBits32Clean(uint32(value>>32), bits-32) -} - -// addBits32Clean will add up to 32 bits. -// It will not check if there is space for them. -// The input must not contain more bits than specified. -func (b *bitWriter) addBits32Clean(value uint32, bits uint8) { - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// addBits16Clean will add up to 16 bits. value may not contain more set bits than indicated. -// It will not check if there is space for them, so the caller must ensure that it has flushed recently. -func (b *bitWriter) addBits16Clean(value uint16, bits uint8) { - b.bitContainer |= uint64(value) << (b.nBits & 63) - b.nBits += bits -} - -// flush32 will flush out, so there are at least 32 bits available for writing. -func (b *bitWriter) flush32() { - if b.nBits < 32 { - return - } - b.out = append(b.out, - byte(b.bitContainer), - byte(b.bitContainer>>8), - byte(b.bitContainer>>16), - byte(b.bitContainer>>24)) - b.nBits -= 32 - b.bitContainer >>= 32 -} - -// flushAlign will flush remaining full bytes and align to next byte boundary. -func (b *bitWriter) flushAlign() { - nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { - b.out = append(b.out, byte(b.bitContainer>>(i*8))) - } - b.nBits = 0 - b.bitContainer = 0 -} - -// close will write the alignment bit and write the final byte(s) -// to the output. -func (b *bitWriter) close() { - // End mark - b.addBits16Clean(1, 1) - // flush until next byte. - b.flushAlign() -} - -// reset and continue writing by appending to out. -func (b *bitWriter) reset(out []byte) { - b.bitContainer = 0 - b.nBits = 0 - b.out = out -} diff --git a/vendor/github.com/klauspost/compress/zstd/blockdec.go b/vendor/github.com/klauspost/compress/zstd/blockdec.go deleted file mode 100644 index 03744fbc7..000000000 --- a/vendor/github.com/klauspost/compress/zstd/blockdec.go +++ /dev/null @@ -1,729 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "hash/crc32" - "io" - "os" - "path/filepath" - "sync" - - "github.com/klauspost/compress/huff0" - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -type blockType uint8 - -//go:generate stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex - -const ( - blockTypeRaw blockType = iota - blockTypeRLE - blockTypeCompressed - blockTypeReserved -) - -type literalsBlockType uint8 - -const ( - literalsBlockRaw literalsBlockType = iota - literalsBlockRLE - literalsBlockCompressed - literalsBlockTreeless -) - -const ( - // maxCompressedBlockSize is the biggest allowed compressed block size (128KB) - maxCompressedBlockSize = 128 << 10 - - compressedBlockOverAlloc = 16 - maxCompressedBlockSizeAlloc = 128<<10 + compressedBlockOverAlloc - - // Maximum possible block size (all Raw+Uncompressed). - maxBlockSize = (1 << 21) - 1 - - maxMatchLen = 131074 - maxSequences = 0x7f00 + 0xffff - - // We support slightly less than the reference decoder to be able to - // use ints on 32 bit archs. - maxOffsetBits = 30 -) - -var ( - huffDecoderPool = sync.Pool{New: func() interface{} { - return &huff0.Scratch{} - }} - - fseDecoderPool = sync.Pool{New: func() interface{} { - return &fseDecoder{} - }} -) - -type blockDec struct { - // Raw source data of the block. - data []byte - dataStorage []byte - - // Destination of the decoded data. - dst []byte - - // Buffer for literals data. - literalBuf []byte - - // Window size of the block. - WindowSize uint64 - - err error - - // Check against this crc, if hasCRC is true. - checkCRC uint32 - hasCRC bool - - // Frame to use for singlethreaded decoding. - // Should not be used by the decoder itself since parent may be another frame. - localFrame *frameDec - - sequence []seqVals - - async struct { - newHist *history - literals []byte - seqData []byte - seqSize int // Size of uncompressed sequences - fcs uint64 - } - - // Block is RLE, this is the size. - RLESize uint32 - - Type blockType - - // Is this the last block of a frame? - Last bool - - // Use less memory - lowMem bool -} - -func (b *blockDec) String() string { - if b == nil { - return "" - } - return fmt.Sprintf("Steam Size: %d, Type: %v, Last: %t, Window: %d", len(b.data), b.Type, b.Last, b.WindowSize) -} - -func newBlockDec(lowMem bool) *blockDec { - b := blockDec{ - lowMem: lowMem, - } - return &b -} - -// reset will reset the block. -// Input must be a start of a block and will be at the end of the block when returned. -func (b *blockDec) reset(br byteBuffer, windowSize uint64) error { - b.WindowSize = windowSize - tmp, err := br.readSmall(3) - if err != nil { - println("Reading block header:", err) - return err - } - bh := uint32(tmp[0]) | (uint32(tmp[1]) << 8) | (uint32(tmp[2]) << 16) - b.Last = bh&1 != 0 - b.Type = blockType((bh >> 1) & 3) - // find size. - cSize := int(bh >> 3) - maxSize := maxCompressedBlockSizeAlloc - switch b.Type { - case blockTypeReserved: - return ErrReservedBlockType - case blockTypeRLE: - if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) { - if debugDecoder { - printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b) - } - return ErrWindowSizeExceeded - } - b.RLESize = uint32(cSize) - if b.lowMem { - maxSize = cSize - } - cSize = 1 - case blockTypeCompressed: - if debugDecoder { - println("Data size on stream:", cSize) - } - b.RLESize = 0 - maxSize = maxCompressedBlockSizeAlloc - if windowSize < maxCompressedBlockSize && b.lowMem { - maxSize = int(windowSize) + compressedBlockOverAlloc - } - if cSize > maxCompressedBlockSize || uint64(cSize) > b.WindowSize { - if debugDecoder { - printf("compressed block too big: csize:%d block: %+v\n", uint64(cSize), b) - } - return ErrCompressedSizeTooBig - } - // Empty compressed blocks must at least be 2 bytes - // for Literals_Block_Type and one for Sequences_Section_Header. - if cSize < 2 { - return ErrBlockTooSmall - } - case blockTypeRaw: - if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) { - if debugDecoder { - printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b) - } - return ErrWindowSizeExceeded - } - - b.RLESize = 0 - // We do not need a destination for raw blocks. - maxSize = -1 - default: - panic("Invalid block type") - } - - // Read block data. - if _, ok := br.(*byteBuf); !ok && cap(b.dataStorage) < cSize { - // byteBuf doesn't need a destination buffer. - if b.lowMem || cSize > maxCompressedBlockSize { - b.dataStorage = make([]byte, 0, cSize+compressedBlockOverAlloc) - } else { - b.dataStorage = make([]byte, 0, maxCompressedBlockSizeAlloc) - } - } - b.data, err = br.readBig(cSize, b.dataStorage) - if err != nil { - if debugDecoder { - println("Reading block:", err, "(", cSize, ")", len(b.data)) - printf("%T", br) - } - return err - } - if cap(b.dst) <= maxSize { - b.dst = make([]byte, 0, maxSize+1) - } - return nil -} - -// sendEOF will make the decoder send EOF on this frame. -func (b *blockDec) sendErr(err error) { - b.Last = true - b.Type = blockTypeReserved - b.err = err -} - -// Close will release resources. -// Closed blockDec cannot be reset. -func (b *blockDec) Close() { -} - -// decodeBuf -func (b *blockDec) decodeBuf(hist *history) error { - switch b.Type { - case blockTypeRLE: - if cap(b.dst) < int(b.RLESize) { - if b.lowMem { - b.dst = make([]byte, b.RLESize) - } else { - b.dst = make([]byte, maxCompressedBlockSize) - } - } - b.dst = b.dst[:b.RLESize] - v := b.data[0] - for i := range b.dst { - b.dst[i] = v - } - hist.appendKeep(b.dst) - return nil - case blockTypeRaw: - hist.appendKeep(b.data) - return nil - case blockTypeCompressed: - saved := b.dst - // Append directly to history - if hist.ignoreBuffer == 0 { - b.dst = hist.b - hist.b = nil - } else { - b.dst = b.dst[:0] - } - err := b.decodeCompressed(hist) - if debugDecoder { - println("Decompressed to total", len(b.dst), "bytes, hash:", xxhash.Sum64(b.dst), "error:", err) - } - if hist.ignoreBuffer == 0 { - hist.b = b.dst - b.dst = saved - } else { - hist.appendKeep(b.dst) - } - return err - case blockTypeReserved: - // Used for returning errors. - return b.err - default: - panic("Invalid block type") - } -} - -func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err error) { - // There must be at least one byte for Literals_Block_Type and one for Sequences_Section_Header - if len(in) < 2 { - return in, ErrBlockTooSmall - } - - litType := literalsBlockType(in[0] & 3) - var litRegenSize int - var litCompSize int - sizeFormat := (in[0] >> 2) & 3 - var fourStreams bool - var literals []byte - switch litType { - case literalsBlockRaw, literalsBlockRLE: - switch sizeFormat { - case 0, 2: - // Regenerated_Size uses 5 bits (0-31). Literals_Section_Header uses 1 byte. - litRegenSize = int(in[0] >> 3) - in = in[1:] - case 1: - // Regenerated_Size uses 12 bits (0-4095). Literals_Section_Header uses 2 bytes. - litRegenSize = int(in[0]>>4) + (int(in[1]) << 4) - in = in[2:] - case 3: - // Regenerated_Size uses 20 bits (0-1048575). Literals_Section_Header uses 3 bytes. - if len(in) < 3 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) - return in, ErrBlockTooSmall - } - litRegenSize = int(in[0]>>4) + (int(in[1]) << 4) + (int(in[2]) << 12) - in = in[3:] - } - case literalsBlockCompressed, literalsBlockTreeless: - switch sizeFormat { - case 0, 1: - // Both Regenerated_Size and Compressed_Size use 10 bits (0-1023). - if len(in) < 3 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) - return in, ErrBlockTooSmall - } - n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) - litRegenSize = int(n & 1023) - litCompSize = int(n >> 10) - fourStreams = sizeFormat == 1 - in = in[3:] - case 2: - fourStreams = true - if len(in) < 4 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) - return in, ErrBlockTooSmall - } - n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20) - litRegenSize = int(n & 16383) - litCompSize = int(n >> 14) - in = in[4:] - case 3: - fourStreams = true - if len(in) < 5 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in)) - return in, ErrBlockTooSmall - } - n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20) + (uint64(in[4]) << 28) - litRegenSize = int(n & 262143) - litCompSize = int(n >> 18) - in = in[5:] - } - } - if debugDecoder { - println("literals type:", litType, "litRegenSize:", litRegenSize, "litCompSize:", litCompSize, "sizeFormat:", sizeFormat, "4X:", fourStreams) - } - if litRegenSize > int(b.WindowSize) || litRegenSize > maxCompressedBlockSize { - return in, ErrWindowSizeExceeded - } - - switch litType { - case literalsBlockRaw: - if len(in) < litRegenSize { - println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litRegenSize) - return in, ErrBlockTooSmall - } - literals = in[:litRegenSize] - in = in[litRegenSize:] - //printf("Found %d uncompressed literals\n", litRegenSize) - case literalsBlockRLE: - if len(in) < 1 { - println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", 1) - return in, ErrBlockTooSmall - } - if cap(b.literalBuf) < litRegenSize { - if b.lowMem { - b.literalBuf = make([]byte, litRegenSize, litRegenSize+compressedBlockOverAlloc) - } else { - b.literalBuf = make([]byte, litRegenSize, maxCompressedBlockSize+compressedBlockOverAlloc) - } - } - literals = b.literalBuf[:litRegenSize] - v := in[0] - for i := range literals { - literals[i] = v - } - in = in[1:] - if debugDecoder { - printf("Found %d RLE compressed literals\n", litRegenSize) - } - case literalsBlockTreeless: - if len(in) < litCompSize { - println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize) - return in, ErrBlockTooSmall - } - // Store compressed literals, so we defer decoding until we get history. - literals = in[:litCompSize] - in = in[litCompSize:] - if debugDecoder { - printf("Found %d compressed literals\n", litCompSize) - } - huff := hist.huffTree - if huff == nil { - return in, errors.New("literal block was treeless, but no history was defined") - } - // Ensure we have space to store it. - if cap(b.literalBuf) < litRegenSize { - if b.lowMem { - b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc) - } else { - b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc) - } - } - var err error - // Use our out buffer. - huff.MaxDecodedSize = litRegenSize - if fourStreams { - literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals) - } else { - literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals) - } - // Make sure we don't leak our literals buffer - if err != nil { - println("decompressing literals:", err) - return in, err - } - if len(literals) != litRegenSize { - return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals)) - } - - case literalsBlockCompressed: - if len(in) < litCompSize { - println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize) - return in, ErrBlockTooSmall - } - literals = in[:litCompSize] - in = in[litCompSize:] - // Ensure we have space to store it. - if cap(b.literalBuf) < litRegenSize { - if b.lowMem { - b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc) - } else { - b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc) - } - } - huff := hist.huffTree - if huff == nil || (hist.dict != nil && huff == hist.dict.litEnc) { - huff = huffDecoderPool.Get().(*huff0.Scratch) - if huff == nil { - huff = &huff0.Scratch{} - } - } - var err error - if debugDecoder { - println("huff table input:", len(literals), "CRC:", crc32.ChecksumIEEE(literals)) - } - huff, literals, err = huff0.ReadTable(literals, huff) - if err != nil { - println("reading huffman table:", err) - return in, err - } - hist.huffTree = huff - huff.MaxDecodedSize = litRegenSize - // Use our out buffer. - if fourStreams { - literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals) - } else { - literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals) - } - if err != nil { - println("decoding compressed literals:", err) - return in, err - } - // Make sure we don't leak our literals buffer - if len(literals) != litRegenSize { - return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals)) - } - // Re-cap to get extra size. - literals = b.literalBuf[:len(literals)] - if debugDecoder { - printf("Decompressed %d literals into %d bytes\n", litCompSize, litRegenSize) - } - } - hist.decoders.literals = literals - return in, nil -} - -// decodeCompressed will start decompressing a block. -func (b *blockDec) decodeCompressed(hist *history) error { - in := b.data - in, err := b.decodeLiterals(in, hist) - if err != nil { - return err - } - err = b.prepareSequences(in, hist) - if err != nil { - return err - } - if hist.decoders.nSeqs == 0 { - b.dst = append(b.dst, hist.decoders.literals...) - return nil - } - before := len(hist.decoders.out) - err = hist.decoders.decodeSync(hist.b[hist.ignoreBuffer:]) - if err != nil { - return err - } - if hist.decoders.maxSyncLen > 0 { - hist.decoders.maxSyncLen += uint64(before) - hist.decoders.maxSyncLen -= uint64(len(hist.decoders.out)) - } - b.dst = hist.decoders.out - hist.recentOffsets = hist.decoders.prevOffset - return nil -} - -func (b *blockDec) prepareSequences(in []byte, hist *history) (err error) { - if debugDecoder { - printf("prepareSequences: %d byte(s) input\n", len(in)) - } - // Decode Sequences - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#sequences-section - if len(in) < 1 { - return ErrBlockTooSmall - } - var nSeqs int - seqHeader := in[0] - switch { - case seqHeader < 128: - nSeqs = int(seqHeader) - in = in[1:] - case seqHeader < 255: - if len(in) < 2 { - return ErrBlockTooSmall - } - nSeqs = int(seqHeader-128)<<8 | int(in[1]) - in = in[2:] - case seqHeader == 255: - if len(in) < 3 { - return ErrBlockTooSmall - } - nSeqs = 0x7f00 + int(in[1]) + (int(in[2]) << 8) - in = in[3:] - } - if nSeqs == 0 && len(in) != 0 { - // When no sequences, there should not be any more data... - if debugDecoder { - printf("prepareSequences: 0 sequences, but %d byte(s) left on stream\n", len(in)) - } - return ErrUnexpectedBlockSize - } - - var seqs = &hist.decoders - seqs.nSeqs = nSeqs - if nSeqs > 0 { - if len(in) < 1 { - return ErrBlockTooSmall - } - br := byteReader{b: in, off: 0} - compMode := br.Uint8() - br.advance(1) - if debugDecoder { - printf("Compression modes: 0b%b", compMode) - } - if compMode&3 != 0 { - return errors.New("corrupt block: reserved bits not zero") - } - for i := uint(0); i < 3; i++ { - mode := seqCompMode((compMode >> (6 - i*2)) & 3) - if debugDecoder { - println("Table", tableIndex(i), "is", mode) - } - var seq *sequenceDec - switch tableIndex(i) { - case tableLiteralLengths: - seq = &seqs.litLengths - case tableOffsets: - seq = &seqs.offsets - case tableMatchLengths: - seq = &seqs.matchLengths - default: - panic("unknown table") - } - switch mode { - case compModePredefined: - if seq.fse != nil && !seq.fse.preDefined { - fseDecoderPool.Put(seq.fse) - } - seq.fse = &fsePredef[i] - case compModeRLE: - if br.remain() < 1 { - return ErrBlockTooSmall - } - v := br.Uint8() - br.advance(1) - if seq.fse == nil || seq.fse.preDefined { - seq.fse = fseDecoderPool.Get().(*fseDecoder) - } - symb, err := decSymbolValue(v, symbolTableX[i]) - if err != nil { - printf("RLE Transform table (%v) error: %v", tableIndex(i), err) - return err - } - seq.fse.setRLE(symb) - if debugDecoder { - printf("RLE set to 0x%x, code: %v", symb, v) - } - case compModeFSE: - println("Reading table for", tableIndex(i)) - if seq.fse == nil || seq.fse.preDefined { - seq.fse = fseDecoderPool.Get().(*fseDecoder) - } - err := seq.fse.readNCount(&br, uint16(maxTableSymbol[i])) - if err != nil { - println("Read table error:", err) - return err - } - err = seq.fse.transform(symbolTableX[i]) - if err != nil { - println("Transform table error:", err) - return err - } - if debugDecoder { - println("Read table ok", "symbolLen:", seq.fse.symbolLen) - } - case compModeRepeat: - seq.repeat = true - } - if br.overread() { - return io.ErrUnexpectedEOF - } - } - in = br.unread() - } - if debugDecoder { - println("Literals:", len(seqs.literals), "hash:", xxhash.Sum64(seqs.literals), "and", seqs.nSeqs, "sequences.") - } - - if nSeqs == 0 { - if len(b.sequence) > 0 { - b.sequence = b.sequence[:0] - } - return nil - } - br := seqs.br - if br == nil { - br = &bitReader{} - } - if err := br.init(in); err != nil { - return err - } - - if err := seqs.initialize(br, hist, b.dst); err != nil { - println("initializing sequences:", err) - return err - } - // Extract blocks... - if false && hist.dict == nil { - fatalErr := func(err error) { - if err != nil { - panic(err) - } - } - fn := fmt.Sprintf("n-%d-lits-%d-prev-%d-%d-%d-win-%d.blk", hist.decoders.nSeqs, len(hist.decoders.literals), hist.recentOffsets[0], hist.recentOffsets[1], hist.recentOffsets[2], hist.windowSize) - var buf bytes.Buffer - fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.litLengths.fse)) - fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.matchLengths.fse)) - fatalErr(binary.Write(&buf, binary.LittleEndian, hist.decoders.offsets.fse)) - buf.Write(in) - os.WriteFile(filepath.Join("testdata", "seqs", fn), buf.Bytes(), os.ModePerm) - } - - return nil -} - -func (b *blockDec) decodeSequences(hist *history) error { - if cap(b.sequence) < hist.decoders.nSeqs { - if b.lowMem { - b.sequence = make([]seqVals, 0, hist.decoders.nSeqs) - } else { - b.sequence = make([]seqVals, 0, 0x7F00+0xffff) - } - } - b.sequence = b.sequence[:hist.decoders.nSeqs] - if hist.decoders.nSeqs == 0 { - hist.decoders.seqSize = len(hist.decoders.literals) - return nil - } - hist.decoders.windowSize = hist.windowSize - hist.decoders.prevOffset = hist.recentOffsets - - err := hist.decoders.decode(b.sequence) - hist.recentOffsets = hist.decoders.prevOffset - return err -} - -func (b *blockDec) executeSequences(hist *history) error { - hbytes := hist.b - if len(hbytes) > hist.windowSize { - hbytes = hbytes[len(hbytes)-hist.windowSize:] - // We do not need history anymore. - if hist.dict != nil { - hist.dict.content = nil - } - } - hist.decoders.windowSize = hist.windowSize - hist.decoders.out = b.dst[:0] - err := hist.decoders.execute(b.sequence, hbytes) - if err != nil { - return err - } - return b.updateHistory(hist) -} - -func (b *blockDec) updateHistory(hist *history) error { - if len(b.data) > maxCompressedBlockSize { - return fmt.Errorf("compressed block size too large (%d)", len(b.data)) - } - // Set output and release references. - b.dst = hist.decoders.out - hist.recentOffsets = hist.decoders.prevOffset - - if b.Last { - // if last block we don't care about history. - println("Last block, no history returned") - hist.b = hist.b[:0] - return nil - } else { - hist.append(b.dst) - if debugDecoder { - println("Finished block with ", len(b.sequence), "sequences. Added", len(b.dst), "to history, now length", len(hist.b)) - } - } - hist.decoders.out, hist.decoders.literals = nil, nil - - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/blockenc.go b/vendor/github.com/klauspost/compress/zstd/blockenc.go deleted file mode 100644 index 32a7f401d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/blockenc.go +++ /dev/null @@ -1,909 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "fmt" - "math" - "math/bits" - - "github.com/klauspost/compress/huff0" -) - -type blockEnc struct { - size int - literals []byte - sequences []seq - coders seqCoders - litEnc *huff0.Scratch - dictLitEnc *huff0.Scratch - wr bitWriter - - extraLits int - output []byte - recentOffsets [3]uint32 - prevRecentOffsets [3]uint32 - - last bool - lowMem bool -} - -// init should be used once the block has been created. -// If called more than once, the effect is the same as calling reset. -func (b *blockEnc) init() { - if b.lowMem { - // 1K literals - if cap(b.literals) < 1<<10 { - b.literals = make([]byte, 0, 1<<10) - } - const defSeqs = 20 - if cap(b.sequences) < defSeqs { - b.sequences = make([]seq, 0, defSeqs) - } - // 1K - if cap(b.output) < 1<<10 { - b.output = make([]byte, 0, 1<<10) - } - } else { - if cap(b.literals) < maxCompressedBlockSize { - b.literals = make([]byte, 0, maxCompressedBlockSize) - } - const defSeqs = 2000 - if cap(b.sequences) < defSeqs { - b.sequences = make([]seq, 0, defSeqs) - } - if cap(b.output) < maxCompressedBlockSize { - b.output = make([]byte, 0, maxCompressedBlockSize) - } - } - - if b.coders.mlEnc == nil { - b.coders.mlEnc = &fseEncoder{} - b.coders.mlPrev = &fseEncoder{} - b.coders.ofEnc = &fseEncoder{} - b.coders.ofPrev = &fseEncoder{} - b.coders.llEnc = &fseEncoder{} - b.coders.llPrev = &fseEncoder{} - } - b.litEnc = &huff0.Scratch{WantLogLess: 4} - b.reset(nil) -} - -// initNewEncode can be used to reset offsets and encoders to the initial state. -func (b *blockEnc) initNewEncode() { - b.recentOffsets = [3]uint32{1, 4, 8} - b.litEnc.Reuse = huff0.ReusePolicyNone - b.coders.setPrev(nil, nil, nil) -} - -// reset will reset the block for a new encode, but in the same stream, -// meaning that state will be carried over, but the block content is reset. -// If a previous block is provided, the recent offsets are carried over. -func (b *blockEnc) reset(prev *blockEnc) { - b.extraLits = 0 - b.literals = b.literals[:0] - b.size = 0 - b.sequences = b.sequences[:0] - b.output = b.output[:0] - b.last = false - if prev != nil { - b.recentOffsets = prev.prevRecentOffsets - } - b.dictLitEnc = nil -} - -// reset will reset the block for a new encode, but in the same stream, -// meaning that state will be carried over, but the block content is reset. -// If a previous block is provided, the recent offsets are carried over. -func (b *blockEnc) swapEncoders(prev *blockEnc) { - b.coders.swap(&prev.coders) - b.litEnc, prev.litEnc = prev.litEnc, b.litEnc -} - -// blockHeader contains the information for a block header. -type blockHeader uint32 - -// setLast sets the 'last' indicator on a block. -func (h *blockHeader) setLast(b bool) { - if b { - *h = *h | 1 - } else { - const mask = (1 << 24) - 2 - *h = *h & mask - } -} - -// setSize will store the compressed size of a block. -func (h *blockHeader) setSize(v uint32) { - const mask = 7 - *h = (*h)&mask | blockHeader(v<<3) -} - -// setType sets the block type. -func (h *blockHeader) setType(t blockType) { - const mask = 1 | (((1 << 24) - 1) ^ 7) - *h = (*h & mask) | blockHeader(t<<1) -} - -// appendTo will append the block header to a slice. -func (h blockHeader) appendTo(b []byte) []byte { - return append(b, uint8(h), uint8(h>>8), uint8(h>>16)) -} - -// String returns a string representation of the block. -func (h blockHeader) String() string { - return fmt.Sprintf("Type: %d, Size: %d, Last:%t", (h>>1)&3, h>>3, h&1 == 1) -} - -// literalsHeader contains literals header information. -type literalsHeader uint64 - -// setType can be used to set the type of literal block. -func (h *literalsHeader) setType(t literalsBlockType) { - const mask = math.MaxUint64 - 3 - *h = (*h & mask) | literalsHeader(t) -} - -// setSize can be used to set a single size, for uncompressed and RLE content. -func (h *literalsHeader) setSize(regenLen int) { - inBits := bits.Len32(uint32(regenLen)) - // Only retain 2 bits - const mask = 3 - lh := uint64(*h & mask) - switch { - case inBits < 5: - lh |= (uint64(regenLen) << 3) | (1 << 60) - if debugEncoder { - got := int(lh>>3) & 0xff - if got != regenLen { - panic(fmt.Sprint("litRegenSize = ", regenLen, "(want) != ", got, "(got)")) - } - } - case inBits < 12: - lh |= (1 << 2) | (uint64(regenLen) << 4) | (2 << 60) - case inBits < 20: - lh |= (3 << 2) | (uint64(regenLen) << 4) | (3 << 60) - default: - panic(fmt.Errorf("internal error: block too big (%d)", regenLen)) - } - *h = literalsHeader(lh) -} - -// setSizes will set the size of a compressed literals section and the input length. -func (h *literalsHeader) setSizes(compLen, inLen int, single bool) { - compBits, inBits := bits.Len32(uint32(compLen)), bits.Len32(uint32(inLen)) - // Only retain 2 bits - const mask = 3 - lh := uint64(*h & mask) - switch { - case compBits <= 10 && inBits <= 10: - if !single { - lh |= 1 << 2 - } - lh |= (uint64(inLen) << 4) | (uint64(compLen) << (10 + 4)) | (3 << 60) - if debugEncoder { - const mmask = (1 << 24) - 1 - n := (lh >> 4) & mmask - if int(n&1023) != inLen { - panic(fmt.Sprint("regensize:", int(n&1023), "!=", inLen, inBits)) - } - if int(n>>10) != compLen { - panic(fmt.Sprint("compsize:", int(n>>10), "!=", compLen, compBits)) - } - } - case compBits <= 14 && inBits <= 14: - lh |= (2 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (14 + 4)) | (4 << 60) - if single { - panic("single stream used with more than 10 bits length.") - } - case compBits <= 18 && inBits <= 18: - lh |= (3 << 2) | (uint64(inLen) << 4) | (uint64(compLen) << (18 + 4)) | (5 << 60) - if single { - panic("single stream used with more than 10 bits length.") - } - default: - panic("internal error: block too big") - } - *h = literalsHeader(lh) -} - -// appendTo will append the literals header to a byte slice. -func (h literalsHeader) appendTo(b []byte) []byte { - size := uint8(h >> 60) - switch size { - case 1: - b = append(b, uint8(h)) - case 2: - b = append(b, uint8(h), uint8(h>>8)) - case 3: - b = append(b, uint8(h), uint8(h>>8), uint8(h>>16)) - case 4: - b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24)) - case 5: - b = append(b, uint8(h), uint8(h>>8), uint8(h>>16), uint8(h>>24), uint8(h>>32)) - default: - panic(fmt.Errorf("internal error: literalsHeader has invalid size (%d)", size)) - } - return b -} - -// size returns the output size with currently set values. -func (h literalsHeader) size() int { - return int(h >> 60) -} - -func (h literalsHeader) String() string { - return fmt.Sprintf("Type: %d, SizeFormat: %d, Size: 0x%d, Bytes:%d", literalsBlockType(h&3), (h>>2)&3, h&((1<<60)-1)>>4, h>>60) -} - -// pushOffsets will push the recent offsets to the backup store. -func (b *blockEnc) pushOffsets() { - b.prevRecentOffsets = b.recentOffsets -} - -// pushOffsets will push the recent offsets to the backup store. -func (b *blockEnc) popOffsets() { - b.recentOffsets = b.prevRecentOffsets -} - -// matchOffset will adjust recent offsets and return the adjusted one, -// if it matches a previous offset. -func (b *blockEnc) matchOffset(offset, lits uint32) uint32 { - // Check if offset is one of the recent offsets. - // Adjusts the output offset accordingly. - // Gives a tiny bit of compression, typically around 1%. - if true { - if lits > 0 { - switch offset { - case b.recentOffsets[0]: - offset = 1 - case b.recentOffsets[1]: - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 2 - case b.recentOffsets[2]: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 3 - default: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset += 3 - } - } else { - switch offset { - case b.recentOffsets[1]: - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 1 - case b.recentOffsets[2]: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 2 - case b.recentOffsets[0] - 1: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset = 3 - default: - b.recentOffsets[2] = b.recentOffsets[1] - b.recentOffsets[1] = b.recentOffsets[0] - b.recentOffsets[0] = offset - offset += 3 - } - } - } else { - offset += 3 - } - return offset -} - -// encodeRaw can be used to set the output to a raw representation of supplied bytes. -func (b *blockEnc) encodeRaw(a []byte) { - var bh blockHeader - bh.setLast(b.last) - bh.setSize(uint32(len(a))) - bh.setType(blockTypeRaw) - b.output = bh.appendTo(b.output[:0]) - b.output = append(b.output, a...) - if debugEncoder { - println("Adding RAW block, length", len(a), "last:", b.last) - } -} - -// encodeRaw can be used to set the output to a raw representation of supplied bytes. -func (b *blockEnc) encodeRawTo(dst, src []byte) []byte { - var bh blockHeader - bh.setLast(b.last) - bh.setSize(uint32(len(src))) - bh.setType(blockTypeRaw) - dst = bh.appendTo(dst) - dst = append(dst, src...) - if debugEncoder { - println("Adding RAW block, length", len(src), "last:", b.last) - } - return dst -} - -// encodeLits can be used if the block is only litLen. -func (b *blockEnc) encodeLits(lits []byte, raw bool) error { - var bh blockHeader - bh.setLast(b.last) - bh.setSize(uint32(len(lits))) - - // Don't compress extremely small blocks - if len(lits) < 8 || (len(lits) < 32 && b.dictLitEnc == nil) || raw { - if debugEncoder { - println("Adding RAW block, length", len(lits), "last:", b.last) - } - bh.setType(blockTypeRaw) - b.output = bh.appendTo(b.output) - b.output = append(b.output, lits...) - return nil - } - - var ( - out []byte - reUsed, single bool - err error - ) - if b.dictLitEnc != nil { - b.litEnc.TransferCTable(b.dictLitEnc) - b.litEnc.Reuse = huff0.ReusePolicyAllow - b.dictLitEnc = nil - } - if len(lits) >= 1024 { - // Use 4 Streams. - out, reUsed, err = huff0.Compress4X(lits, b.litEnc) - } else if len(lits) > 16 { - // Use 1 stream - single = true - out, reUsed, err = huff0.Compress1X(lits, b.litEnc) - } else { - err = huff0.ErrIncompressible - } - if err == nil && len(out)+5 > len(lits) { - // If we are close, we may still be worse or equal to raw. - var lh literalsHeader - lh.setSizes(len(out), len(lits), single) - if len(out)+lh.size() >= len(lits) { - err = huff0.ErrIncompressible - } - } - switch err { - case huff0.ErrIncompressible: - if debugEncoder { - println("Adding RAW block, length", len(lits), "last:", b.last) - } - bh.setType(blockTypeRaw) - b.output = bh.appendTo(b.output) - b.output = append(b.output, lits...) - return nil - case huff0.ErrUseRLE: - if debugEncoder { - println("Adding RLE block, length", len(lits)) - } - bh.setType(blockTypeRLE) - b.output = bh.appendTo(b.output) - b.output = append(b.output, lits[0]) - return nil - case nil: - default: - return err - } - // Compressed... - // Now, allow reuse - b.litEnc.Reuse = huff0.ReusePolicyAllow - bh.setType(blockTypeCompressed) - var lh literalsHeader - if reUsed { - if debugEncoder { - println("Reused tree, compressed to", len(out)) - } - lh.setType(literalsBlockTreeless) - } else { - if debugEncoder { - println("New tree, compressed to", len(out), "tree size:", len(b.litEnc.OutTable)) - } - lh.setType(literalsBlockCompressed) - } - // Set sizes - lh.setSizes(len(out), len(lits), single) - bh.setSize(uint32(len(out) + lh.size() + 1)) - - // Write block headers. - b.output = bh.appendTo(b.output) - b.output = lh.appendTo(b.output) - // Add compressed data. - b.output = append(b.output, out...) - // No sequences. - b.output = append(b.output, 0) - return nil -} - -// encodeRLE will encode an RLE block. -func (b *blockEnc) encodeRLE(val byte, length uint32) { - var bh blockHeader - bh.setLast(b.last) - bh.setSize(length) - bh.setType(blockTypeRLE) - b.output = bh.appendTo(b.output) - b.output = append(b.output, val) -} - -// fuzzFseEncoder can be used to fuzz the FSE encoder. -func fuzzFseEncoder(data []byte) int { - if len(data) > maxSequences || len(data) < 2 { - return 0 - } - enc := fseEncoder{} - hist := enc.Histogram() - maxSym := uint8(0) - for i, v := range data { - v = v & 63 - data[i] = v - hist[v]++ - if v > maxSym { - maxSym = v - } - } - if maxSym == 0 { - // All 0 - return 0 - } - maxCount := func(a []uint32) int { - var max uint32 - for _, v := range a { - if v > max { - max = v - } - } - return int(max) - } - cnt := maxCount(hist[:maxSym]) - if cnt == len(data) { - // RLE - return 0 - } - enc.HistogramFinished(maxSym, cnt) - err := enc.normalizeCount(len(data)) - if err != nil { - return 0 - } - _, err = enc.writeCount(nil) - if err != nil { - panic(err) - } - return 1 -} - -// encode will encode the block and append the output in b.output. -// Previous offset codes must be pushed if more blocks are expected. -func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { - if len(b.sequences) == 0 { - return b.encodeLits(b.literals, rawAllLits) - } - if len(b.sequences) == 1 && len(org) > 0 && len(b.literals) <= 1 { - // Check common RLE cases. - seq := b.sequences[0] - if seq.litLen == uint32(len(b.literals)) && seq.offset-3 == 1 { - // Offset == 1 and 0 or 1 literals. - b.encodeRLE(org[0], b.sequences[0].matchLen+zstdMinMatch+seq.litLen) - return nil - } - } - - // We want some difference to at least account for the headers. - saved := b.size - len(b.literals) - (b.size >> 6) - if saved < 16 { - if org == nil { - return errIncompressible - } - b.popOffsets() - return b.encodeLits(org, rawAllLits) - } - - var bh blockHeader - var lh literalsHeader - bh.setLast(b.last) - bh.setType(blockTypeCompressed) - // Store offset of the block header. Needed when we know the size. - bhOffset := len(b.output) - b.output = bh.appendTo(b.output) - - var ( - out []byte - reUsed, single bool - err error - ) - if b.dictLitEnc != nil { - b.litEnc.TransferCTable(b.dictLitEnc) - b.litEnc.Reuse = huff0.ReusePolicyAllow - b.dictLitEnc = nil - } - if len(b.literals) >= 1024 && !raw { - // Use 4 Streams. - out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc) - } else if len(b.literals) > 16 && !raw { - // Use 1 stream - single = true - out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc) - } else { - err = huff0.ErrIncompressible - } - - if err == nil && len(out)+5 > len(b.literals) { - // If we are close, we may still be worse or equal to raw. - var lh literalsHeader - lh.setSize(len(b.literals)) - szRaw := lh.size() - lh.setSizes(len(out), len(b.literals), single) - szComp := lh.size() - if len(out)+szComp >= len(b.literals)+szRaw { - err = huff0.ErrIncompressible - } - } - switch err { - case huff0.ErrIncompressible: - lh.setType(literalsBlockRaw) - lh.setSize(len(b.literals)) - b.output = lh.appendTo(b.output) - b.output = append(b.output, b.literals...) - if debugEncoder { - println("Adding literals RAW, length", len(b.literals)) - } - case huff0.ErrUseRLE: - lh.setType(literalsBlockRLE) - lh.setSize(len(b.literals)) - b.output = lh.appendTo(b.output) - b.output = append(b.output, b.literals[0]) - if debugEncoder { - println("Adding literals RLE") - } - case nil: - // Compressed litLen... - if reUsed { - if debugEncoder { - println("reused tree") - } - lh.setType(literalsBlockTreeless) - } else { - if debugEncoder { - println("new tree, size:", len(b.litEnc.OutTable)) - } - lh.setType(literalsBlockCompressed) - if debugEncoder { - _, _, err := huff0.ReadTable(out, nil) - if err != nil { - panic(err) - } - } - } - lh.setSizes(len(out), len(b.literals), single) - if debugEncoder { - printf("Compressed %d literals to %d bytes", len(b.literals), len(out)) - println("Adding literal header:", lh) - } - b.output = lh.appendTo(b.output) - b.output = append(b.output, out...) - b.litEnc.Reuse = huff0.ReusePolicyAllow - if debugEncoder { - println("Adding literals compressed") - } - default: - if debugEncoder { - println("Adding literals ERROR:", err) - } - return err - } - // Sequence compression - - // Write the number of sequences - switch { - case len(b.sequences) < 128: - b.output = append(b.output, uint8(len(b.sequences))) - case len(b.sequences) < 0x7f00: // TODO: this could be wrong - n := len(b.sequences) - b.output = append(b.output, 128+uint8(n>>8), uint8(n)) - default: - n := len(b.sequences) - 0x7f00 - b.output = append(b.output, 255, uint8(n), uint8(n>>8)) - } - if debugEncoder { - println("Encoding", len(b.sequences), "sequences") - } - b.genCodes() - llEnc := b.coders.llEnc - ofEnc := b.coders.ofEnc - mlEnc := b.coders.mlEnc - err = llEnc.normalizeCount(len(b.sequences)) - if err != nil { - return err - } - err = ofEnc.normalizeCount(len(b.sequences)) - if err != nil { - return err - } - err = mlEnc.normalizeCount(len(b.sequences)) - if err != nil { - return err - } - - // Choose the best compression mode for each type. - // Will evaluate the new vs predefined and previous. - chooseComp := func(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) { - // See if predefined/previous is better - hist := cur.count[:cur.symbolLen] - nSize := cur.approxSize(hist) + cur.maxHeaderSize() - predefSize := preDef.approxSize(hist) - prevSize := prev.approxSize(hist) - - // Add a small penalty for new encoders. - // Don't bother with extremely small (<2 byte gains). - nSize = nSize + (nSize+2*8*16)>>4 - switch { - case predefSize <= prevSize && predefSize <= nSize || forcePreDef: - if debugEncoder { - println("Using predefined", predefSize>>3, "<=", nSize>>3) - } - return preDef, compModePredefined - case prevSize <= nSize: - if debugEncoder { - println("Using previous", prevSize>>3, "<=", nSize>>3) - } - return prev, compModeRepeat - default: - if debugEncoder { - println("Using new, predef", predefSize>>3, ". previous:", prevSize>>3, ">", nSize>>3, "header max:", cur.maxHeaderSize()>>3, "bytes") - println("tl:", cur.actualTableLog, "symbolLen:", cur.symbolLen, "norm:", cur.norm[:cur.symbolLen], "hist", cur.count[:cur.symbolLen]) - } - return cur, compModeFSE - } - } - - // Write compression mode - var mode uint8 - if llEnc.useRLE { - mode |= uint8(compModeRLE) << 6 - llEnc.setRLE(b.sequences[0].llCode) - if debugEncoder { - println("llEnc.useRLE") - } - } else { - var m seqCompMode - llEnc, m = chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths]) - mode |= uint8(m) << 6 - } - if ofEnc.useRLE { - mode |= uint8(compModeRLE) << 4 - ofEnc.setRLE(b.sequences[0].ofCode) - if debugEncoder { - println("ofEnc.useRLE") - } - } else { - var m seqCompMode - ofEnc, m = chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets]) - mode |= uint8(m) << 4 - } - - if mlEnc.useRLE { - mode |= uint8(compModeRLE) << 2 - mlEnc.setRLE(b.sequences[0].mlCode) - if debugEncoder { - println("mlEnc.useRLE, code: ", b.sequences[0].mlCode, "value", b.sequences[0].matchLen) - } - } else { - var m seqCompMode - mlEnc, m = chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths]) - mode |= uint8(m) << 2 - } - b.output = append(b.output, mode) - if debugEncoder { - printf("Compression modes: 0b%b", mode) - } - b.output, err = llEnc.writeCount(b.output) - if err != nil { - return err - } - start := len(b.output) - b.output, err = ofEnc.writeCount(b.output) - if err != nil { - return err - } - if false { - println("block:", b.output[start:], "tablelog", ofEnc.actualTableLog, "maxcount:", ofEnc.maxCount) - fmt.Printf("selected TableLog: %d, Symbol length: %d\n", ofEnc.actualTableLog, ofEnc.symbolLen) - for i, v := range ofEnc.norm[:ofEnc.symbolLen] { - fmt.Printf("%3d: %5d -> %4d \n", i, ofEnc.count[i], v) - } - } - b.output, err = mlEnc.writeCount(b.output) - if err != nil { - return err - } - - // Maybe in block? - wr := &b.wr - wr.reset(b.output) - - var ll, of, ml cState - - // Current sequence - seq := len(b.sequences) - 1 - s := b.sequences[seq] - llEnc.setBits(llBitsTable[:]) - mlEnc.setBits(mlBitsTable[:]) - ofEnc.setBits(nil) - - llTT, ofTT, mlTT := llEnc.ct.symbolTT[:256], ofEnc.ct.symbolTT[:256], mlEnc.ct.symbolTT[:256] - - // We have 3 bounds checks here (and in the loop). - // Since we are iterating backwards it is kinda hard to avoid. - llB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode] - ll.init(wr, &llEnc.ct, llB) - of.init(wr, &ofEnc.ct, ofB) - wr.flush32() - ml.init(wr, &mlEnc.ct, mlB) - - // Each of these lookups also generates a bounds check. - wr.addBits32NC(s.litLen, llB.outBits) - wr.addBits32NC(s.matchLen, mlB.outBits) - wr.flush32() - wr.addBits32NC(s.offset, ofB.outBits) - if debugSequences { - println("Encoded seq", seq, s, "codes:", s.llCode, s.mlCode, s.ofCode, "states:", ll.state, ml.state, of.state, "bits:", llB, mlB, ofB) - } - seq-- - // Store sequences in reverse... - for seq >= 0 { - s = b.sequences[seq] - - ofB := ofTT[s.ofCode] - wr.flush32() // tablelog max is below 8 for each, so it will fill max 24 bits. - //of.encode(ofB) - nbBitsOut := (uint32(of.state) + ofB.deltaNbBits) >> 16 - dstState := int32(of.state>>(nbBitsOut&15)) + int32(ofB.deltaFindState) - wr.addBits16NC(of.state, uint8(nbBitsOut)) - of.state = of.stateTable[dstState] - - // Accumulate extra bits. - outBits := ofB.outBits & 31 - extraBits := uint64(s.offset & bitMask32[outBits]) - extraBitsN := outBits - - mlB := mlTT[s.mlCode] - //ml.encode(mlB) - nbBitsOut = (uint32(ml.state) + mlB.deltaNbBits) >> 16 - dstState = int32(ml.state>>(nbBitsOut&15)) + int32(mlB.deltaFindState) - wr.addBits16NC(ml.state, uint8(nbBitsOut)) - ml.state = ml.stateTable[dstState] - - outBits = mlB.outBits & 31 - extraBits = extraBits<> 16 - dstState = int32(ll.state>>(nbBitsOut&15)) + int32(llB.deltaFindState) - wr.addBits16NC(ll.state, uint8(nbBitsOut)) - ll.state = ll.stateTable[dstState] - - outBits = llB.outBits & 31 - extraBits = extraBits<= b.size { - // Discard and encode as raw block. - b.output = b.encodeRawTo(b.output[:bhOffset], org) - b.popOffsets() - b.litEnc.Reuse = huff0.ReusePolicyNone - return nil - } - - // Size is output minus block header. - bh.setSize(uint32(len(b.output)-bhOffset) - 3) - if debugEncoder { - println("Rewriting block header", bh) - } - _ = bh.appendTo(b.output[bhOffset:bhOffset]) - b.coders.setPrev(llEnc, mlEnc, ofEnc) - return nil -} - -var errIncompressible = errors.New("incompressible") - -func (b *blockEnc) genCodes() { - if len(b.sequences) == 0 { - // nothing to do - return - } - if len(b.sequences) > math.MaxUint16 { - panic("can only encode up to 64K sequences") - } - // No bounds checks after here: - llH := b.coders.llEnc.Histogram() - ofH := b.coders.ofEnc.Histogram() - mlH := b.coders.mlEnc.Histogram() - for i := range llH { - llH[i] = 0 - } - for i := range ofH { - ofH[i] = 0 - } - for i := range mlH { - mlH[i] = 0 - } - - var llMax, ofMax, mlMax uint8 - for i := range b.sequences { - seq := &b.sequences[i] - v := llCode(seq.litLen) - seq.llCode = v - llH[v]++ - if v > llMax { - llMax = v - } - - v = ofCode(seq.offset) - seq.ofCode = v - ofH[v]++ - if v > ofMax { - ofMax = v - } - - v = mlCode(seq.matchLen) - seq.mlCode = v - mlH[v]++ - if v > mlMax { - mlMax = v - if debugAsserts && mlMax > maxMatchLengthSymbol { - panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d), matchlen: %d", mlMax, seq.matchLen)) - } - } - } - maxCount := func(a []uint32) int { - var max uint32 - for _, v := range a { - if v > max { - max = v - } - } - return int(max) - } - if debugAsserts && mlMax > maxMatchLengthSymbol { - panic(fmt.Errorf("mlMax > maxMatchLengthSymbol (%d)", mlMax)) - } - if debugAsserts && ofMax > maxOffsetBits { - panic(fmt.Errorf("ofMax > maxOffsetBits (%d)", ofMax)) - } - if debugAsserts && llMax > maxLiteralLengthSymbol { - panic(fmt.Errorf("llMax > maxLiteralLengthSymbol (%d)", llMax)) - } - - b.coders.mlEnc.HistogramFinished(mlMax, maxCount(mlH[:mlMax+1])) - b.coders.ofEnc.HistogramFinished(ofMax, maxCount(ofH[:ofMax+1])) - b.coders.llEnc.HistogramFinished(llMax, maxCount(llH[:llMax+1])) -} diff --git a/vendor/github.com/klauspost/compress/zstd/blocktype_string.go b/vendor/github.com/klauspost/compress/zstd/blocktype_string.go deleted file mode 100644 index 01a01e486..000000000 --- a/vendor/github.com/klauspost/compress/zstd/blocktype_string.go +++ /dev/null @@ -1,85 +0,0 @@ -// Code generated by "stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex"; DO NOT EDIT. - -package zstd - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[blockTypeRaw-0] - _ = x[blockTypeRLE-1] - _ = x[blockTypeCompressed-2] - _ = x[blockTypeReserved-3] -} - -const _blockType_name = "blockTypeRawblockTypeRLEblockTypeCompressedblockTypeReserved" - -var _blockType_index = [...]uint8{0, 12, 24, 43, 60} - -func (i blockType) String() string { - if i >= blockType(len(_blockType_index)-1) { - return "blockType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _blockType_name[_blockType_index[i]:_blockType_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[literalsBlockRaw-0] - _ = x[literalsBlockRLE-1] - _ = x[literalsBlockCompressed-2] - _ = x[literalsBlockTreeless-3] -} - -const _literalsBlockType_name = "literalsBlockRawliteralsBlockRLEliteralsBlockCompressedliteralsBlockTreeless" - -var _literalsBlockType_index = [...]uint8{0, 16, 32, 55, 76} - -func (i literalsBlockType) String() string { - if i >= literalsBlockType(len(_literalsBlockType_index)-1) { - return "literalsBlockType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _literalsBlockType_name[_literalsBlockType_index[i]:_literalsBlockType_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[compModePredefined-0] - _ = x[compModeRLE-1] - _ = x[compModeFSE-2] - _ = x[compModeRepeat-3] -} - -const _seqCompMode_name = "compModePredefinedcompModeRLEcompModeFSEcompModeRepeat" - -var _seqCompMode_index = [...]uint8{0, 18, 29, 40, 54} - -func (i seqCompMode) String() string { - if i >= seqCompMode(len(_seqCompMode_index)-1) { - return "seqCompMode(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _seqCompMode_name[_seqCompMode_index[i]:_seqCompMode_index[i+1]] -} -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[tableLiteralLengths-0] - _ = x[tableOffsets-1] - _ = x[tableMatchLengths-2] -} - -const _tableIndex_name = "tableLiteralLengthstableOffsetstableMatchLengths" - -var _tableIndex_index = [...]uint8{0, 19, 31, 48} - -func (i tableIndex) String() string { - if i >= tableIndex(len(_tableIndex_index)-1) { - return "tableIndex(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _tableIndex_name[_tableIndex_index[i]:_tableIndex_index[i+1]] -} diff --git a/vendor/github.com/klauspost/compress/zstd/bytebuf.go b/vendor/github.com/klauspost/compress/zstd/bytebuf.go deleted file mode 100644 index 55a388553..000000000 --- a/vendor/github.com/klauspost/compress/zstd/bytebuf.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "fmt" - "io" -) - -type byteBuffer interface { - // Read up to 8 bytes. - // Returns io.ErrUnexpectedEOF if this cannot be satisfied. - readSmall(n int) ([]byte, error) - - // Read >8 bytes. - // MAY use the destination slice. - readBig(n int, dst []byte) ([]byte, error) - - // Read a single byte. - readByte() (byte, error) - - // Skip n bytes. - skipN(n int64) error -} - -// in-memory buffer -type byteBuf []byte - -func (b *byteBuf) readSmall(n int) ([]byte, error) { - if debugAsserts && n > 8 { - panic(fmt.Errorf("small read > 8 (%d). use readBig", n)) - } - bb := *b - if len(bb) < n { - return nil, io.ErrUnexpectedEOF - } - r := bb[:n] - *b = bb[n:] - return r, nil -} - -func (b *byteBuf) readBig(n int, dst []byte) ([]byte, error) { - bb := *b - if len(bb) < n { - return nil, io.ErrUnexpectedEOF - } - r := bb[:n] - *b = bb[n:] - return r, nil -} - -func (b *byteBuf) readByte() (byte, error) { - bb := *b - if len(bb) < 1 { - return 0, io.ErrUnexpectedEOF - } - r := bb[0] - *b = bb[1:] - return r, nil -} - -func (b *byteBuf) skipN(n int64) error { - bb := *b - if n < 0 { - return fmt.Errorf("negative skip (%d) requested", n) - } - if int64(len(bb)) < n { - return io.ErrUnexpectedEOF - } - *b = bb[n:] - return nil -} - -// wrapper around a reader. -type readerWrapper struct { - r io.Reader - tmp [8]byte -} - -func (r *readerWrapper) readSmall(n int) ([]byte, error) { - if debugAsserts && n > 8 { - panic(fmt.Errorf("small read > 8 (%d). use readBig", n)) - } - n2, err := io.ReadFull(r.r, r.tmp[:n]) - // We only really care about the actual bytes read. - if err != nil { - if err == io.EOF { - return nil, io.ErrUnexpectedEOF - } - if debugDecoder { - println("readSmall: got", n2, "want", n, "err", err) - } - return nil, err - } - return r.tmp[:n], nil -} - -func (r *readerWrapper) readBig(n int, dst []byte) ([]byte, error) { - if cap(dst) < n { - dst = make([]byte, n) - } - n2, err := io.ReadFull(r.r, dst[:n]) - if err == io.EOF && n > 0 { - err = io.ErrUnexpectedEOF - } - return dst[:n2], err -} - -func (r *readerWrapper) readByte() (byte, error) { - n2, err := io.ReadFull(r.r, r.tmp[:1]) - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return 0, err - } - if n2 != 1 { - return 0, io.ErrUnexpectedEOF - } - return r.tmp[0], nil -} - -func (r *readerWrapper) skipN(n int64) error { - n2, err := io.CopyN(io.Discard, r.r, n) - if n2 != n { - err = io.ErrUnexpectedEOF - } - return err -} diff --git a/vendor/github.com/klauspost/compress/zstd/bytereader.go b/vendor/github.com/klauspost/compress/zstd/bytereader.go deleted file mode 100644 index 0e59a242d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/bytereader.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -// byteReader provides a byte reader that reads -// little endian values from a byte stream. -// The input stream is manually advanced. -// The reader performs no bounds checks. -type byteReader struct { - b []byte - off int -} - -// advance the stream b n bytes. -func (b *byteReader) advance(n uint) { - b.off += int(n) -} - -// overread returns whether we have advanced too far. -func (b *byteReader) overread() bool { - return b.off > len(b.b) -} - -// Int32 returns a little endian int32 starting at current offset. -func (b byteReader) Int32() int32 { - b2 := b.b[b.off:] - b2 = b2[:4] - v3 := int32(b2[3]) - v2 := int32(b2[2]) - v1 := int32(b2[1]) - v0 := int32(b2[0]) - return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) -} - -// Uint8 returns the next byte -func (b *byteReader) Uint8() uint8 { - v := b.b[b.off] - return v -} - -// Uint32 returns a little endian uint32 starting at current offset. -func (b byteReader) Uint32() uint32 { - if r := b.remain(); r < 4 { - // Very rare - v := uint32(0) - for i := 1; i <= r; i++ { - v = (v << 8) | uint32(b.b[len(b.b)-i]) - } - return v - } - b2 := b.b[b.off:] - b2 = b2[:4] - v3 := uint32(b2[3]) - v2 := uint32(b2[2]) - v1 := uint32(b2[1]) - v0 := uint32(b2[0]) - return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) -} - -// Uint32NC returns a little endian uint32 starting at current offset. -// The caller must be sure if there are at least 4 bytes left. -func (b byteReader) Uint32NC() uint32 { - b2 := b.b[b.off:] - b2 = b2[:4] - v3 := uint32(b2[3]) - v2 := uint32(b2[2]) - v1 := uint32(b2[1]) - v0 := uint32(b2[0]) - return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24) -} - -// unread returns the unread portion of the input. -func (b byteReader) unread() []byte { - return b.b[b.off:] -} - -// remain will return the number of bytes remaining. -func (b byteReader) remain() int { - return len(b.b) - b.off -} diff --git a/vendor/github.com/klauspost/compress/zstd/decodeheader.go b/vendor/github.com/klauspost/compress/zstd/decodeheader.go deleted file mode 100644 index 6a5a2988b..000000000 --- a/vendor/github.com/klauspost/compress/zstd/decodeheader.go +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright 2020+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package zstd - -import ( - "encoding/binary" - "errors" - "io" -) - -// HeaderMaxSize is the maximum size of a Frame and Block Header. -// If less is sent to Header.Decode it *may* still contain enough information. -const HeaderMaxSize = 14 + 3 - -// Header contains information about the first frame and block within that. -type Header struct { - // SingleSegment specifies whether the data is to be decompressed into a - // single contiguous memory segment. - // It implies that WindowSize is invalid and that FrameContentSize is valid. - SingleSegment bool - - // WindowSize is the window of data to keep while decoding. - // Will only be set if SingleSegment is false. - WindowSize uint64 - - // Dictionary ID. - // If 0, no dictionary. - DictionaryID uint32 - - // HasFCS specifies whether FrameContentSize has a valid value. - HasFCS bool - - // FrameContentSize is the expected uncompressed size of the entire frame. - FrameContentSize uint64 - - // Skippable will be true if the frame is meant to be skipped. - // This implies that FirstBlock.OK is false. - Skippable bool - - // SkippableID is the user-specific ID for the skippable frame. - // Valid values are between 0 to 15, inclusive. - SkippableID int - - // SkippableSize is the length of the user data to skip following - // the header. - SkippableSize uint32 - - // HeaderSize is the raw size of the frame header. - // - // For normal frames, it includes the size of the magic number and - // the size of the header (per section 3.1.1.1). - // It does not include the size for any data blocks (section 3.1.1.2) nor - // the size for the trailing content checksum. - // - // For skippable frames, this counts the size of the magic number - // along with the size of the size field of the payload. - // It does not include the size of the skippable payload itself. - // The total frame size is the HeaderSize plus the SkippableSize. - HeaderSize int - - // First block information. - FirstBlock struct { - // OK will be set if first block could be decoded. - OK bool - - // Is this the last block of a frame? - Last bool - - // Is the data compressed? - // If true CompressedSize will be populated. - // Unfortunately DecompressedSize cannot be determined - // without decoding the blocks. - Compressed bool - - // DecompressedSize is the expected decompressed size of the block. - // Will be 0 if it cannot be determined. - DecompressedSize int - - // CompressedSize of the data in the block. - // Does not include the block header. - // Will be equal to DecompressedSize if not Compressed. - CompressedSize int - } - - // If set there is a checksum present for the block content. - // The checksum field at the end is always 4 bytes long. - HasCheckSum bool -} - -// Decode the header from the beginning of the stream. -// This will decode the frame header and the first block header if enough bytes are provided. -// It is recommended to provide at least HeaderMaxSize bytes. -// If the frame header cannot be read an error will be returned. -// If there isn't enough input, io.ErrUnexpectedEOF is returned. -// The FirstBlock.OK will indicate if enough information was available to decode the first block header. -func (h *Header) Decode(in []byte) error { - _, err := h.DecodeAndStrip(in) - return err -} - -// DecodeAndStrip will decode the header from the beginning of the stream -// and on success return the remaining bytes. -// This will decode the frame header and the first block header if enough bytes are provided. -// It is recommended to provide at least HeaderMaxSize bytes. -// If the frame header cannot be read an error will be returned. -// If there isn't enough input, io.ErrUnexpectedEOF is returned. -// The FirstBlock.OK will indicate if enough information was available to decode the first block header. -func (h *Header) DecodeAndStrip(in []byte) (remain []byte, err error) { - *h = Header{} - if len(in) < 4 { - return nil, io.ErrUnexpectedEOF - } - h.HeaderSize += 4 - b, in := in[:4], in[4:] - if string(b) != frameMagic { - if string(b[1:4]) != skippableFrameMagic || b[0]&0xf0 != 0x50 { - return nil, ErrMagicMismatch - } - if len(in) < 4 { - return nil, io.ErrUnexpectedEOF - } - h.HeaderSize += 4 - h.Skippable = true - h.SkippableID = int(b[0] & 0xf) - h.SkippableSize = binary.LittleEndian.Uint32(in) - return in[4:], nil - } - - // Read Window_Descriptor - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#window_descriptor - if len(in) < 1 { - return nil, io.ErrUnexpectedEOF - } - fhd, in := in[0], in[1:] - h.HeaderSize++ - h.SingleSegment = fhd&(1<<5) != 0 - h.HasCheckSum = fhd&(1<<2) != 0 - if fhd&(1<<3) != 0 { - return nil, errors.New("reserved bit set on frame header") - } - - if !h.SingleSegment { - if len(in) < 1 { - return nil, io.ErrUnexpectedEOF - } - var wd byte - wd, in = in[0], in[1:] - h.HeaderSize++ - windowLog := 10 + (wd >> 3) - windowBase := uint64(1) << windowLog - windowAdd := (windowBase / 8) * uint64(wd&0x7) - h.WindowSize = windowBase + windowAdd - } - - // Read Dictionary_ID - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary_id - if size := fhd & 3; size != 0 { - if size == 3 { - size = 4 - } - if len(in) < int(size) { - return nil, io.ErrUnexpectedEOF - } - b, in = in[:size], in[size:] - h.HeaderSize += int(size) - switch len(b) { - case 1: - h.DictionaryID = uint32(b[0]) - case 2: - h.DictionaryID = uint32(b[0]) | (uint32(b[1]) << 8) - case 4: - h.DictionaryID = uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - } - } - - // Read Frame_Content_Size - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frame_content_size - var fcsSize int - v := fhd >> 6 - switch v { - case 0: - if h.SingleSegment { - fcsSize = 1 - } - default: - fcsSize = 1 << v - } - - if fcsSize > 0 { - h.HasFCS = true - if len(in) < fcsSize { - return nil, io.ErrUnexpectedEOF - } - b, in = in[:fcsSize], in[fcsSize:] - h.HeaderSize += int(fcsSize) - switch len(b) { - case 1: - h.FrameContentSize = uint64(b[0]) - case 2: - // When FCS_Field_Size is 2, the offset of 256 is added. - h.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) + 256 - case 4: - h.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) | (uint64(b[2]) << 16) | (uint64(b[3]) << 24) - case 8: - d1 := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - d2 := uint32(b[4]) | (uint32(b[5]) << 8) | (uint32(b[6]) << 16) | (uint32(b[7]) << 24) - h.FrameContentSize = uint64(d1) | (uint64(d2) << 32) - } - } - - // Frame Header done, we will not fail from now on. - if len(in) < 3 { - return in, nil - } - tmp := in[:3] - bh := uint32(tmp[0]) | (uint32(tmp[1]) << 8) | (uint32(tmp[2]) << 16) - h.FirstBlock.Last = bh&1 != 0 - blockType := blockType((bh >> 1) & 3) - // find size. - cSize := int(bh >> 3) - switch blockType { - case blockTypeReserved: - return in, nil - case blockTypeRLE: - h.FirstBlock.Compressed = true - h.FirstBlock.DecompressedSize = cSize - h.FirstBlock.CompressedSize = 1 - case blockTypeCompressed: - h.FirstBlock.Compressed = true - h.FirstBlock.CompressedSize = cSize - case blockTypeRaw: - h.FirstBlock.DecompressedSize = cSize - h.FirstBlock.CompressedSize = cSize - default: - panic("Invalid block type") - } - - h.FirstBlock.OK = true - return in, nil -} - -// AppendTo will append the encoded header to the dst slice. -// There is no error checking performed on the header values. -func (h *Header) AppendTo(dst []byte) ([]byte, error) { - if h.Skippable { - magic := [4]byte{0x50, 0x2a, 0x4d, 0x18} - magic[0] |= byte(h.SkippableID & 0xf) - dst = append(dst, magic[:]...) - f := h.SkippableSize - return append(dst, uint8(f), uint8(f>>8), uint8(f>>16), uint8(f>>24)), nil - } - f := frameHeader{ - ContentSize: h.FrameContentSize, - WindowSize: uint32(h.WindowSize), - SingleSegment: h.SingleSegment, - Checksum: h.HasCheckSum, - DictID: h.DictionaryID, - } - return f.appendTo(dst), nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/decoder.go b/vendor/github.com/klauspost/compress/zstd/decoder.go deleted file mode 100644 index bbca17234..000000000 --- a/vendor/github.com/klauspost/compress/zstd/decoder.go +++ /dev/null @@ -1,948 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "context" - "encoding/binary" - "io" - "sync" - - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -// Decoder provides decoding of zstandard streams. -// The decoder has been designed to operate without allocations after a warmup. -// This means that you should store the decoder for best performance. -// To re-use a stream decoder, use the Reset(r io.Reader) error to switch to another stream. -// A decoder can safely be re-used even if the previous stream failed. -// To release the resources, you must call the Close() function on a decoder. -type Decoder struct { - o decoderOptions - - // Unreferenced decoders, ready for use. - decoders chan *blockDec - - // Current read position used for Reader functionality. - current decoderState - - // sync stream decoding - syncStream struct { - decodedFrame uint64 - br readerWrapper - enabled bool - inFrame bool - dstBuf []byte - } - - frame *frameDec - - // Custom dictionaries. - dicts map[uint32]*dict - - // streamWg is the waitgroup for all streams - streamWg sync.WaitGroup -} - -// decoderState is used for maintaining state when the decoder -// is used for streaming. -type decoderState struct { - // current block being written to stream. - decodeOutput - - // output in order to be written to stream. - output chan decodeOutput - - // cancel remaining output. - cancel context.CancelFunc - - // crc of current frame - crc *xxhash.Digest - - flushed bool -} - -var ( - // Check the interfaces we want to support. - _ = io.WriterTo(&Decoder{}) - _ = io.Reader(&Decoder{}) -) - -// NewReader creates a new decoder. -// A nil Reader can be provided in which case Reset can be used to start a decode. -// -// A Decoder can be used in two modes: -// -// 1) As a stream, or -// 2) For stateless decoding using DecodeAll. -// -// Only a single stream can be decoded concurrently, but the same decoder -// can run multiple concurrent stateless decodes. It is even possible to -// use stateless decodes while a stream is being decoded. -// -// The Reset function can be used to initiate a new stream, which will considerably -// reduce the allocations normally caused by NewReader. -func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) { - initPredefined() - var d Decoder - d.o.setDefault() - for _, o := range opts { - err := o(&d.o) - if err != nil { - return nil, err - } - } - d.current.crc = xxhash.New() - d.current.flushed = true - - if r == nil { - d.current.err = ErrDecoderNilInput - } - - // Transfer option dicts. - d.dicts = make(map[uint32]*dict, len(d.o.dicts)) - for _, dc := range d.o.dicts { - d.dicts[dc.id] = dc - } - d.o.dicts = nil - - // Create decoders - d.decoders = make(chan *blockDec, d.o.concurrent) - for i := 0; i < d.o.concurrent; i++ { - dec := newBlockDec(d.o.lowMem) - dec.localFrame = newFrameDec(d.o) - d.decoders <- dec - } - - if r == nil { - return &d, nil - } - return &d, d.Reset(r) -} - -// Read bytes from the decompressed stream into p. -// Returns the number of bytes written and any error that occurred. -// When the stream is done, io.EOF will be returned. -func (d *Decoder) Read(p []byte) (int, error) { - var n int - for { - if len(d.current.b) > 0 { - filled := copy(p, d.current.b) - p = p[filled:] - d.current.b = d.current.b[filled:] - n += filled - } - if len(p) == 0 { - break - } - if len(d.current.b) == 0 { - // We have an error and no more data - if d.current.err != nil { - break - } - if !d.nextBlock(n == 0) { - return n, d.current.err - } - } - } - if len(d.current.b) > 0 { - if debugDecoder { - println("returning", n, "still bytes left:", len(d.current.b)) - } - // Only return error at end of block - return n, nil - } - if d.current.err != nil { - d.drainOutput() - } - if debugDecoder { - println("returning", n, d.current.err, len(d.decoders)) - } - return n, d.current.err -} - -// Reset will reset the decoder the supplied stream after the current has finished processing. -// Note that this functionality cannot be used after Close has been called. -// Reset can be called with a nil reader to release references to the previous reader. -// After being called with a nil reader, no other operations than Reset or DecodeAll or Close -// should be used. -func (d *Decoder) Reset(r io.Reader) error { - if d.current.err == ErrDecoderClosed { - return d.current.err - } - - d.drainOutput() - - d.syncStream.br.r = nil - if r == nil { - d.current.err = ErrDecoderNilInput - if len(d.current.b) > 0 { - d.current.b = d.current.b[:0] - } - d.current.flushed = true - return nil - } - - // If bytes buffer and < 5MB, do sync decoding anyway. - if bb, ok := r.(byter); ok && bb.Len() < d.o.decodeBufsBelow && !d.o.limitToCap { - bb2 := bb - if debugDecoder { - println("*bytes.Buffer detected, doing sync decode, len:", bb.Len()) - } - b := bb2.Bytes() - var dst []byte - if cap(d.syncStream.dstBuf) > 0 { - dst = d.syncStream.dstBuf[:0] - } - - dst, err := d.DecodeAll(b, dst) - if err == nil { - err = io.EOF - } - // Save output buffer - d.syncStream.dstBuf = dst - d.current.b = dst - d.current.err = err - d.current.flushed = true - if debugDecoder { - println("sync decode to", len(dst), "bytes, err:", err) - } - return nil - } - // Remove current block. - d.stashDecoder() - d.current.decodeOutput = decodeOutput{} - d.current.err = nil - d.current.flushed = false - d.current.d = nil - d.syncStream.dstBuf = nil - - // Ensure no-one else is still running... - d.streamWg.Wait() - if d.frame == nil { - d.frame = newFrameDec(d.o) - } - - if d.o.concurrent == 1 { - return d.startSyncDecoder(r) - } - - d.current.output = make(chan decodeOutput, d.o.concurrent) - ctx, cancel := context.WithCancel(context.Background()) - d.current.cancel = cancel - d.streamWg.Add(1) - go d.startStreamDecoder(ctx, r, d.current.output) - - return nil -} - -// drainOutput will drain the output until errEndOfStream is sent. -func (d *Decoder) drainOutput() { - if d.current.cancel != nil { - if debugDecoder { - println("cancelling current") - } - d.current.cancel() - d.current.cancel = nil - } - if d.current.d != nil { - if debugDecoder { - printf("re-adding current decoder %p, decoders: %d", d.current.d, len(d.decoders)) - } - d.decoders <- d.current.d - d.current.d = nil - d.current.b = nil - } - if d.current.output == nil || d.current.flushed { - println("current already flushed") - return - } - for v := range d.current.output { - if v.d != nil { - if debugDecoder { - printf("re-adding decoder %p", v.d) - } - d.decoders <- v.d - } - } - d.current.output = nil - d.current.flushed = true -} - -// WriteTo writes data to w until there's no more data to write or when an error occurs. -// The return value n is the number of bytes written. -// Any error encountered during the write is also returned. -func (d *Decoder) WriteTo(w io.Writer) (int64, error) { - var n int64 - for { - if len(d.current.b) > 0 { - n2, err2 := w.Write(d.current.b) - n += int64(n2) - if err2 != nil && (d.current.err == nil || d.current.err == io.EOF) { - d.current.err = err2 - } else if n2 != len(d.current.b) { - d.current.err = io.ErrShortWrite - } - } - if d.current.err != nil { - break - } - d.nextBlock(true) - } - err := d.current.err - if err != nil { - d.drainOutput() - } - if err == io.EOF { - err = nil - } - return n, err -} - -// DecodeAll allows stateless decoding of a blob of bytes. -// Output will be appended to dst, so if the destination size is known -// you can pre-allocate the destination slice to avoid allocations. -// DecodeAll can be used concurrently. -// The Decoder concurrency limits will be respected. -func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { - if d.decoders == nil { - return dst, ErrDecoderClosed - } - - // Grab a block decoder and frame decoder. - block := <-d.decoders - frame := block.localFrame - initialSize := len(dst) - defer func() { - if debugDecoder { - printf("re-adding decoder: %p", block) - } - frame.rawInput = nil - frame.bBuf = nil - if frame.history.decoders.br != nil { - frame.history.decoders.br.in = nil - } - d.decoders <- block - }() - frame.bBuf = input - - for { - frame.history.reset() - err := frame.reset(&frame.bBuf) - if err != nil { - if err == io.EOF { - if debugDecoder { - println("frame reset return EOF") - } - return dst, nil - } - return dst, err - } - if err = d.setDict(frame); err != nil { - return nil, err - } - if frame.WindowSize > d.o.maxWindowSize { - if debugDecoder { - println("window size exceeded:", frame.WindowSize, ">", d.o.maxWindowSize) - } - return dst, ErrWindowSizeExceeded - } - if frame.FrameContentSize != fcsUnknown { - if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)-initialSize) { - if debugDecoder { - println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", d.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst)) - } - return dst, ErrDecoderSizeExceeded - } - if d.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) { - if debugDecoder { - println("decoder size exceeded; fcs:", frame.FrameContentSize, "> (cap-len)", cap(dst)-len(dst)) - } - return dst, ErrDecoderSizeExceeded - } - if cap(dst)-len(dst) < int(frame.FrameContentSize) { - dst2 := make([]byte, len(dst), len(dst)+int(frame.FrameContentSize)+compressedBlockOverAlloc) - copy(dst2, dst) - dst = dst2 - } - } - - if cap(dst) == 0 && !d.o.limitToCap { - // Allocate len(input) * 2 by default if nothing is provided - // and we didn't get frame content size. - size := len(input) * 2 - // Cap to 1 MB. - if size > 1<<20 { - size = 1 << 20 - } - if uint64(size) > d.o.maxDecodedSize { - size = int(d.o.maxDecodedSize) - } - dst = make([]byte, 0, size) - } - - dst, err = frame.runDecoder(dst, block) - if err != nil { - return dst, err - } - if uint64(len(dst)-initialSize) > d.o.maxDecodedSize { - return dst, ErrDecoderSizeExceeded - } - if len(frame.bBuf) == 0 { - if debugDecoder { - println("frame dbuf empty") - } - break - } - } - return dst, nil -} - -// nextBlock returns the next block. -// If an error occurs d.err will be set. -// Optionally the function can block for new output. -// If non-blocking mode is used the returned boolean will be false -// if no data was available without blocking. -func (d *Decoder) nextBlock(blocking bool) (ok bool) { - if d.current.err != nil { - // Keep error state. - return false - } - d.current.b = d.current.b[:0] - - // SYNC: - if d.syncStream.enabled { - if !blocking { - return false - } - ok = d.nextBlockSync() - if !ok { - d.stashDecoder() - } - return ok - } - - //ASYNC: - d.stashDecoder() - if blocking { - d.current.decodeOutput, ok = <-d.current.output - } else { - select { - case d.current.decodeOutput, ok = <-d.current.output: - default: - return false - } - } - if !ok { - // This should not happen, so signal error state... - d.current.err = io.ErrUnexpectedEOF - return false - } - next := d.current.decodeOutput - if next.d != nil && next.d.async.newHist != nil { - d.current.crc.Reset() - } - if debugDecoder { - var tmp [4]byte - binary.LittleEndian.PutUint32(tmp[:], uint32(xxhash.Sum64(next.b))) - println("got", len(d.current.b), "bytes, error:", d.current.err, "data crc:", tmp) - } - - if d.o.ignoreChecksum { - return true - } - - if len(next.b) > 0 { - d.current.crc.Write(next.b) - } - if next.err == nil && next.d != nil && next.d.hasCRC { - got := uint32(d.current.crc.Sum64()) - if got != next.d.checkCRC { - if debugDecoder { - printf("CRC Check Failed: %08x (got) != %08x (on stream)\n", got, next.d.checkCRC) - } - d.current.err = ErrCRCMismatch - } else { - if debugDecoder { - printf("CRC ok %08x\n", got) - } - } - } - - return true -} - -func (d *Decoder) nextBlockSync() (ok bool) { - if d.current.d == nil { - d.current.d = <-d.decoders - } - for len(d.current.b) == 0 { - if !d.syncStream.inFrame { - d.frame.history.reset() - d.current.err = d.frame.reset(&d.syncStream.br) - if d.current.err == nil { - d.current.err = d.setDict(d.frame) - } - if d.current.err != nil { - return false - } - if d.frame.WindowSize > d.o.maxDecodedSize || d.frame.WindowSize > d.o.maxWindowSize { - d.current.err = ErrDecoderSizeExceeded - return false - } - - d.syncStream.decodedFrame = 0 - d.syncStream.inFrame = true - } - d.current.err = d.frame.next(d.current.d) - if d.current.err != nil { - return false - } - d.frame.history.ensureBlock() - if debugDecoder { - println("History trimmed:", len(d.frame.history.b), "decoded already:", d.syncStream.decodedFrame) - } - histBefore := len(d.frame.history.b) - d.current.err = d.current.d.decodeBuf(&d.frame.history) - - if d.current.err != nil { - println("error after:", d.current.err) - return false - } - d.current.b = d.frame.history.b[histBefore:] - if debugDecoder { - println("history after:", len(d.frame.history.b)) - } - - // Check frame size (before CRC) - d.syncStream.decodedFrame += uint64(len(d.current.b)) - if d.syncStream.decodedFrame > d.frame.FrameContentSize { - if debugDecoder { - printf("DecodedFrame (%d) > FrameContentSize (%d)\n", d.syncStream.decodedFrame, d.frame.FrameContentSize) - } - d.current.err = ErrFrameSizeExceeded - return false - } - - // Check FCS - if d.current.d.Last && d.frame.FrameContentSize != fcsUnknown && d.syncStream.decodedFrame != d.frame.FrameContentSize { - if debugDecoder { - printf("DecodedFrame (%d) != FrameContentSize (%d)\n", d.syncStream.decodedFrame, d.frame.FrameContentSize) - } - d.current.err = ErrFrameSizeMismatch - return false - } - - // Update/Check CRC - if d.frame.HasCheckSum { - if !d.o.ignoreChecksum { - d.frame.crc.Write(d.current.b) - } - if d.current.d.Last { - if !d.o.ignoreChecksum { - d.current.err = d.frame.checkCRC() - } else { - d.current.err = d.frame.consumeCRC() - } - if d.current.err != nil { - println("CRC error:", d.current.err) - return false - } - } - } - d.syncStream.inFrame = !d.current.d.Last - } - return true -} - -func (d *Decoder) stashDecoder() { - if d.current.d != nil { - if debugDecoder { - printf("re-adding current decoder %p", d.current.d) - } - d.decoders <- d.current.d - d.current.d = nil - } -} - -// Close will release all resources. -// It is NOT possible to reuse the decoder after this. -func (d *Decoder) Close() { - if d.current.err == ErrDecoderClosed { - return - } - d.drainOutput() - if d.current.cancel != nil { - d.current.cancel() - d.streamWg.Wait() - d.current.cancel = nil - } - if d.decoders != nil { - close(d.decoders) - for dec := range d.decoders { - dec.Close() - } - d.decoders = nil - } - if d.current.d != nil { - d.current.d.Close() - d.current.d = nil - } - d.current.err = ErrDecoderClosed -} - -// IOReadCloser returns the decoder as an io.ReadCloser for convenience. -// Any changes to the decoder will be reflected, so the returned ReadCloser -// can be reused along with the decoder. -// io.WriterTo is also supported by the returned ReadCloser. -func (d *Decoder) IOReadCloser() io.ReadCloser { - return closeWrapper{d: d} -} - -// closeWrapper wraps a function call as a closer. -type closeWrapper struct { - d *Decoder -} - -// WriteTo forwards WriteTo calls to the decoder. -func (c closeWrapper) WriteTo(w io.Writer) (n int64, err error) { - return c.d.WriteTo(w) -} - -// Read forwards read calls to the decoder. -func (c closeWrapper) Read(p []byte) (n int, err error) { - return c.d.Read(p) -} - -// Close closes the decoder. -func (c closeWrapper) Close() error { - c.d.Close() - return nil -} - -type decodeOutput struct { - d *blockDec - b []byte - err error -} - -func (d *Decoder) startSyncDecoder(r io.Reader) error { - d.frame.history.reset() - d.syncStream.br = readerWrapper{r: r} - d.syncStream.inFrame = false - d.syncStream.enabled = true - d.syncStream.decodedFrame = 0 - return nil -} - -// Create Decoder: -// ASYNC: -// Spawn 3 go routines. -// 0: Read frames and decode block literals. -// 1: Decode sequences. -// 2: Execute sequences, send to output. -func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output chan decodeOutput) { - defer d.streamWg.Done() - br := readerWrapper{r: r} - - var seqDecode = make(chan *blockDec, d.o.concurrent) - var seqExecute = make(chan *blockDec, d.o.concurrent) - - // Async 1: Decode sequences... - go func() { - var hist history - var hasErr bool - - for block := range seqDecode { - if hasErr { - if block != nil { - seqExecute <- block - } - continue - } - if block.async.newHist != nil { - if debugDecoder { - println("Async 1: new history, recent:", block.async.newHist.recentOffsets) - } - hist.reset() - hist.decoders = block.async.newHist.decoders - hist.recentOffsets = block.async.newHist.recentOffsets - hist.windowSize = block.async.newHist.windowSize - if block.async.newHist.dict != nil { - hist.setDict(block.async.newHist.dict) - } - } - if block.err != nil || block.Type != blockTypeCompressed { - hasErr = block.err != nil - seqExecute <- block - continue - } - - hist.decoders.literals = block.async.literals - block.err = block.prepareSequences(block.async.seqData, &hist) - if debugDecoder && block.err != nil { - println("prepareSequences returned:", block.err) - } - hasErr = block.err != nil - if block.err == nil { - block.err = block.decodeSequences(&hist) - if debugDecoder && block.err != nil { - println("decodeSequences returned:", block.err) - } - hasErr = block.err != nil - // block.async.sequence = hist.decoders.seq[:hist.decoders.nSeqs] - block.async.seqSize = hist.decoders.seqSize - } - seqExecute <- block - } - close(seqExecute) - hist.reset() - }() - - var wg sync.WaitGroup - wg.Add(1) - - // Async 3: Execute sequences... - frameHistCache := d.frame.history.b - go func() { - var hist history - var decodedFrame uint64 - var fcs uint64 - var hasErr bool - for block := range seqExecute { - out := decodeOutput{err: block.err, d: block} - if block.err != nil || hasErr { - hasErr = true - output <- out - continue - } - if block.async.newHist != nil { - if debugDecoder { - println("Async 2: new history") - } - hist.reset() - hist.windowSize = block.async.newHist.windowSize - hist.allocFrameBuffer = block.async.newHist.allocFrameBuffer - if block.async.newHist.dict != nil { - hist.setDict(block.async.newHist.dict) - } - - if cap(hist.b) < hist.allocFrameBuffer { - if cap(frameHistCache) >= hist.allocFrameBuffer { - hist.b = frameHistCache - } else { - hist.b = make([]byte, 0, hist.allocFrameBuffer) - println("Alloc history sized", hist.allocFrameBuffer) - } - } - hist.b = hist.b[:0] - fcs = block.async.fcs - decodedFrame = 0 - } - do := decodeOutput{err: block.err, d: block} - switch block.Type { - case blockTypeRLE: - if debugDecoder { - println("add rle block length:", block.RLESize) - } - - if cap(block.dst) < int(block.RLESize) { - if block.lowMem { - block.dst = make([]byte, block.RLESize) - } else { - block.dst = make([]byte, maxCompressedBlockSize) - } - } - block.dst = block.dst[:block.RLESize] - v := block.data[0] - for i := range block.dst { - block.dst[i] = v - } - hist.append(block.dst) - do.b = block.dst - case blockTypeRaw: - if debugDecoder { - println("add raw block length:", len(block.data)) - } - hist.append(block.data) - do.b = block.data - case blockTypeCompressed: - if debugDecoder { - println("execute with history length:", len(hist.b), "window:", hist.windowSize) - } - hist.decoders.seqSize = block.async.seqSize - hist.decoders.literals = block.async.literals - do.err = block.executeSequences(&hist) - hasErr = do.err != nil - if debugDecoder && hasErr { - println("executeSequences returned:", do.err) - } - do.b = block.dst - } - if !hasErr { - decodedFrame += uint64(len(do.b)) - if decodedFrame > fcs { - println("fcs exceeded", block.Last, fcs, decodedFrame) - do.err = ErrFrameSizeExceeded - hasErr = true - } else if block.Last && fcs != fcsUnknown && decodedFrame != fcs { - do.err = ErrFrameSizeMismatch - hasErr = true - } else { - if debugDecoder { - println("fcs ok", block.Last, fcs, decodedFrame) - } - } - } - output <- do - } - close(output) - frameHistCache = hist.b - wg.Done() - if debugDecoder { - println("decoder goroutines finished") - } - hist.reset() - }() - - var hist history -decodeStream: - for { - var hasErr bool - hist.reset() - decodeBlock := func(block *blockDec) { - if hasErr { - if block != nil { - seqDecode <- block - } - return - } - if block.err != nil || block.Type != blockTypeCompressed { - hasErr = block.err != nil - seqDecode <- block - return - } - - remain, err := block.decodeLiterals(block.data, &hist) - block.err = err - hasErr = block.err != nil - if err == nil { - block.async.literals = hist.decoders.literals - block.async.seqData = remain - } else if debugDecoder { - println("decodeLiterals error:", err) - } - seqDecode <- block - } - frame := d.frame - if debugDecoder { - println("New frame...") - } - var historySent bool - frame.history.reset() - err := frame.reset(&br) - if debugDecoder && err != nil { - println("Frame decoder returned", err) - } - if err == nil { - err = d.setDict(frame) - } - if err == nil && d.frame.WindowSize > d.o.maxWindowSize { - if debugDecoder { - println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.o.maxWindowSize) - } - - err = ErrDecoderSizeExceeded - } - if err != nil { - select { - case <-ctx.Done(): - case dec := <-d.decoders: - dec.sendErr(err) - decodeBlock(dec) - } - break decodeStream - } - - // Go through all blocks of the frame. - for { - var dec *blockDec - select { - case <-ctx.Done(): - break decodeStream - case dec = <-d.decoders: - // Once we have a decoder, we MUST return it. - } - err := frame.next(dec) - if !historySent { - h := frame.history - if debugDecoder { - println("Alloc History:", h.allocFrameBuffer) - } - hist.reset() - if h.dict != nil { - hist.setDict(h.dict) - } - dec.async.newHist = &h - dec.async.fcs = frame.FrameContentSize - historySent = true - } else { - dec.async.newHist = nil - } - if debugDecoder && err != nil { - println("next block returned error:", err) - } - dec.err = err - dec.hasCRC = false - if dec.Last && frame.HasCheckSum && err == nil { - crc, err := frame.rawInput.readSmall(4) - if len(crc) < 4 { - if err == nil { - err = io.ErrUnexpectedEOF - - } - println("CRC missing?", err) - dec.err = err - } else { - dec.checkCRC = binary.LittleEndian.Uint32(crc) - dec.hasCRC = true - if debugDecoder { - printf("found crc to check: %08x\n", dec.checkCRC) - } - } - } - err = dec.err - last := dec.Last - decodeBlock(dec) - if err != nil { - break decodeStream - } - if last { - break - } - } - } - close(seqDecode) - wg.Wait() - hist.reset() - d.frame.history.b = frameHistCache -} - -func (d *Decoder) setDict(frame *frameDec) (err error) { - dict, ok := d.dicts[frame.DictionaryID] - if ok { - if debugDecoder { - println("setting dict", frame.DictionaryID) - } - frame.history.setDict(dict) - } else if frame.DictionaryID != 0 { - // A zero or missing dictionary id is ambiguous: - // either dictionary zero, or no dictionary. In particular, - // zstd --patch-from uses this id for the source file, - // so only return an error if the dictionary id is not zero. - err = ErrUnknownDictionary - } - return err -} diff --git a/vendor/github.com/klauspost/compress/zstd/decoder_options.go b/vendor/github.com/klauspost/compress/zstd/decoder_options.go deleted file mode 100644 index 774c5f00f..000000000 --- a/vendor/github.com/klauspost/compress/zstd/decoder_options.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "fmt" - "math/bits" - "runtime" -) - -// DOption is an option for creating a decoder. -type DOption func(*decoderOptions) error - -// options retains accumulated state of multiple options. -type decoderOptions struct { - lowMem bool - concurrent int - maxDecodedSize uint64 - maxWindowSize uint64 - dicts []*dict - ignoreChecksum bool - limitToCap bool - decodeBufsBelow int -} - -func (o *decoderOptions) setDefault() { - *o = decoderOptions{ - // use less ram: true for now, but may change. - lowMem: true, - concurrent: runtime.GOMAXPROCS(0), - maxWindowSize: MaxWindowSize, - decodeBufsBelow: 128 << 10, - } - if o.concurrent > 4 { - o.concurrent = 4 - } - o.maxDecodedSize = 64 << 30 -} - -// WithDecoderLowmem will set whether to use a lower amount of memory, -// but possibly have to allocate more while running. -func WithDecoderLowmem(b bool) DOption { - return func(o *decoderOptions) error { o.lowMem = b; return nil } -} - -// WithDecoderConcurrency sets the number of created decoders. -// When decoding block with DecodeAll, this will limit the number -// of possible concurrently running decodes. -// When decoding streams, this will limit the number of -// inflight blocks. -// When decoding streams and setting maximum to 1, -// no async decoding will be done. -// When a value of 0 is provided GOMAXPROCS will be used. -// By default this will be set to 4 or GOMAXPROCS, whatever is lower. -func WithDecoderConcurrency(n int) DOption { - return func(o *decoderOptions) error { - if n < 0 { - return errors.New("concurrency must be at least 1") - } - if n == 0 { - o.concurrent = runtime.GOMAXPROCS(0) - } else { - o.concurrent = n - } - return nil - } -} - -// WithDecoderMaxMemory allows to set a maximum decoded size for in-memory -// non-streaming operations or maximum window size for streaming operations. -// This can be used to control memory usage of potentially hostile content. -// Maximum is 1 << 63 bytes. Default is 64GiB. -func WithDecoderMaxMemory(n uint64) DOption { - return func(o *decoderOptions) error { - if n == 0 { - return errors.New("WithDecoderMaxMemory must be at least 1") - } - if n > 1<<63 { - return errors.New("WithDecoderMaxmemory must be less than 1 << 63") - } - o.maxDecodedSize = n - return nil - } -} - -// WithDecoderDicts allows to register one or more dictionaries for the decoder. -// -// Each slice in dict must be in the [dictionary format] produced by -// "zstd --train" from the Zstandard reference implementation. -// -// If several dictionaries with the same ID are provided, the last one will be used. -// -// [dictionary format]: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary-format -func WithDecoderDicts(dicts ...[]byte) DOption { - return func(o *decoderOptions) error { - for _, b := range dicts { - d, err := loadDict(b) - if err != nil { - return err - } - o.dicts = append(o.dicts, d) - } - return nil - } -} - -// WithDecoderDictRaw registers a dictionary that may be used by the decoder. -// The slice content can be arbitrary data. -func WithDecoderDictRaw(id uint32, content []byte) DOption { - return func(o *decoderOptions) error { - if bits.UintSize > 32 && uint(len(content)) > dictMaxLength { - return fmt.Errorf("dictionary of size %d > 2GiB too large", len(content)) - } - o.dicts = append(o.dicts, &dict{id: id, content: content, offsets: [3]int{1, 4, 8}}) - return nil - } -} - -// WithDecoderMaxWindow allows to set a maximum window size for decodes. -// This allows rejecting packets that will cause big memory usage. -// The Decoder will likely allocate more memory based on the WithDecoderLowmem setting. -// If WithDecoderMaxMemory is set to a lower value, that will be used. -// Default is 512MB, Maximum is ~3.75 TB as per zstandard spec. -func WithDecoderMaxWindow(size uint64) DOption { - return func(o *decoderOptions) error { - if size < MinWindowSize { - return errors.New("WithMaxWindowSize must be at least 1KB, 1024 bytes") - } - if size > (1<<41)+7*(1<<38) { - return errors.New("WithMaxWindowSize must be less than (1<<41) + 7*(1<<38) ~ 3.75TB") - } - o.maxWindowSize = size - return nil - } -} - -// WithDecodeAllCapLimit will limit DecodeAll to decoding cap(dst)-len(dst) bytes, -// or any size set in WithDecoderMaxMemory. -// This can be used to limit decoding to a specific maximum output size. -// Disabled by default. -func WithDecodeAllCapLimit(b bool) DOption { - return func(o *decoderOptions) error { - o.limitToCap = b - return nil - } -} - -// WithDecodeBuffersBelow will fully decode readers that have a -// `Bytes() []byte` and `Len() int` interface similar to bytes.Buffer. -// This typically uses less allocations but will have the full decompressed object in memory. -// Note that DecodeAllCapLimit will disable this, as well as giving a size of 0 or less. -// Default is 128KiB. -func WithDecodeBuffersBelow(size int) DOption { - return func(o *decoderOptions) error { - o.decodeBufsBelow = size - return nil - } -} - -// IgnoreChecksum allows to forcibly ignore checksum checking. -func IgnoreChecksum(b bool) DOption { - return func(o *decoderOptions) error { - o.ignoreChecksum = b - return nil - } -} diff --git a/vendor/github.com/klauspost/compress/zstd/dict.go b/vendor/github.com/klauspost/compress/zstd/dict.go deleted file mode 100644 index b7b83164b..000000000 --- a/vendor/github.com/klauspost/compress/zstd/dict.go +++ /dev/null @@ -1,565 +0,0 @@ -package zstd - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "sort" - - "github.com/klauspost/compress/huff0" -) - -type dict struct { - id uint32 - - litEnc *huff0.Scratch - llDec, ofDec, mlDec sequenceDec - offsets [3]int - content []byte -} - -const dictMagic = "\x37\xa4\x30\xec" - -// Maximum dictionary size for the reference implementation (1.5.3) is 2 GiB. -const dictMaxLength = 1 << 31 - -// ID returns the dictionary id or 0 if d is nil. -func (d *dict) ID() uint32 { - if d == nil { - return 0 - } - return d.id -} - -// ContentSize returns the dictionary content size or 0 if d is nil. -func (d *dict) ContentSize() int { - if d == nil { - return 0 - } - return len(d.content) -} - -// Content returns the dictionary content. -func (d *dict) Content() []byte { - if d == nil { - return nil - } - return d.content -} - -// Offsets returns the initial offsets. -func (d *dict) Offsets() [3]int { - if d == nil { - return [3]int{} - } - return d.offsets -} - -// LitEncoder returns the literal encoder. -func (d *dict) LitEncoder() *huff0.Scratch { - if d == nil { - return nil - } - return d.litEnc -} - -// Load a dictionary as described in -// https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format -func loadDict(b []byte) (*dict, error) { - // Check static field size. - if len(b) <= 8+(3*4) { - return nil, io.ErrUnexpectedEOF - } - d := dict{ - llDec: sequenceDec{fse: &fseDecoder{}}, - ofDec: sequenceDec{fse: &fseDecoder{}}, - mlDec: sequenceDec{fse: &fseDecoder{}}, - } - if string(b[:4]) != dictMagic { - return nil, ErrMagicMismatch - } - d.id = binary.LittleEndian.Uint32(b[4:8]) - if d.id == 0 { - return nil, errors.New("dictionaries cannot have ID 0") - } - - // Read literal table - var err error - d.litEnc, b, err = huff0.ReadTable(b[8:], nil) - if err != nil { - return nil, fmt.Errorf("loading literal table: %w", err) - } - d.litEnc.Reuse = huff0.ReusePolicyMust - - br := byteReader{ - b: b, - off: 0, - } - readDec := func(i tableIndex, dec *fseDecoder) error { - if err := dec.readNCount(&br, uint16(maxTableSymbol[i])); err != nil { - return err - } - if br.overread() { - return io.ErrUnexpectedEOF - } - err = dec.transform(symbolTableX[i]) - if err != nil { - println("Transform table error:", err) - return err - } - if debugDecoder || debugEncoder { - println("Read table ok", "symbolLen:", dec.symbolLen) - } - // Set decoders as predefined so they aren't reused. - dec.preDefined = true - return nil - } - - if err := readDec(tableOffsets, d.ofDec.fse); err != nil { - return nil, err - } - if err := readDec(tableMatchLengths, d.mlDec.fse); err != nil { - return nil, err - } - if err := readDec(tableLiteralLengths, d.llDec.fse); err != nil { - return nil, err - } - if br.remain() < 12 { - return nil, io.ErrUnexpectedEOF - } - - d.offsets[0] = int(br.Uint32()) - br.advance(4) - d.offsets[1] = int(br.Uint32()) - br.advance(4) - d.offsets[2] = int(br.Uint32()) - br.advance(4) - if d.offsets[0] <= 0 || d.offsets[1] <= 0 || d.offsets[2] <= 0 { - return nil, errors.New("invalid offset in dictionary") - } - d.content = make([]byte, br.remain()) - copy(d.content, br.unread()) - if d.offsets[0] > len(d.content) || d.offsets[1] > len(d.content) || d.offsets[2] > len(d.content) { - return nil, fmt.Errorf("initial offset bigger than dictionary content size %d, offsets: %v", len(d.content), d.offsets) - } - - return &d, nil -} - -// InspectDictionary loads a zstd dictionary and provides functions to inspect the content. -func InspectDictionary(b []byte) (interface { - ID() uint32 - ContentSize() int - Content() []byte - Offsets() [3]int - LitEncoder() *huff0.Scratch -}, error) { - initPredefined() - d, err := loadDict(b) - return d, err -} - -type BuildDictOptions struct { - // Dictionary ID. - ID uint32 - - // Content to use to create dictionary tables. - Contents [][]byte - - // History to use for all blocks. - History []byte - - // Offsets to use. - Offsets [3]int - - // CompatV155 will make the dictionary compatible with Zstd v1.5.5 and earlier. - // See https://github.com/facebook/zstd/issues/3724 - CompatV155 bool - - // Use the specified encoder level. - // The dictionary will be built using the specified encoder level, - // which will reflect speed and make the dictionary tailored for that level. - // If not set SpeedBestCompression will be used. - Level EncoderLevel - - // DebugOut will write stats and other details here if set. - DebugOut io.Writer -} - -func BuildDict(o BuildDictOptions) ([]byte, error) { - initPredefined() - hist := o.History - contents := o.Contents - debug := o.DebugOut != nil - println := func(args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprintln(o.DebugOut, args...) - } - } - printf := func(s string, args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprintf(o.DebugOut, s, args...) - } - } - print := func(args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprint(o.DebugOut, args...) - } - } - - if int64(len(hist)) > dictMaxLength { - return nil, fmt.Errorf("dictionary of size %d > %d", len(hist), int64(dictMaxLength)) - } - if len(hist) < 8 { - return nil, fmt.Errorf("dictionary of size %d < %d", len(hist), 8) - } - if len(contents) == 0 { - return nil, errors.New("no content provided") - } - d := dict{ - id: o.ID, - litEnc: nil, - llDec: sequenceDec{}, - ofDec: sequenceDec{}, - mlDec: sequenceDec{}, - offsets: o.Offsets, - content: hist, - } - block := blockEnc{lowMem: false} - block.init() - enc := encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}}) - if o.Level != 0 { - eOpts := encoderOptions{ - level: o.Level, - blockSize: maxMatchLen, - windowSize: maxMatchLen, - dict: &d, - lowMem: false, - } - enc = eOpts.encoder() - } else { - o.Level = SpeedBestCompression - } - var ( - remain [256]int - ll [256]int - ml [256]int - of [256]int - ) - addValues := func(dst *[256]int, src []byte) { - for _, v := range src { - dst[v]++ - } - } - addHist := func(dst *[256]int, src *[256]uint32) { - for i, v := range src { - dst[i] += int(v) - } - } - seqs := 0 - nUsed := 0 - litTotal := 0 - newOffsets := make(map[uint32]int, 1000) - for _, b := range contents { - block.reset(nil) - if len(b) < 8 { - continue - } - nUsed++ - enc.Reset(&d, true) - enc.Encode(&block, b) - addValues(&remain, block.literals) - litTotal += len(block.literals) - if len(block.sequences) == 0 { - continue - } - seqs += len(block.sequences) - block.genCodes() - addHist(&ll, block.coders.llEnc.Histogram()) - addHist(&ml, block.coders.mlEnc.Histogram()) - addHist(&of, block.coders.ofEnc.Histogram()) - for i, seq := range block.sequences { - if i > 3 { - break - } - offset := seq.offset - if offset == 0 { - continue - } - if int(offset) >= len(o.History) { - continue - } - if offset > 3 { - newOffsets[offset-3]++ - } else { - newOffsets[uint32(o.Offsets[offset-1])]++ - } - } - } - // Find most used offsets. - var sortedOffsets []uint32 - for k := range newOffsets { - sortedOffsets = append(sortedOffsets, k) - } - sort.Slice(sortedOffsets, func(i, j int) bool { - a, b := sortedOffsets[i], sortedOffsets[j] - if a == b { - // Prefer the longer offset - return sortedOffsets[i] > sortedOffsets[j] - } - return newOffsets[sortedOffsets[i]] > newOffsets[sortedOffsets[j]] - }) - if len(sortedOffsets) > 3 { - if debug { - print("Offsets:") - for i, v := range sortedOffsets { - if i > 20 { - break - } - printf("[%d: %d],", v, newOffsets[v]) - } - println("") - } - - sortedOffsets = sortedOffsets[:3] - } - for i, v := range sortedOffsets { - o.Offsets[i] = int(v) - } - if debug { - println("New repeat offsets", o.Offsets) - } - - if nUsed == 0 || seqs == 0 { - return nil, fmt.Errorf("%d blocks, %d sequences found", nUsed, seqs) - } - if debug { - println("Sequences:", seqs, "Blocks:", nUsed, "Literals:", litTotal) - } - if seqs/nUsed < 512 { - // Use 512 as minimum. - nUsed = seqs / 512 - if nUsed == 0 { - nUsed = 1 - } - } - copyHist := func(dst *fseEncoder, src *[256]int) ([]byte, error) { - hist := dst.Histogram() - var maxSym uint8 - var maxCount int - var fakeLength int - for i, v := range src { - if v > 0 { - v = v / nUsed - if v == 0 { - v = 1 - } - } - if v > maxCount { - maxCount = v - } - if v != 0 { - maxSym = uint8(i) - } - fakeLength += v - hist[i] = uint32(v) - } - - // Ensure we aren't trying to represent RLE. - if maxCount == fakeLength { - for i := range hist { - if uint8(i) == maxSym { - fakeLength++ - maxSym++ - hist[i+1] = 1 - if maxSym > 1 { - break - } - } - if hist[0] == 0 { - fakeLength++ - hist[i] = 1 - if maxSym > 1 { - break - } - } - } - } - - dst.HistogramFinished(maxSym, maxCount) - dst.reUsed = false - dst.useRLE = false - err := dst.normalizeCount(fakeLength) - if err != nil { - return nil, err - } - if debug { - println("RAW:", dst.count[:maxSym+1], "NORM:", dst.norm[:maxSym+1], "LEN:", fakeLength) - } - return dst.writeCount(nil) - } - if debug { - print("Literal lengths: ") - } - llTable, err := copyHist(block.coders.llEnc, &ll) - if err != nil { - return nil, err - } - if debug { - print("Match lengths: ") - } - mlTable, err := copyHist(block.coders.mlEnc, &ml) - if err != nil { - return nil, err - } - if debug { - print("Offsets: ") - } - ofTable, err := copyHist(block.coders.ofEnc, &of) - if err != nil { - return nil, err - } - - // Literal table - avgSize := litTotal - if avgSize > huff0.BlockSizeMax/2 { - avgSize = huff0.BlockSizeMax / 2 - } - huffBuff := make([]byte, 0, avgSize) - // Target size - div := litTotal / avgSize - if div < 1 { - div = 1 - } - if debug { - println("Huffman weights:") - } - for i, n := range remain[:] { - if n > 0 { - n = n / div - // Allow all entries to be represented. - if n == 0 { - n = 1 - } - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - if debug { - printf("[%d: %d], ", i, n) - } - } - } - if o.CompatV155 && remain[255]/div == 0 { - huffBuff = append(huffBuff, 255) - } - scratch := &huff0.Scratch{TableLog: 11} - for tries := 0; tries < 255; tries++ { - scratch = &huff0.Scratch{TableLog: 11} - _, _, err = huff0.Compress1X(huffBuff, scratch) - if err == nil { - break - } - if debug { - printf("Try %d: Huffman error: %v\n", tries+1, err) - } - huffBuff = huffBuff[:0] - if tries == 250 { - if debug { - println("Huffman: Bailing out with predefined table") - } - - // Bail out.... Just generate something - huffBuff = append(huffBuff, bytes.Repeat([]byte{255}, 10000)...) - for i := 0; i < 128; i++ { - huffBuff = append(huffBuff, byte(i)) - } - continue - } - if errors.Is(err, huff0.ErrIncompressible) { - // Try truncating least common. - for i, n := range remain[:] { - if n > 0 { - n = n / (div * (i + 1)) - if n > 0 { - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - } - } - } - if o.CompatV155 && len(huffBuff) > 0 && huffBuff[len(huffBuff)-1] != 255 { - huffBuff = append(huffBuff, 255) - } - if len(huffBuff) == 0 { - huffBuff = append(huffBuff, 0, 255) - } - } - if errors.Is(err, huff0.ErrUseRLE) { - for i, n := range remain[:] { - n = n / (div * (i + 1)) - // Allow all entries to be represented. - if n == 0 { - n = 1 - } - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - } - } - } - - var out bytes.Buffer - out.Write([]byte(dictMagic)) - out.Write(binary.LittleEndian.AppendUint32(nil, o.ID)) - out.Write(scratch.OutTable) - if debug { - println("huff table:", len(scratch.OutTable), "bytes") - println("of table:", len(ofTable), "bytes") - println("ml table:", len(mlTable), "bytes") - println("ll table:", len(llTable), "bytes") - } - out.Write(ofTable) - out.Write(mlTable) - out.Write(llTable) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[0]))) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[1]))) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[2]))) - out.Write(hist) - if debug { - _, err := loadDict(out.Bytes()) - if err != nil { - panic(err) - } - i, err := InspectDictionary(out.Bytes()) - if err != nil { - panic(err) - } - println("ID:", i.ID()) - println("Content size:", i.ContentSize()) - println("Encoder:", i.LitEncoder() != nil) - println("Offsets:", i.Offsets()) - var totalSize int - for _, b := range contents { - totalSize += len(b) - } - - encWith := func(opts ...EOption) int { - enc, err := NewWriter(nil, opts...) - if err != nil { - panic(err) - } - defer enc.Close() - var dst []byte - var totalSize int - for _, b := range contents { - dst = enc.EncodeAll(b, dst[:0]) - totalSize += len(dst) - } - return totalSize - } - plain := encWith(WithEncoderLevel(o.Level)) - withDict := encWith(WithEncoderLevel(o.Level), WithEncoderDict(out.Bytes())) - println("Input size:", totalSize) - println("Plain Compressed:", plain) - println("Dict Compressed:", withDict) - println("Saved:", plain-withDict, (plain-withDict)/len(contents), "bytes per input (rounded down)") - } - return out.Bytes(), nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_base.go b/vendor/github.com/klauspost/compress/zstd/enc_base.go deleted file mode 100644 index 5ca46038a..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_base.go +++ /dev/null @@ -1,173 +0,0 @@ -package zstd - -import ( - "fmt" - "math/bits" - - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -const ( - dictShardBits = 6 -) - -type fastBase struct { - // cur is the offset at the start of hist - cur int32 - // maximum offset. Should be at least 2x block size. - maxMatchOff int32 - bufferReset int32 - hist []byte - crc *xxhash.Digest - tmp [8]byte - blk *blockEnc - lastDictID uint32 - lowMem bool -} - -// CRC returns the underlying CRC writer. -func (e *fastBase) CRC() *xxhash.Digest { - return e.crc -} - -// AppendCRC will append the CRC to the destination slice and return it. -func (e *fastBase) AppendCRC(dst []byte) []byte { - crc := e.crc.Sum(e.tmp[:0]) - dst = append(dst, crc[7], crc[6], crc[5], crc[4]) - return dst -} - -// WindowSize returns the window size of the encoder, -// or a window size small enough to contain the input size, if > 0. -func (e *fastBase) WindowSize(size int64) int32 { - if size > 0 && size < int64(e.maxMatchOff) { - b := int32(1) << uint(bits.Len(uint(size))) - // Keep minimum window. - if b < 1024 { - b = 1024 - } - return b - } - return e.maxMatchOff -} - -// Block returns the current block. -func (e *fastBase) Block() *blockEnc { - return e.blk -} - -func (e *fastBase) addBlock(src []byte) int32 { - if debugAsserts && e.cur > e.bufferReset { - panic(fmt.Sprintf("ecur (%d) > buffer reset (%d)", e.cur, e.bufferReset)) - } - // check if we have space already - if len(e.hist)+len(src) > cap(e.hist) { - if cap(e.hist) == 0 { - e.ensureHist(len(src)) - } else { - if cap(e.hist) < int(e.maxMatchOff+maxCompressedBlockSize) { - panic(fmt.Errorf("unexpected buffer cap %d, want at least %d with window %d", cap(e.hist), e.maxMatchOff+maxCompressedBlockSize, e.maxMatchOff)) - } - // Move down - offset := int32(len(e.hist)) - e.maxMatchOff - copy(e.hist[0:e.maxMatchOff], e.hist[offset:]) - e.cur += offset - e.hist = e.hist[:e.maxMatchOff] - } - } - s := int32(len(e.hist)) - e.hist = append(e.hist, src...) - return s -} - -// ensureHist will ensure that history can keep at least this many bytes. -func (e *fastBase) ensureHist(n int) { - if cap(e.hist) >= n { - return - } - l := e.maxMatchOff - if (e.lowMem && e.maxMatchOff > maxCompressedBlockSize) || e.maxMatchOff <= maxCompressedBlockSize { - l += maxCompressedBlockSize - } else { - l += e.maxMatchOff - } - // Make it at least 1MB. - if l < 1<<20 && !e.lowMem { - l = 1 << 20 - } - // Make it at least the requested size. - if l < int32(n) { - l = int32(n) - } - e.hist = make([]byte, 0, l) -} - -// useBlock will replace the block with the provided one, -// but transfer recent offsets from the previous. -func (e *fastBase) UseBlock(enc *blockEnc) { - enc.reset(e.blk) - e.blk = enc -} - -func (e *fastBase) matchlen(s, t int32, src []byte) int32 { - if debugAsserts { - if s < 0 { - err := fmt.Sprintf("s (%d) < 0", s) - panic(err) - } - if t < 0 { - err := fmt.Sprintf("s (%d) < 0", s) - panic(err) - } - if s-t > e.maxMatchOff { - err := fmt.Sprintf("s (%d) - t (%d) > maxMatchOff (%d)", s, t, e.maxMatchOff) - panic(err) - } - if len(src)-int(s) > maxCompressedBlockSize { - panic(fmt.Sprintf("len(src)-s (%d) > maxCompressedBlockSize (%d)", len(src)-int(s), maxCompressedBlockSize)) - } - } - return int32(matchLen(src[s:], src[t:])) -} - -// Reset the encoding table. -func (e *fastBase) resetBase(d *dict, singleBlock bool) { - if e.blk == nil { - e.blk = &blockEnc{lowMem: e.lowMem} - e.blk.init() - } else { - e.blk.reset(nil) - } - e.blk.initNewEncode() - if e.crc == nil { - e.crc = xxhash.New() - } else { - e.crc.Reset() - } - e.blk.dictLitEnc = nil - if d != nil { - low := e.lowMem - if singleBlock { - e.lowMem = true - } - e.ensureHist(d.ContentSize() + maxCompressedBlockSize) - e.lowMem = low - } - - // We offset current position so everything will be out of reach. - // If above reset line, history will be purged. - if e.cur < e.bufferReset { - e.cur += e.maxMatchOff + int32(len(e.hist)) - } - e.hist = e.hist[:0] - if d != nil { - // Set offsets (currently not used) - for i, off := range d.offsets { - e.blk.recentOffsets[i] = uint32(off) - e.blk.prevRecentOffsets[i] = e.blk.recentOffsets[i] - } - // Transfer litenc. - e.blk.dictLitEnc = d.litEnc - e.hist = append(e.hist, d.content...) - } -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_best.go b/vendor/github.com/klauspost/compress/zstd/enc_best.go deleted file mode 100644 index 4613724e9..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_best.go +++ /dev/null @@ -1,560 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "bytes" - "fmt" - - "github.com/klauspost/compress" -) - -const ( - bestLongTableBits = 22 // Bits used in the long match table - bestLongTableSize = 1 << bestLongTableBits // Size of the table - bestLongLen = 8 // Bytes used for table hash - - // Note: Increasing the short table bits or making the hash shorter - // can actually lead to compression degradation since it will 'steal' more from the - // long match table and match offsets are quite big. - // This greatly depends on the type of input. - bestShortTableBits = 18 // Bits used in the short match table - bestShortTableSize = 1 << bestShortTableBits // Size of the table - bestShortLen = 4 // Bytes used for table hash - -) - -type match struct { - offset int32 - s int32 - length int32 - rep int32 - est int32 -} - -const highScore = maxMatchLen * 8 - -// estBits will estimate output bits from predefined tables. -func (m *match) estBits(bitsPerByte int32) { - mlc := mlCode(uint32(m.length - zstdMinMatch)) - var ofc uint8 - if m.rep < 0 { - ofc = ofCode(uint32(m.s-m.offset) + 3) - } else { - ofc = ofCode(uint32(m.rep) & 3) - } - // Cost, excluding - ofTT, mlTT := fsePredefEnc[tableOffsets].ct.symbolTT[ofc], fsePredefEnc[tableMatchLengths].ct.symbolTT[mlc] - - // Add cost of match encoding... - m.est = int32(ofTT.outBits + mlTT.outBits) - m.est += int32(ofTT.deltaNbBits>>16 + mlTT.deltaNbBits>>16) - // Subtract savings compared to literal encoding... - m.est -= (m.length * bitsPerByte) >> 10 - if m.est > 0 { - // Unlikely gain.. - m.length = 0 - m.est = highScore - } -} - -// bestFastEncoder uses 2 tables, one for short matches (5 bytes) and one for long matches. -// The long match table contains the previous entry with the same hash, -// effectively making it a "chain" of length 2. -// When we find a long match we choose between the two values and select the longest. -// When we find a short match, after checking the long, we check if we can find a long at n+1 -// and that it is longer (lazy matching). -type bestFastEncoder struct { - fastBase - table [bestShortTableSize]prevEntry - longTable [bestLongTableSize]prevEntry - dictTable []prevEntry - dictLongTable []prevEntry -} - -// Encode improves compression... -func (e *bestFastEncoder) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 4 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - e.table = [bestShortTableSize]prevEntry{} - e.longTable = [bestLongTableSize]prevEntry{} - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - v2 := e.table[i].prev - if v < minOff { - v = 0 - v2 = 0 - } else { - v = v - e.cur + e.maxMatchOff - if v2 < minOff { - v2 = 0 - } else { - v2 = v2 - e.cur + e.maxMatchOff - } - } - e.table[i] = prevEntry{ - offset: v, - prev: v2, - } - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - v2 := e.longTable[i].prev - if v < minOff { - v = 0 - v2 = 0 - } else { - v = v - e.cur + e.maxMatchOff - if v2 < minOff { - v2 = 0 - } else { - v2 = v2 - e.cur + e.maxMatchOff - } - } - e.longTable[i] = prevEntry{ - offset: v, - prev: v2, - } - } - e.cur = e.maxMatchOff - break - } - - // Add block to history - s := e.addBlock(src) - blk.size = len(src) - - // Check RLE first - if len(src) > zstdMinMatch { - ml := matchLen(src[1:], src) - if ml == len(src)-1 { - blk.literals = append(blk.literals, src[0]) - blk.sequences = append(blk.sequences, seq{litLen: 1, matchLen: uint32(len(src)-1) - zstdMinMatch, offset: 1 + 3}) - return - } - } - - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Use this to estimate literal cost. - // Scaled by 10 bits. - bitsPerByte := int32((compress.ShannonEntropyBits(src) * 1024) / len(src)) - // Huffman can never go < 1 bit/byte - if bitsPerByte < 1024 { - bitsPerByte = 1024 - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - const kSearchStrength = 10 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - offset3 := int32(blk.recentOffsets[2]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - const goodEnough = 250 - - cv := load6432(src, s) - - nextHashL := hashLen(cv, bestLongTableBits, bestLongLen) - nextHashS := hashLen(cv, bestShortTableBits, bestShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - // Set m to a match at offset if it looks like that will improve compression. - improve := func(m *match, offset int32, s int32, first uint32, rep int32) { - delta := s - offset - if delta >= e.maxMatchOff || delta <= 0 || load3232(src, offset) != first { - return - } - // Try to quick reject if we already have a long match. - if m.length > 16 { - left := len(src) - int(m.s+m.length) - // If we are too close to the end, keep as is. - if left <= 0 { - return - } - checkLen := m.length - (s - m.s) - 8 - if left > 2 && checkLen > 4 { - // Check 4 bytes, 4 bytes from the end of the current match. - a := load3232(src, offset+checkLen) - b := load3232(src, s+checkLen) - if a != b { - return - } - } - } - l := 4 + e.matchlen(s+4, offset+4, src) - if m.rep <= 0 { - // Extend candidate match backwards as far as possible. - // Do not extend repeats as we can assume they are optimal - // and offsets change if s == nextEmit. - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for offset > tMin && s > nextEmit && src[offset-1] == src[s-1] && l < maxMatchLength { - s-- - offset-- - l++ - } - } - if debugAsserts { - if offset >= s { - panic(fmt.Sprintf("offset: %d - s:%d - rep: %d - cur :%d - max: %d", offset, s, rep, e.cur, e.maxMatchOff)) - } - if !bytes.Equal(src[s:s+l], src[offset:offset+l]) { - panic(fmt.Sprintf("second match mismatch: %v != %v, first: %08x", src[s:s+4], src[offset:offset+4], first)) - } - } - cand := match{offset: offset, s: s, length: l, rep: rep} - cand.estBits(bitsPerByte) - if m.est >= highScore || cand.est-m.est+(cand.s-m.s)*bitsPerByte>>10 < 0 { - *m = cand - } - } - - best := match{s: s, est: highScore} - improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1) - improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1) - improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1) - improve(&best, candidateS.prev-e.cur, s, uint32(cv), -1) - - if canRepeat && best.length < goodEnough { - if s == nextEmit { - // Check repeats straight after a match. - improve(&best, s-offset2, s, uint32(cv), 1|4) - improve(&best, s-offset3, s, uint32(cv), 2|4) - if offset1 > 1 { - improve(&best, s-(offset1-1), s, uint32(cv), 3|4) - } - } - - // If either no match or a non-repeat match, check at + 1 - if best.rep <= 0 { - cv32 := uint32(cv >> 8) - spp := s + 1 - improve(&best, spp-offset1, spp, cv32, 1) - improve(&best, spp-offset2, spp, cv32, 2) - improve(&best, spp-offset3, spp, cv32, 3) - if best.rep < 0 { - cv32 = uint32(cv >> 24) - spp += 2 - improve(&best, spp-offset1, spp, cv32, 1) - improve(&best, spp-offset2, spp, cv32, 2) - improve(&best, spp-offset3, spp, cv32, 3) - } - } - } - // Load next and check... - e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: candidateL.offset} - e.table[nextHashS] = prevEntry{offset: s + e.cur, prev: candidateS.offset} - index0 := s + 1 - - // Look far ahead, unless we have a really long match already... - if best.length < goodEnough { - // No match found, move forward on input, no need to check forward... - if best.length < 4 { - s += 1 + (s-nextEmit)>>(kSearchStrength-1) - if s >= sLimit { - break encodeLoop - } - continue - } - - candidateS = e.table[hashLen(cv>>8, bestShortTableBits, bestShortLen)] - cv = load6432(src, s+1) - cv2 := load6432(src, s+2) - candidateL = e.longTable[hashLen(cv, bestLongTableBits, bestLongLen)] - candidateL2 := e.longTable[hashLen(cv2, bestLongTableBits, bestLongLen)] - - // Short at s+1 - improve(&best, candidateS.offset-e.cur, s+1, uint32(cv), -1) - // Long at s+1, s+2 - improve(&best, candidateL.offset-e.cur, s+1, uint32(cv), -1) - improve(&best, candidateL.prev-e.cur, s+1, uint32(cv), -1) - improve(&best, candidateL2.offset-e.cur, s+2, uint32(cv2), -1) - improve(&best, candidateL2.prev-e.cur, s+2, uint32(cv2), -1) - if false { - // Short at s+3. - // Too often worse... - improve(&best, e.table[hashLen(cv2>>8, bestShortTableBits, bestShortLen)].offset-e.cur, s+3, uint32(cv2>>8), -1) - } - - // Start check at a fixed offset to allow for a few mismatches. - // For this compression level 2 yields the best results. - // We cannot do this if we have already indexed this position. - const skipBeginning = 2 - if best.s > s-skipBeginning { - // See if we can find a better match by checking where the current best ends. - // Use that offset to see if we can find a better full match. - if sAt := best.s + best.length; sAt < sLimit { - nextHashL := hashLen(load6432(src, sAt), bestLongTableBits, bestLongLen) - candidateEnd := e.longTable[nextHashL] - - if off := candidateEnd.offset - e.cur - best.length + skipBeginning; off >= 0 { - improve(&best, off, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) - if off := candidateEnd.prev - e.cur - best.length + skipBeginning; off >= 0 { - improve(&best, off, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) - } - } - } - } - } - - if debugAsserts { - if best.offset >= best.s { - panic(fmt.Sprintf("best.offset > s: %d >= %d", best.offset, best.s)) - } - if best.s < nextEmit { - panic(fmt.Sprintf("s %d < nextEmit %d", best.s, nextEmit)) - } - if best.offset < s-e.maxMatchOff { - panic(fmt.Sprintf("best.offset < s-e.maxMatchOff: %d < %d", best.offset, s-e.maxMatchOff)) - } - if !bytes.Equal(src[best.s:best.s+best.length], src[best.offset:best.offset+best.length]) { - panic(fmt.Sprintf("match mismatch: %v != %v", src[best.s:best.s+best.length], src[best.offset:best.offset+best.length])) - } - } - - // We have a match, we can store the forward value - s = best.s - if best.rep > 0 { - var seq seq - seq.matchLen = uint32(best.length - zstdMinMatch) - addLiterals(&seq, best.s) - - // Repeat. If bit 4 is set, this is a non-lit repeat. - seq.offset = uint32(best.rep & 3) - if debugSequences { - println("repeat sequence", seq, "next s:", best.s, "off:", best.s-best.offset) - } - blk.sequences = append(blk.sequences, seq) - - // Index old s + 1 -> s - 1 - s = best.s + best.length - nextEmit = s - - // Index skipped... - end := s - if s > sLimit+4 { - end = sLimit + 4 - } - off := index0 + e.cur - for index0 < end { - cv0 := load6432(src, index0) - h0 := hashLen(cv0, bestLongTableBits, bestLongLen) - h1 := hashLen(cv0, bestShortTableBits, bestShortLen) - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[h1] = prevEntry{offset: off, prev: e.table[h1].offset} - off++ - index0++ - } - - switch best.rep { - case 2, 4 | 1: - offset1, offset2 = offset2, offset1 - case 3, 4 | 2: - offset1, offset2, offset3 = offset3, offset1, offset2 - case 4 | 3: - offset1, offset2, offset3 = offset1-1, offset1, offset2 - } - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, best.length) - } - break encodeLoop - } - continue - } - - // A 4-byte match has been found. Update recent offsets. - // We'll later see if more than 4 bytes. - t := best.offset - offset1, offset2, offset3 = s-t, offset1, offset2 - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && int(offset1) > len(src) { - panic("invalid offset") - } - - // Write our sequence - var seq seq - l := best.length - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - - // Index old s + 1 -> s - 1 or sLimit - end := s - if s > sLimit-4 { - end = sLimit - 4 - } - - off := index0 + e.cur - for index0 < end { - cv0 := load6432(src, index0) - h0 := hashLen(cv0, bestLongTableBits, bestLongLen) - h1 := hashLen(cv0, bestShortTableBits, bestShortLen) - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[h1] = prevEntry{offset: off, prev: e.table[h1].offset} - index0++ - off++ - } - if s >= sLimit { - break encodeLoop - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - blk.recentOffsets[2] = uint32(offset3) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// EncodeNoHist will encode a block with no history and no following blocks. -// Most notable difference is that src will not be copied for history and -// we do not need to check for max match length. -func (e *bestFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { - e.ensureHist(len(src)) - e.Encode(blk, src) -} - -// Reset will reset and set a dictionary if not nil -func (e *bestFastEncoder) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d == nil { - return - } - // Init or copy dict table - if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { - if len(e.dictTable) != len(e.table) { - e.dictTable = make([]prevEntry, len(e.table)) - } - end := int32(len(d.content)) - 8 + e.maxMatchOff - for i := e.maxMatchOff; i < end; i += 4 { - const hashLog = bestShortTableBits - - cv := load6432(d.content, i-e.maxMatchOff) - nextHash := hashLen(cv, hashLog, bestShortLen) // 0 -> 4 - nextHash1 := hashLen(cv>>8, hashLog, bestShortLen) // 1 -> 5 - nextHash2 := hashLen(cv>>16, hashLog, bestShortLen) // 2 -> 6 - nextHash3 := hashLen(cv>>24, hashLog, bestShortLen) // 3 -> 7 - e.dictTable[nextHash] = prevEntry{ - prev: e.dictTable[nextHash].offset, - offset: i, - } - e.dictTable[nextHash1] = prevEntry{ - prev: e.dictTable[nextHash1].offset, - offset: i + 1, - } - e.dictTable[nextHash2] = prevEntry{ - prev: e.dictTable[nextHash2].offset, - offset: i + 2, - } - e.dictTable[nextHash3] = prevEntry{ - prev: e.dictTable[nextHash3].offset, - offset: i + 3, - } - } - e.lastDictID = d.id - } - - // Init or copy dict table - if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { - if len(e.dictLongTable) != len(e.longTable) { - e.dictLongTable = make([]prevEntry, len(e.longTable)) - } - if len(d.content) >= 8 { - cv := load6432(d.content, 0) - h := hashLen(cv, bestLongTableBits, bestLongLen) - e.dictLongTable[h] = prevEntry{ - offset: e.maxMatchOff, - prev: e.dictLongTable[h].offset, - } - - end := int32(len(d.content)) - 8 + e.maxMatchOff - off := 8 // First to read - for i := e.maxMatchOff + 1; i < end; i++ { - cv = cv>>8 | (uint64(d.content[off]) << 56) - h := hashLen(cv, bestLongTableBits, bestLongLen) - e.dictLongTable[h] = prevEntry{ - offset: i, - prev: e.dictLongTable[h].offset, - } - off++ - } - } - e.lastDictID = d.id - } - // Reset table to initial state - copy(e.longTable[:], e.dictLongTable) - - e.cur = e.maxMatchOff - // Reset table to initial state - copy(e.table[:], e.dictTable) -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_better.go b/vendor/github.com/klauspost/compress/zstd/enc_better.go deleted file mode 100644 index a4f5bf91f..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_better.go +++ /dev/null @@ -1,1252 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import "fmt" - -const ( - betterLongTableBits = 19 // Bits used in the long match table - betterLongTableSize = 1 << betterLongTableBits // Size of the table - betterLongLen = 8 // Bytes used for table hash - - // Note: Increasing the short table bits or making the hash shorter - // can actually lead to compression degradation since it will 'steal' more from the - // long match table and match offsets are quite big. - // This greatly depends on the type of input. - betterShortTableBits = 13 // Bits used in the short match table - betterShortTableSize = 1 << betterShortTableBits // Size of the table - betterShortLen = 5 // Bytes used for table hash - - betterLongTableShardCnt = 1 << (betterLongTableBits - dictShardBits) // Number of shards in the table - betterLongTableShardSize = betterLongTableSize / betterLongTableShardCnt // Size of an individual shard - - betterShortTableShardCnt = 1 << (betterShortTableBits - dictShardBits) // Number of shards in the table - betterShortTableShardSize = betterShortTableSize / betterShortTableShardCnt // Size of an individual shard -) - -type prevEntry struct { - offset int32 - prev int32 -} - -// betterFastEncoder uses 2 tables, one for short matches (5 bytes) and one for long matches. -// The long match table contains the previous entry with the same hash, -// effectively making it a "chain" of length 2. -// When we find a long match we choose between the two values and select the longest. -// When we find a short match, after checking the long, we check if we can find a long at n+1 -// and that it is longer (lazy matching). -type betterFastEncoder struct { - fastBase - table [betterShortTableSize]tableEntry - longTable [betterLongTableSize]prevEntry -} - -type betterFastEncoderDict struct { - betterFastEncoder - dictTable []tableEntry - dictLongTable []prevEntry - shortTableShardDirty [betterShortTableShardCnt]bool - longTableShardDirty [betterLongTableShardCnt]bool - allDirty bool -} - -// Encode improves compression... -func (e *betterFastEncoder) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - e.table = [betterShortTableSize]tableEntry{} - e.longTable = [betterLongTableSize]prevEntry{} - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - v2 := e.longTable[i].prev - if v < minOff { - v = 0 - v2 = 0 - } else { - v = v - e.cur + e.maxMatchOff - if v2 < minOff { - v2 = 0 - } else { - v2 = v2 - e.cur + e.maxMatchOff - } - } - e.longTable[i] = prevEntry{ - offset: v, - prev: v2, - } - } - e.cur = e.maxMatchOff - break - } - // Add block to history - s := e.addBlock(src) - blk.size = len(src) - - // Check RLE first - if len(src) > zstdMinMatch { - ml := matchLen(src[1:], src) - if ml == len(src)-1 { - blk.literals = append(blk.literals, src[0]) - blk.sequences = append(blk.sequences, seq{litLen: 1, matchLen: uint32(len(src)-1) - zstdMinMatch, offset: 1 + 3}) - return - } - } - - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 9 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - var matched, index0 int32 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - off := s + e.cur - e.longTable[nextHashL] = prevEntry{offset: off, prev: candidateL.offset} - e.table[nextHashS] = tableEntry{offset: off, val: uint32(cv)} - index0 = s + 1 - - if canRepeat { - if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Index match start+1 (long) -> s - 1 - index0 := s + repOff - s += lenght + repOff - - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - // Index skipped... - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 - } - cv = load6432(src, s) - continue - } - const repOff2 = 1 - - // We deviate from the reference encoder and also check offset 2. - // Still slower and not much better, so disabled. - // repIndex = s - offset2 + repOff2 - if false && repIndex >= 0 && load6432(src, repIndex) == load6432(src, s+repOff) { - // Consider history as well. - var seq seq - lenght := 8 + e.matchlen(s+8+repOff2, repIndex+8, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 2 - seq.offset = 2 - if debugSequences { - println("repeat sequence 2", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - s += lenght + repOff2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - - // Index skipped... - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 - } - cv = load6432(src, s) - // Swap offsets - offset1, offset2 = offset2, offset1 - continue - } - } - // Find the offsets of our two matches. - coffsetL := candidateL.offset - e.cur - coffsetLP := candidateL.prev - e.cur - - // Check if we have a long match. - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matched = e.matchlen(s+8, coffsetL+8, src) + 8 - t = coffsetL - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - - if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { - // Found a long match, at least 8 bytes. - prevMatch := e.matchlen(s+8, coffsetLP+8, src) + 8 - if prevMatch > matched { - matched = prevMatch - t = coffsetLP - } - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - } - break - } - - // Check if we have a long match on prev. - if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { - // Found a long match, at least 8 bytes. - matched = e.matchlen(s+8, coffsetLP+8, src) + 8 - t = coffsetLP - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - coffsetS := candidateS.offset - e.cur - - // Check if we have a short match. - if s-coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - matched = e.matchlen(s+4, coffsetS+4, src) + 4 - - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, betterLongTableBits, betterLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = candidateL.offset - e.cur - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = prevEntry{offset: s + checkAt + e.cur, prev: candidateL.offset} - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 - if matchedNext > matched { - t = coffsetL - s += checkAt - matched = matchedNext - if debugMatches { - println("long match (after short)") - } - break - } - } - - // Check prev long... - coffsetL = candidateL.prev - e.cur - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 - if matchedNext > matched { - t = coffsetL - s += checkAt - matched = matchedNext - if debugMatches { - println("prev long match (after short)") - } - break - } - } - t = coffsetS - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - - // Try to find a better match by searching for a long match at the end of the current best match - if s+matched < sLimit { - // Allow some bytes at the beginning to mismatch. - // Sweet spot is around 3 bytes, but depends on input. - // The skipped bytes are tested in Extend backwards, - // and still picked up as part of the match if they do. - const skipBeginning = 3 - - nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen) - s2 := s + skipBeginning - cv := load3232(src, s2) - candidateL := e.longTable[nextHashL] - coffsetL := candidateL.offset - e.cur - matched + skipBeginning - if coffsetL >= 0 && coffsetL < s2 && s2-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { - // Found a long match, at least 4 bytes. - matchedNext := e.matchlen(s2+4, coffsetL+4, src) + 4 - if matchedNext > matched { - t = coffsetL - s = s2 - matched = matchedNext - if debugMatches { - println("long match at end-of-match") - } - } - } - - // Check prev long... - if true { - coffsetL = candidateL.prev - e.cur - matched + skipBeginning - if coffsetL >= 0 && coffsetL < s2 && s2-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { - // Found a long match, at least 4 bytes. - matchedNext := e.matchlen(s2+4, coffsetL+4, src) + 4 - if matchedNext > matched { - t = coffsetL - s = s2 - matched = matchedNext - if debugMatches { - println("prev long match at end-of-match") - } - } - } - } - } - // A match has been found. Update recent offsets. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the n-byte match as long as possible. - l := matched - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) -> s - 1 - off := index0 + e.cur - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)} - index0 += 2 - off += 2 - } - - cv = load6432(src, s) - if !canRepeat { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset} - e.table[nextHashS] = tableEntry{offset: s + e.cur, val: uint32(cv)} - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// EncodeNoHist will encode a block with no history and no following blocks. -// Most notable difference is that src will not be copied for history and -// we do not need to check for max match length. -func (e *betterFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { - e.ensureHist(len(src)) - e.Encode(blk, src) -} - -// Encode improves compression... -func (e *betterFastEncoderDict) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.longTable[:] { - e.longTable[i] = prevEntry{} - } - e.cur = e.maxMatchOff - e.allDirty = true - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - v2 := e.longTable[i].prev - if v < minOff { - v = 0 - v2 = 0 - } else { - v = v - e.cur + e.maxMatchOff - if v2 < minOff { - v2 = 0 - } else { - v2 = v2 - e.cur + e.maxMatchOff - } - } - e.longTable[i] = prevEntry{ - offset: v, - prev: v2, - } - } - e.allDirty = true - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 9 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - var matched, index0 int32 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - off := s + e.cur - e.longTable[nextHashL] = prevEntry{offset: off, prev: candidateL.offset} - e.markLongShardDirty(nextHashL) - e.table[nextHashS] = tableEntry{offset: off, val: uint32(cv)} - e.markShortShardDirty(nextHashS) - index0 = s + 1 - - if canRepeat { - if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Index match start+1 (long) -> s - 1 - s += lenght + repOff - - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - // Index skipped... - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) - e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} - e.markShortShardDirty(h1) - index0 += 2 - } - cv = load6432(src, s) - continue - } - const repOff2 = 1 - - // We deviate from the reference encoder and also check offset 2. - // Still slower and not much better, so disabled. - // repIndex = s - offset2 + repOff2 - if false && repIndex >= 0 && load6432(src, repIndex) == load6432(src, s+repOff) { - // Consider history as well. - var seq seq - lenght := 8 + e.matchlen(s+8+repOff2, repIndex+8, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 2 - seq.offset = 2 - if debugSequences { - println("repeat sequence 2", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - s += lenght + repOff2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - - // Index skipped... - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - off := index0 + e.cur - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) - e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} - e.markShortShardDirty(h1) - index0 += 2 - } - cv = load6432(src, s) - // Swap offsets - offset1, offset2 = offset2, offset1 - continue - } - } - // Find the offsets of our two matches. - coffsetL := candidateL.offset - e.cur - coffsetLP := candidateL.prev - e.cur - - // Check if we have a long match. - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matched = e.matchlen(s+8, coffsetL+8, src) + 8 - t = coffsetL - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - - if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { - // Found a long match, at least 8 bytes. - prevMatch := e.matchlen(s+8, coffsetLP+8, src) + 8 - if prevMatch > matched { - matched = prevMatch - t = coffsetLP - } - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - } - break - } - - // Check if we have a long match on prev. - if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) { - // Found a long match, at least 8 bytes. - matched = e.matchlen(s+8, coffsetLP+8, src) + 8 - t = coffsetLP - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - coffsetS := candidateS.offset - e.cur - - // Check if we have a short match. - if s-coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - matched = e.matchlen(s+4, coffsetS+4, src) + 4 - - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, betterLongTableBits, betterLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = candidateL.offset - e.cur - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = prevEntry{offset: s + checkAt + e.cur, prev: candidateL.offset} - e.markLongShardDirty(nextHashL) - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 - if matchedNext > matched { - t = coffsetL - s += checkAt - matched = matchedNext - if debugMatches { - println("long match (after short)") - } - break - } - } - - // Check prev long... - coffsetL = candidateL.prev - e.cur - if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) { - // Found a long match, at least 8 bytes. - matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8 - if matchedNext > matched { - t = coffsetL - s += checkAt - matched = matchedNext - if debugMatches { - println("prev long match (after short)") - } - break - } - } - t = coffsetS - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - // Try to find a better match by searching for a long match at the end of the current best match - if s+matched < sLimit { - nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen) - cv := load3232(src, s) - candidateL := e.longTable[nextHashL] - coffsetL := candidateL.offset - e.cur - matched - if coffsetL >= 0 && coffsetL < s && s-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { - // Found a long match, at least 4 bytes. - matchedNext := e.matchlen(s+4, coffsetL+4, src) + 4 - if matchedNext > matched { - t = coffsetL - matched = matchedNext - if debugMatches { - println("long match at end-of-match") - } - } - } - - // Check prev long... - if true { - coffsetL = candidateL.prev - e.cur - matched - if coffsetL >= 0 && coffsetL < s && s-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) { - // Found a long match, at least 4 bytes. - matchedNext := e.matchlen(s+4, coffsetL+4, src) + 4 - if matchedNext > matched { - t = coffsetL - matched = matchedNext - if debugMatches { - println("prev long match at end-of-match") - } - } - } - } - } - // A match has been found. Update recent offsets. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the n-byte match as long as possible. - l := matched - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) -> s - 1 - off := index0 + e.cur - for index0 < s-1 { - cv0 := load6432(src, index0) - cv1 := cv0 >> 8 - h0 := hashLen(cv0, betterLongTableBits, betterLongLen) - e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset} - e.markLongShardDirty(h0) - h1 := hashLen(cv1, betterShortTableBits, betterShortLen) - e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)} - e.markShortShardDirty(h1) - index0 += 2 - off += 2 - } - - cv = load6432(src, s) - if !canRepeat { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashL := hashLen(cv, betterLongTableBits, betterLongLen) - nextHashS := hashLen(cv, betterShortTableBits, betterShortLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset} - e.markLongShardDirty(nextHashL) - e.table[nextHashS] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.markShortShardDirty(nextHashS) - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *betterFastEncoder) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d != nil { - panic("betterFastEncoder: Reset with dict") - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d == nil { - return - } - // Init or copy dict table - if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { - if len(e.dictTable) != len(e.table) { - e.dictTable = make([]tableEntry, len(e.table)) - } - end := int32(len(d.content)) - 8 + e.maxMatchOff - for i := e.maxMatchOff; i < end; i += 4 { - const hashLog = betterShortTableBits - - cv := load6432(d.content, i-e.maxMatchOff) - nextHash := hashLen(cv, hashLog, betterShortLen) // 0 -> 4 - nextHash1 := hashLen(cv>>8, hashLog, betterShortLen) // 1 -> 5 - nextHash2 := hashLen(cv>>16, hashLog, betterShortLen) // 2 -> 6 - nextHash3 := hashLen(cv>>24, hashLog, betterShortLen) // 3 -> 7 - e.dictTable[nextHash] = tableEntry{ - val: uint32(cv), - offset: i, - } - e.dictTable[nextHash1] = tableEntry{ - val: uint32(cv >> 8), - offset: i + 1, - } - e.dictTable[nextHash2] = tableEntry{ - val: uint32(cv >> 16), - offset: i + 2, - } - e.dictTable[nextHash3] = tableEntry{ - val: uint32(cv >> 24), - offset: i + 3, - } - } - e.lastDictID = d.id - e.allDirty = true - } - - // Init or copy dict table - if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { - if len(e.dictLongTable) != len(e.longTable) { - e.dictLongTable = make([]prevEntry, len(e.longTable)) - } - if len(d.content) >= 8 { - cv := load6432(d.content, 0) - h := hashLen(cv, betterLongTableBits, betterLongLen) - e.dictLongTable[h] = prevEntry{ - offset: e.maxMatchOff, - prev: e.dictLongTable[h].offset, - } - - end := int32(len(d.content)) - 8 + e.maxMatchOff - off := 8 // First to read - for i := e.maxMatchOff + 1; i < end; i++ { - cv = cv>>8 | (uint64(d.content[off]) << 56) - h := hashLen(cv, betterLongTableBits, betterLongLen) - e.dictLongTable[h] = prevEntry{ - offset: i, - prev: e.dictLongTable[h].offset, - } - off++ - } - } - e.lastDictID = d.id - e.allDirty = true - } - - // Reset table to initial state - { - dirtyShardCnt := 0 - if !e.allDirty { - for i := range e.shortTableShardDirty { - if e.shortTableShardDirty[i] { - dirtyShardCnt++ - } - } - } - const shardCnt = betterShortTableShardCnt - const shardSize = betterShortTableShardSize - if e.allDirty || dirtyShardCnt > shardCnt*4/6 { - copy(e.table[:], e.dictTable) - for i := range e.shortTableShardDirty { - e.shortTableShardDirty[i] = false - } - } else { - for i := range e.shortTableShardDirty { - if !e.shortTableShardDirty[i] { - continue - } - - copy(e.table[i*shardSize:(i+1)*shardSize], e.dictTable[i*shardSize:(i+1)*shardSize]) - e.shortTableShardDirty[i] = false - } - } - } - { - dirtyShardCnt := 0 - if !e.allDirty { - for i := range e.shortTableShardDirty { - if e.shortTableShardDirty[i] { - dirtyShardCnt++ - } - } - } - const shardCnt = betterLongTableShardCnt - const shardSize = betterLongTableShardSize - if e.allDirty || dirtyShardCnt > shardCnt*4/6 { - copy(e.longTable[:], e.dictLongTable) - for i := range e.longTableShardDirty { - e.longTableShardDirty[i] = false - } - } else { - for i := range e.longTableShardDirty { - if !e.longTableShardDirty[i] { - continue - } - - copy(e.longTable[i*shardSize:(i+1)*shardSize], e.dictLongTable[i*shardSize:(i+1)*shardSize]) - e.longTableShardDirty[i] = false - } - } - } - e.cur = e.maxMatchOff - e.allDirty = false -} - -func (e *betterFastEncoderDict) markLongShardDirty(entryNum uint32) { - e.longTableShardDirty[entryNum/betterLongTableShardSize] = true -} - -func (e *betterFastEncoderDict) markShortShardDirty(entryNum uint32) { - e.shortTableShardDirty[entryNum/betterShortTableShardSize] = true -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go b/vendor/github.com/klauspost/compress/zstd/enc_dfast.go deleted file mode 100644 index a154c18f7..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go +++ /dev/null @@ -1,1123 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import "fmt" - -const ( - dFastLongTableBits = 17 // Bits used in the long match table - dFastLongTableSize = 1 << dFastLongTableBits // Size of the table - dFastLongTableMask = dFastLongTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. - dFastLongLen = 8 // Bytes used for table hash - - dLongTableShardCnt = 1 << (dFastLongTableBits - dictShardBits) // Number of shards in the table - dLongTableShardSize = dFastLongTableSize / tableShardCnt // Size of an individual shard - - dFastShortTableBits = tableBits // Bits used in the short match table - dFastShortTableSize = 1 << dFastShortTableBits // Size of the table - dFastShortTableMask = dFastShortTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. - dFastShortLen = 5 // Bytes used for table hash - -) - -type doubleFastEncoder struct { - fastEncoder - longTable [dFastLongTableSize]tableEntry -} - -type doubleFastEncoderDict struct { - fastEncoderDict - longTable [dFastLongTableSize]tableEntry - dictLongTable []tableEntry - longTableShardDirty [dLongTableShardCnt]bool -} - -// Encode mimmics functionality in zstd_dfast.c -func (e *doubleFastEncoder) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - e.table = [dFastShortTableSize]tableEntry{} - e.longTable = [dFastLongTableSize]tableEntry{} - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.longTable[i].offset = v - } - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 8 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.table[nextHashS] = entry - - if canRepeat { - if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += lenght + repOff - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - } - // Find the offsets of our two matches. - coffsetL := s - (candidateL.offset - e.cur) - coffsetS := s - (candidateS.offset - e.cur) - - // Check if we have a long match. - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - // Check if we have a short match. - if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = s - (candidateL.offset - e.cur) + checkAt - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - s += checkAt - if debugMatches { - println("long match (after short)") - } - break - } - - t = candidateS.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - - // A 4-byte match has been found. Update recent offsets. - // We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) and start+2 (short) - index0 := s - l + 1 - // Index match end-2 (long) and end-1 (short) - index1 := s - 2 - - cv0 := load6432(src, index0) - cv1 := load6432(src, index1) - te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} - te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0 - e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1 - cv0 >>= 8 - cv1 >>= 8 - te0.offset++ - te1.offset++ - te0.val = uint32(cv0) - te1.val = uint32(cv1) - e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0 - e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1 - - cv = load6432(src, s) - - if !canRepeat { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.table[nextHashS] = entry - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// EncodeNoHist will encode a block with no history and no following blocks. -// Most notable difference is that src will not be copied for history and -// we do not need to check for max match length. -func (e *doubleFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - if e.cur >= e.bufferReset { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.longTable[:] { - e.longTable[i] = tableEntry{} - } - e.cur = e.maxMatchOff - } - - s := int32(0) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 8 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - for { - - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.table[nextHashS] = entry - - if len(blk.sequences) > 2 { - if load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - //length := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - length := 4 + int32(matchLen(src[s+4+repOff:], src[repIndex+4:])) - - seq.matchLen = uint32(length - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += length + repOff - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, length) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - } - // Find the offsets of our two matches. - coffsetL := s - (candidateL.offset - e.cur) - coffsetS := s - (candidateS.offset - e.cur) - - // Check if we have a long match. - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d). cur: %d", s, t, e.cur)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - // Check if we have a short match. - if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = s - (candidateL.offset - e.cur) + checkAt - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - s += checkAt - if debugMatches { - println("long match (after short)") - } - break - } - - t = candidateS.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - - // A 4-byte match has been found. Update recent offsets. - // We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - // Extend the 4-byte match as long as possible. - //l := e.matchlen(s+4, t+4, src) + 4 - l := int32(matchLen(src[s+4:], src[t+4:])) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) and start+2 (short) - index0 := s - l + 1 - // Index match end-2 (long) and end-1 (short) - index1 := s - 2 - - cv0 := load6432(src, index0) - cv1 := load6432(src, index1) - te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} - te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0 - e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1 - cv0 >>= 8 - cv1 >>= 8 - te0.offset++ - te1.offset++ - te0.val = uint32(cv0) - te1.val = uint32(cv1) - e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0 - e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1 - - cv = load6432(src, s) - - if len(blk.sequences) <= 2 { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashS := hashLen(cv1>>8, dFastShortTableBits, dFastShortLen) - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - //l := 4 + e.matchlen(s+4, o2+4, src) - l := 4 + int32(matchLen(src[s+4:], src[o2+4:])) - - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.table[nextHashS] = entry - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } - - // We do not store history, so we must offset e.cur to avoid false matches for next user. - if e.cur < e.bufferReset { - e.cur += int32(len(src)) - } -} - -// Encode will encode the content, with a dictionary if initialized for it. -func (e *doubleFastEncoderDict) Encode(blk *blockEnc, src []byte) { - const ( - // Input margin is the number of bytes we read (8) - // and the maximum we will read ahead (2) - inputMargin = 8 + 2 - minNonLiteralBlockSize = 16 - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - for i := range e.longTable[:] { - e.longTable[i] = tableEntry{} - } - e.markAllShardsDirty() - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - for i := range e.longTable[:] { - v := e.longTable[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.longTable[i].offset = v - } - e.markAllShardsDirty() - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 1. - const stepSize = 1 - - const kSearchStrength = 8 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - var t int32 - // We allow the encoder to optionally turn off repeat offsets across blocks - canRepeat := len(blk.sequences) > 2 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - candidateL := e.longTable[nextHashL] - candidateS := e.table[nextHashS] - - const repOff = 1 - repIndex := s - offset1 + repOff - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.markLongShardDirty(nextHashL) - e.table[nextHashS] = entry - e.markShardDirty(nextHashS) - - if canRepeat { - if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) { - // Consider history as well. - var seq seq - lenght := 4 + e.matchlen(s+4+repOff, repIndex+4, src) - - seq.matchLen = uint32(lenght - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + repOff - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += lenght + repOff - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, lenght) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - } - // Find the offsets of our two matches. - coffsetL := s - (candidateL.offset - e.cur) - coffsetS := s - (candidateS.offset - e.cur) - - // Check if we have a long match. - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugMatches { - println("long match") - } - break - } - - // Check if we have a short match. - if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val { - // found a regular match - // See if we can find a long match at s+1 - const checkAt = 1 - cv := load6432(src, s+checkAt) - nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen) - candidateL = e.longTable[nextHashL] - coffsetL = s - (candidateL.offset - e.cur) + checkAt - - // We can store it, since we have at least a 4 byte match. - e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)} - e.markLongShardDirty(nextHashL) - if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val { - // Found a long match, likely at least 8 bytes. - // Reference encoder checks all 8 bytes, we only check 4, - // but the likelihood of both the first 4 bytes and the hash matching should be enough. - t = candidateL.offset - e.cur - s += checkAt - if debugMatches { - println("long match (after short)") - } - break - } - - t = candidateS.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - if debugMatches { - println("short match") - } - break - } - - // No match found, move forward in input. - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - - // A 4-byte match has been found. Update recent offsets. - // We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - - // Index match start+1 (long) and start+2 (short) - index0 := s - l + 1 - // Index match end-2 (long) and end-1 (short) - index1 := s - 2 - - cv0 := load6432(src, index0) - cv1 := load6432(src, index1) - te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)} - te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)} - longHash1 := hashLen(cv0, dFastLongTableBits, dFastLongLen) - longHash2 := hashLen(cv1, dFastLongTableBits, dFastLongLen) - e.longTable[longHash1] = te0 - e.longTable[longHash2] = te1 - e.markLongShardDirty(longHash1) - e.markLongShardDirty(longHash2) - cv0 >>= 8 - cv1 >>= 8 - te0.offset++ - te1.offset++ - te0.val = uint32(cv0) - te1.val = uint32(cv1) - hashVal1 := hashLen(cv0, dFastShortTableBits, dFastShortLen) - hashVal2 := hashLen(cv1, dFastShortTableBits, dFastShortLen) - e.table[hashVal1] = te0 - e.markShardDirty(hashVal1) - e.table[hashVal2] = te1 - e.markShardDirty(hashVal2) - - cv = load6432(src, s) - - if !canRepeat { - continue - } - - // Check offset 2 - for { - o2 := s - offset2 - if load3232(src, o2) != uint32(cv) { - // Do regular search - break - } - - // Store this, since we have it. - nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen) - nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen) - - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - entry := tableEntry{offset: s + e.cur, val: uint32(cv)} - e.longTable[nextHashL] = entry - e.markLongShardDirty(nextHashL) - e.table[nextHashS] = entry - e.markShardDirty(nextHashS) - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - // Finished - break encodeLoop - } - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } - // If we encoded more than 64K mark all dirty. - if len(src) > 64<<10 { - e.markAllShardsDirty() - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *doubleFastEncoder) Reset(d *dict, singleBlock bool) { - e.fastEncoder.Reset(d, singleBlock) - if d != nil { - panic("doubleFastEncoder: Reset with dict not supported") - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) { - allDirty := e.allDirty - e.fastEncoderDict.Reset(d, singleBlock) - if d == nil { - return - } - - // Init or copy dict table - if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID { - if len(e.dictLongTable) != len(e.longTable) { - e.dictLongTable = make([]tableEntry, len(e.longTable)) - } - if len(d.content) >= 8 { - cv := load6432(d.content, 0) - e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{ - val: uint32(cv), - offset: e.maxMatchOff, - } - end := int32(len(d.content)) - 8 + e.maxMatchOff - for i := e.maxMatchOff + 1; i < end; i++ { - cv = cv>>8 | (uint64(d.content[i-e.maxMatchOff+7]) << 56) - e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{ - val: uint32(cv), - offset: i, - } - } - } - e.lastDictID = d.id - allDirty = true - } - // Reset table to initial state - e.cur = e.maxMatchOff - - dirtyShardCnt := 0 - if !allDirty { - for i := range e.longTableShardDirty { - if e.longTableShardDirty[i] { - dirtyShardCnt++ - } - } - } - - if allDirty || dirtyShardCnt > dLongTableShardCnt/2 { - //copy(e.longTable[:], e.dictLongTable) - e.longTable = *(*[dFastLongTableSize]tableEntry)(e.dictLongTable) - for i := range e.longTableShardDirty { - e.longTableShardDirty[i] = false - } - return - } - for i := range e.longTableShardDirty { - if !e.longTableShardDirty[i] { - continue - } - - // copy(e.longTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize], e.dictLongTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize]) - *(*[dLongTableShardSize]tableEntry)(e.longTable[i*dLongTableShardSize:]) = *(*[dLongTableShardSize]tableEntry)(e.dictLongTable[i*dLongTableShardSize:]) - - e.longTableShardDirty[i] = false - } -} - -func (e *doubleFastEncoderDict) markLongShardDirty(entryNum uint32) { - e.longTableShardDirty[entryNum/dLongTableShardSize] = true -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_fast.go b/vendor/github.com/klauspost/compress/zstd/enc_fast.go deleted file mode 100644 index f45a3da7d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/enc_fast.go +++ /dev/null @@ -1,891 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "fmt" -) - -const ( - tableBits = 15 // Bits used in the table - tableSize = 1 << tableBits // Size of the table - tableShardCnt = 1 << (tableBits - dictShardBits) // Number of shards in the table - tableShardSize = tableSize / tableShardCnt // Size of an individual shard - tableFastHashLen = 6 - tableMask = tableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks. - maxMatchLength = 131074 -) - -type tableEntry struct { - val uint32 - offset int32 -} - -type fastEncoder struct { - fastBase - table [tableSize]tableEntry -} - -type fastEncoderDict struct { - fastEncoder - dictTable []tableEntry - tableShardDirty [tableShardCnt]bool - allDirty bool -} - -// Encode mimmics functionality in zstd_fast.c -func (e *fastEncoder) Encode(blk *blockEnc, src []byte) { - const ( - inputMargin = 8 - minNonLiteralBlockSize = 1 + 1 + inputMargin - ) - - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 2. - const stepSize = 2 - - // TEMPLATE - const hashLog = tableBits - // seems global, but would be nice to tweak. - const kSearchStrength = 6 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - // t will contain the match offset when we find one. - // When existing the search loop, we have already checked 4 bytes. - var t int32 - - // We will not use repeat offsets across blocks. - // By not using them for the first 3 matches - canRepeat := len(blk.sequences) > 2 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHash := hashLen(cv, hashLog, tableFastHashLen) - nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) - candidate := e.table[nextHash] - candidate2 := e.table[nextHash2] - repIndex := s - offset1 + 2 - - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} - - if canRepeat && repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>16) { - // Consider history as well. - var seq seq - length := 4 + e.matchlen(s+6, repIndex+4, src) - seq.matchLen = uint32(length - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + 2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } - for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += length + 2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, length) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - coffset0 := s - (candidate.offset - e.cur) - coffset1 := s - (candidate2.offset - e.cur) + 1 - if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { - // found a regular match - t = candidate.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - break - } - - if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { - // found a regular match - t = candidate2.offset - e.cur - s++ - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - break - } - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - // A 4-byte match has been found. We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence. - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - // Don't use repeat offsets - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - - // Check offset 2 - if o2 := s - offset2; canRepeat && load3232(src, o2) == uint32(cv) { - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - // Store this, since we have it. - nextHash := hashLen(cv, hashLog, tableFastHashLen) - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - break encodeLoop - } - // Prepare next loop. - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// EncodeNoHist will encode a block with no history and no following blocks. -// Most notable difference is that src will not be copied for history and -// we do not need to check for max match length. -func (e *fastEncoder) EncodeNoHist(blk *blockEnc, src []byte) { - const ( - inputMargin = 8 - minNonLiteralBlockSize = 1 + 1 + inputMargin - ) - if debugEncoder { - if len(src) > maxCompressedBlockSize { - panic("src too big") - } - } - - // Protect against e.cur wraparound. - if e.cur >= e.bufferReset { - for i := range e.table[:] { - e.table[i] = tableEntry{} - } - e.cur = e.maxMatchOff - } - - s := int32(0) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 2. - const stepSize = 2 - - // TEMPLATE - const hashLog = tableBits - // seems global, but would be nice to tweak. - const kSearchStrength = 6 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - // t will contain the match offset when we find one. - // When existing the search loop, we have already checked 4 bytes. - var t int32 - - // We will not use repeat offsets across blocks. - // By not using them for the first 3 matches - - for { - nextHash := hashLen(cv, hashLog, tableFastHashLen) - nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) - candidate := e.table[nextHash] - candidate2 := e.table[nextHash2] - repIndex := s - offset1 + 2 - - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} - - if len(blk.sequences) > 2 && load3232(src, repIndex) == uint32(cv>>16) { - // Consider history as well. - var seq seq - length := 4 + e.matchlen(s+6, repIndex+4, src) - - seq.matchLen = uint32(length - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + 2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } - for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += length + 2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, length) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - coffset0 := s - (candidate.offset - e.cur) - coffset1 := s - (candidate2.offset - e.cur) + 1 - if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { - // found a regular match - t = candidate.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic(fmt.Sprintf("t (%d) < 0, candidate.offset: %d, e.cur: %d, coffset0: %d, e.maxMatchOff: %d", t, candidate.offset, e.cur, coffset0, e.maxMatchOff)) - } - break - } - - if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { - // found a regular match - t = candidate2.offset - e.cur - s++ - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - break - } - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - // A 4-byte match has been found. We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && t < 0 { - panic(fmt.Sprintf("t (%d) < 0 ", t)) - } - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] { - s-- - t-- - l++ - } - - // Write our sequence. - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - // Don't use repeat offsets - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - - // Check offset 2 - if o2 := s - offset2; len(blk.sequences) > 2 && load3232(src, o2) == uint32(cv) { - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - // Store this, since we have it. - nextHash := hashLen(cv, hashLog, tableFastHashLen) - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - break encodeLoop - } - // Prepare next loop. - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } - // We do not store history, so we must offset e.cur to avoid false matches for next user. - if e.cur < e.bufferReset { - e.cur += int32(len(src)) - } -} - -// Encode will encode the content, with a dictionary if initialized for it. -func (e *fastEncoderDict) Encode(blk *blockEnc, src []byte) { - const ( - inputMargin = 8 - minNonLiteralBlockSize = 1 + 1 + inputMargin - ) - if e.allDirty || len(src) > 32<<10 { - e.fastEncoder.Encode(blk, src) - e.allDirty = true - return - } - // Protect against e.cur wraparound. - for e.cur >= e.bufferReset-int32(len(e.hist)) { - if len(e.hist) == 0 { - e.table = [tableSize]tableEntry{} - e.cur = e.maxMatchOff - break - } - // Shift down everything in the table that isn't already too far away. - minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff - for i := range e.table[:] { - v := e.table[i].offset - if v < minOff { - v = 0 - } else { - v = v - e.cur + e.maxMatchOff - } - e.table[i].offset = v - } - e.cur = e.maxMatchOff - break - } - - s := e.addBlock(src) - blk.size = len(src) - if len(src) < minNonLiteralBlockSize { - blk.extraLits = len(src) - blk.literals = blk.literals[:len(src)] - copy(blk.literals, src) - return - } - - // Override src - src = e.hist - sLimit := int32(len(src)) - inputMargin - // stepSize is the number of bytes to skip on every main loop iteration. - // It should be >= 2. - const stepSize = 2 - - // TEMPLATE - const hashLog = tableBits - // seems global, but would be nice to tweak. - const kSearchStrength = 7 - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := s - cv := load6432(src, s) - - // Relative offsets - offset1 := int32(blk.recentOffsets[0]) - offset2 := int32(blk.recentOffsets[1]) - - addLiterals := func(s *seq, until int32) { - if until == nextEmit { - return - } - blk.literals = append(blk.literals, src[nextEmit:until]...) - s.litLen = uint32(until - nextEmit) - } - if debugEncoder { - println("recent offsets:", blk.recentOffsets) - } - -encodeLoop: - for { - // t will contain the match offset when we find one. - // When existing the search loop, we have already checked 4 bytes. - var t int32 - - // We will not use repeat offsets across blocks. - // By not using them for the first 3 matches - canRepeat := len(blk.sequences) > 2 - - for { - if debugAsserts && canRepeat && offset1 == 0 { - panic("offset0 was 0") - } - - nextHash := hashLen(cv, hashLog, tableFastHashLen) - nextHash2 := hashLen(cv>>8, hashLog, tableFastHashLen) - candidate := e.table[nextHash] - candidate2 := e.table[nextHash2] - repIndex := s - offset1 + 2 - - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.markShardDirty(nextHash) - e.table[nextHash2] = tableEntry{offset: s + e.cur + 1, val: uint32(cv >> 8)} - e.markShardDirty(nextHash2) - - if canRepeat && repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>16) { - // Consider history as well. - var seq seq - length := 4 + e.matchlen(s+6, repIndex+4, src) - - seq.matchLen = uint32(length - zstdMinMatch) - - // We might be able to match backwards. - // Extend as long as we can. - start := s + 2 - // We end the search early, so we don't risk 0 literals - // and have to do special offset treatment. - startLimit := nextEmit + 1 - - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } - for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { - repIndex-- - start-- - seq.matchLen++ - } - addLiterals(&seq, start) - - // rep 0 - seq.offset = 1 - if debugSequences { - println("repeat sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - s += length + 2 - nextEmit = s - if s >= sLimit { - if debugEncoder { - println("repeat ended", s, length) - - } - break encodeLoop - } - cv = load6432(src, s) - continue - } - coffset0 := s - (candidate.offset - e.cur) - coffset1 := s - (candidate2.offset - e.cur) + 1 - if coffset0 < e.maxMatchOff && uint32(cv) == candidate.val { - // found a regular match - t = candidate.offset - e.cur - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - break - } - - if coffset1 < e.maxMatchOff && uint32(cv>>8) == candidate2.val { - // found a regular match - t = candidate2.offset - e.cur - s++ - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - if debugAsserts && s-t > e.maxMatchOff { - panic("s - t >e.maxMatchOff") - } - if debugAsserts && t < 0 { - panic("t<0") - } - break - } - s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1)) - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - } - // A 4-byte match has been found. We'll later see if more than 4 bytes. - offset2 = offset1 - offset1 = s - t - - if debugAsserts && s <= t { - panic(fmt.Sprintf("s (%d) <= t (%d)", s, t)) - } - - if debugAsserts && canRepeat && int(offset1) > len(src) { - panic("invalid offset") - } - - // Extend the 4-byte match as long as possible. - l := e.matchlen(s+4, t+4, src) + 4 - - // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } - for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { - s-- - t-- - l++ - } - - // Write our sequence. - var seq seq - seq.litLen = uint32(s - nextEmit) - seq.matchLen = uint32(l - zstdMinMatch) - if seq.litLen > 0 { - blk.literals = append(blk.literals, src[nextEmit:s]...) - } - // Don't use repeat offsets - seq.offset = uint32(s-t) + 3 - s += l - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - nextEmit = s - if s >= sLimit { - break encodeLoop - } - cv = load6432(src, s) - - // Check offset 2 - if o2 := s - offset2; canRepeat && load3232(src, o2) == uint32(cv) { - // We have at least 4 byte match. - // No need to check backwards. We come straight from a match - l := 4 + e.matchlen(s+4, o2+4, src) - - // Store this, since we have it. - nextHash := hashLen(cv, hashLog, tableFastHashLen) - e.table[nextHash] = tableEntry{offset: s + e.cur, val: uint32(cv)} - e.markShardDirty(nextHash) - seq.matchLen = uint32(l) - zstdMinMatch - seq.litLen = 0 - // Since litlen is always 0, this is offset 1. - seq.offset = 1 - s += l - nextEmit = s - if debugSequences { - println("sequence", seq, "next s:", s) - } - blk.sequences = append(blk.sequences, seq) - - // Swap offset 1 and 2. - offset1, offset2 = offset2, offset1 - if s >= sLimit { - break encodeLoop - } - // Prepare next loop. - cv = load6432(src, s) - } - } - - if int(nextEmit) < len(src) { - blk.literals = append(blk.literals, src[nextEmit:]...) - blk.extraLits = len(src) - int(nextEmit) - } - blk.recentOffsets[0] = uint32(offset1) - blk.recentOffsets[1] = uint32(offset2) - if debugEncoder { - println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits) - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *fastEncoder) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d != nil { - panic("fastEncoder: Reset with dict") - } -} - -// ResetDict will reset and set a dictionary if not nil -func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) { - e.resetBase(d, singleBlock) - if d == nil { - return - } - - // Init or copy dict table - if len(e.dictTable) != len(e.table) || d.id != e.lastDictID { - if len(e.dictTable) != len(e.table) { - e.dictTable = make([]tableEntry, len(e.table)) - } - if true { - end := e.maxMatchOff + int32(len(d.content)) - 8 - for i := e.maxMatchOff; i < end; i += 2 { - const hashLog = tableBits - - cv := load6432(d.content, i-e.maxMatchOff) - nextHash := hashLen(cv, hashLog, tableFastHashLen) // 0 -> 6 - nextHash1 := hashLen(cv>>8, hashLog, tableFastHashLen) // 1 -> 7 - e.dictTable[nextHash] = tableEntry{ - val: uint32(cv), - offset: i, - } - e.dictTable[nextHash1] = tableEntry{ - val: uint32(cv >> 8), - offset: i + 1, - } - } - } - e.lastDictID = d.id - e.allDirty = true - } - - e.cur = e.maxMatchOff - dirtyShardCnt := 0 - if !e.allDirty { - for i := range e.tableShardDirty { - if e.tableShardDirty[i] { - dirtyShardCnt++ - } - } - } - - const shardCnt = tableShardCnt - const shardSize = tableShardSize - if e.allDirty || dirtyShardCnt > shardCnt*4/6 { - //copy(e.table[:], e.dictTable) - e.table = *(*[tableSize]tableEntry)(e.dictTable) - for i := range e.tableShardDirty { - e.tableShardDirty[i] = false - } - e.allDirty = false - return - } - for i := range e.tableShardDirty { - if !e.tableShardDirty[i] { - continue - } - - //copy(e.table[i*shardSize:(i+1)*shardSize], e.dictTable[i*shardSize:(i+1)*shardSize]) - *(*[shardSize]tableEntry)(e.table[i*shardSize:]) = *(*[shardSize]tableEntry)(e.dictTable[i*shardSize:]) - e.tableShardDirty[i] = false - } - e.allDirty = false -} - -func (e *fastEncoderDict) markAllShardsDirty() { - e.allDirty = true -} - -func (e *fastEncoderDict) markShardDirty(entryNum uint32) { - e.tableShardDirty[entryNum/tableShardSize] = true -} diff --git a/vendor/github.com/klauspost/compress/zstd/encoder.go b/vendor/github.com/klauspost/compress/zstd/encoder.go deleted file mode 100644 index 72af7ef0f..000000000 --- a/vendor/github.com/klauspost/compress/zstd/encoder.go +++ /dev/null @@ -1,619 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "crypto/rand" - "fmt" - "io" - "math" - rdebug "runtime/debug" - "sync" - - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -// Encoder provides encoding to Zstandard. -// An Encoder can be used for either compressing a stream via the -// io.WriteCloser interface supported by the Encoder or as multiple independent -// tasks via the EncodeAll function. -// Smaller encodes are encouraged to use the EncodeAll function. -// Use NewWriter to create a new instance. -type Encoder struct { - o encoderOptions - encoders chan encoder - state encoderState - init sync.Once -} - -type encoder interface { - Encode(blk *blockEnc, src []byte) - EncodeNoHist(blk *blockEnc, src []byte) - Block() *blockEnc - CRC() *xxhash.Digest - AppendCRC([]byte) []byte - WindowSize(size int64) int32 - UseBlock(*blockEnc) - Reset(d *dict, singleBlock bool) -} - -type encoderState struct { - w io.Writer - filling []byte - current []byte - previous []byte - encoder encoder - writing *blockEnc - err error - writeErr error - nWritten int64 - nInput int64 - frameContentSize int64 - headerWritten bool - eofWritten bool - fullFrameWritten bool - - // This waitgroup indicates an encode is running. - wg sync.WaitGroup - // This waitgroup indicates we have a block encoding/writing. - wWg sync.WaitGroup -} - -// NewWriter will create a new Zstandard encoder. -// If the encoder will be used for encoding blocks a nil writer can be used. -func NewWriter(w io.Writer, opts ...EOption) (*Encoder, error) { - initPredefined() - var e Encoder - e.o.setDefault() - for _, o := range opts { - err := o(&e.o) - if err != nil { - return nil, err - } - } - if w != nil { - e.Reset(w) - } - return &e, nil -} - -func (e *Encoder) initialize() { - if e.o.concurrent == 0 { - e.o.setDefault() - } - e.encoders = make(chan encoder, e.o.concurrent) - for i := 0; i < e.o.concurrent; i++ { - enc := e.o.encoder() - e.encoders <- enc - } -} - -// Reset will re-initialize the writer and new writes will encode to the supplied writer -// as a new, independent stream. -func (e *Encoder) Reset(w io.Writer) { - s := &e.state - s.wg.Wait() - s.wWg.Wait() - if cap(s.filling) == 0 { - s.filling = make([]byte, 0, e.o.blockSize) - } - if e.o.concurrent > 1 { - if cap(s.current) == 0 { - s.current = make([]byte, 0, e.o.blockSize) - } - if cap(s.previous) == 0 { - s.previous = make([]byte, 0, e.o.blockSize) - } - s.current = s.current[:0] - s.previous = s.previous[:0] - if s.writing == nil { - s.writing = &blockEnc{lowMem: e.o.lowMem} - s.writing.init() - } - s.writing.initNewEncode() - } - if s.encoder == nil { - s.encoder = e.o.encoder() - } - s.filling = s.filling[:0] - s.encoder.Reset(e.o.dict, false) - s.headerWritten = false - s.eofWritten = false - s.fullFrameWritten = false - s.w = w - s.err = nil - s.nWritten = 0 - s.nInput = 0 - s.writeErr = nil - s.frameContentSize = 0 -} - -// ResetContentSize will reset and set a content size for the next stream. -// If the bytes written does not match the size given an error will be returned -// when calling Close(). -// This is removed when Reset is called. -// Sizes <= 0 results in no content size set. -func (e *Encoder) ResetContentSize(w io.Writer, size int64) { - e.Reset(w) - if size >= 0 { - e.state.frameContentSize = size - } -} - -// Write data to the encoder. -// Input data will be buffered and as the buffer fills up -// content will be compressed and written to the output. -// When done writing, use Close to flush the remaining output -// and write CRC if requested. -func (e *Encoder) Write(p []byte) (n int, err error) { - s := &e.state - for len(p) > 0 { - if len(p)+len(s.filling) < e.o.blockSize { - if e.o.crc { - _, _ = s.encoder.CRC().Write(p) - } - s.filling = append(s.filling, p...) - return n + len(p), nil - } - add := p - if len(p)+len(s.filling) > e.o.blockSize { - add = add[:e.o.blockSize-len(s.filling)] - } - if e.o.crc { - _, _ = s.encoder.CRC().Write(add) - } - s.filling = append(s.filling, add...) - p = p[len(add):] - n += len(add) - if len(s.filling) < e.o.blockSize { - return n, nil - } - err := e.nextBlock(false) - if err != nil { - return n, err - } - if debugAsserts && len(s.filling) > 0 { - panic(len(s.filling)) - } - } - return n, nil -} - -// nextBlock will synchronize and start compressing input in e.state.filling. -// If an error has occurred during encoding it will be returned. -func (e *Encoder) nextBlock(final bool) error { - s := &e.state - // Wait for current block. - s.wg.Wait() - if s.err != nil { - return s.err - } - if len(s.filling) > e.o.blockSize { - return fmt.Errorf("block > maxStoreBlockSize") - } - if !s.headerWritten { - // If we have a single block encode, do a sync compression. - if final && len(s.filling) == 0 && !e.o.fullZero { - s.headerWritten = true - s.fullFrameWritten = true - s.eofWritten = true - return nil - } - if final && len(s.filling) > 0 { - s.current = e.EncodeAll(s.filling, s.current[:0]) - var n2 int - n2, s.err = s.w.Write(s.current) - if s.err != nil { - return s.err - } - s.nWritten += int64(n2) - s.nInput += int64(len(s.filling)) - s.current = s.current[:0] - s.filling = s.filling[:0] - s.headerWritten = true - s.fullFrameWritten = true - s.eofWritten = true - return nil - } - - var tmp [maxHeaderSize]byte - fh := frameHeader{ - ContentSize: uint64(s.frameContentSize), - WindowSize: uint32(s.encoder.WindowSize(s.frameContentSize)), - SingleSegment: false, - Checksum: e.o.crc, - DictID: e.o.dict.ID(), - } - - dst := fh.appendTo(tmp[:0]) - s.headerWritten = true - s.wWg.Wait() - var n2 int - n2, s.err = s.w.Write(dst) - if s.err != nil { - return s.err - } - s.nWritten += int64(n2) - } - if s.eofWritten { - // Ensure we only write it once. - final = false - } - - if len(s.filling) == 0 { - // Final block, but no data. - if final { - enc := s.encoder - blk := enc.Block() - blk.reset(nil) - blk.last = true - blk.encodeRaw(nil) - s.wWg.Wait() - _, s.err = s.w.Write(blk.output) - s.nWritten += int64(len(blk.output)) - s.eofWritten = true - } - return s.err - } - - // SYNC: - if e.o.concurrent == 1 { - src := s.filling - s.nInput += int64(len(s.filling)) - if debugEncoder { - println("Adding sync block,", len(src), "bytes, final:", final) - } - enc := s.encoder - blk := enc.Block() - blk.reset(nil) - enc.Encode(blk, src) - blk.last = final - if final { - s.eofWritten = true - } - - s.err = blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) - if s.err != nil { - return s.err - } - _, s.err = s.w.Write(blk.output) - s.nWritten += int64(len(blk.output)) - s.filling = s.filling[:0] - return s.err - } - - // Move blocks forward. - s.filling, s.current, s.previous = s.previous[:0], s.filling, s.current - s.nInput += int64(len(s.current)) - s.wg.Add(1) - go func(src []byte) { - if debugEncoder { - println("Adding block,", len(src), "bytes, final:", final) - } - defer func() { - if r := recover(); r != nil { - s.err = fmt.Errorf("panic while encoding: %v", r) - rdebug.PrintStack() - } - s.wg.Done() - }() - enc := s.encoder - blk := enc.Block() - enc.Encode(blk, src) - blk.last = final - if final { - s.eofWritten = true - } - // Wait for pending writes. - s.wWg.Wait() - if s.writeErr != nil { - s.err = s.writeErr - return - } - // Transfer encoders from previous write block. - blk.swapEncoders(s.writing) - // Transfer recent offsets to next. - enc.UseBlock(s.writing) - s.writing = blk - s.wWg.Add(1) - go func() { - defer func() { - if r := recover(); r != nil { - s.writeErr = fmt.Errorf("panic while encoding/writing: %v", r) - rdebug.PrintStack() - } - s.wWg.Done() - }() - s.writeErr = blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) - if s.writeErr != nil { - return - } - _, s.writeErr = s.w.Write(blk.output) - s.nWritten += int64(len(blk.output)) - }() - }(s.current) - return nil -} - -// ReadFrom reads data from r until EOF or error. -// The return value n is the number of bytes read. -// Any error except io.EOF encountered during the read is also returned. -// -// The Copy function uses ReaderFrom if available. -func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) { - if debugEncoder { - println("Using ReadFrom") - } - - // Flush any current writes. - if len(e.state.filling) > 0 { - if err := e.nextBlock(false); err != nil { - return 0, err - } - } - e.state.filling = e.state.filling[:e.o.blockSize] - src := e.state.filling - for { - n2, err := r.Read(src) - if e.o.crc { - _, _ = e.state.encoder.CRC().Write(src[:n2]) - } - // src is now the unfilled part... - src = src[n2:] - n += int64(n2) - switch err { - case io.EOF: - e.state.filling = e.state.filling[:len(e.state.filling)-len(src)] - if debugEncoder { - println("ReadFrom: got EOF final block:", len(e.state.filling)) - } - return n, nil - case nil: - default: - if debugEncoder { - println("ReadFrom: got error:", err) - } - e.state.err = err - return n, err - } - if len(src) > 0 { - if debugEncoder { - println("ReadFrom: got space left in source:", len(src)) - } - continue - } - err = e.nextBlock(false) - if err != nil { - return n, err - } - e.state.filling = e.state.filling[:e.o.blockSize] - src = e.state.filling - } -} - -// Flush will send the currently written data to output -// and block until everything has been written. -// This should only be used on rare occasions where pushing the currently queued data is critical. -func (e *Encoder) Flush() error { - s := &e.state - if len(s.filling) > 0 { - err := e.nextBlock(false) - if err != nil { - return err - } - } - s.wg.Wait() - s.wWg.Wait() - if s.err != nil { - return s.err - } - return s.writeErr -} - -// Close will flush the final output and close the stream. -// The function will block until everything has been written. -// The Encoder can still be re-used after calling this. -func (e *Encoder) Close() error { - s := &e.state - if s.encoder == nil { - return nil - } - err := e.nextBlock(true) - if err != nil { - return err - } - if s.frameContentSize > 0 { - if s.nInput != s.frameContentSize { - return fmt.Errorf("frame content size %d given, but %d bytes was written", s.frameContentSize, s.nInput) - } - } - if e.state.fullFrameWritten { - return s.err - } - s.wg.Wait() - s.wWg.Wait() - - if s.err != nil { - return s.err - } - if s.writeErr != nil { - return s.writeErr - } - - // Write CRC - if e.o.crc && s.err == nil { - // heap alloc. - var tmp [4]byte - _, s.err = s.w.Write(s.encoder.AppendCRC(tmp[:0])) - s.nWritten += 4 - } - - // Add padding with content from crypto/rand.Reader - if s.err == nil && e.o.pad > 0 { - add := calcSkippableFrame(s.nWritten, int64(e.o.pad)) - frame, err := skippableFrame(s.filling[:0], add, rand.Reader) - if err != nil { - return err - } - _, s.err = s.w.Write(frame) - } - return s.err -} - -// EncodeAll will encode all input in src and append it to dst. -// This function can be called concurrently, but each call will only run on a single goroutine. -// If empty input is given, nothing is returned, unless WithZeroFrames is specified. -// Encoded blocks can be concatenated and the result will be the combined input stream. -// Data compressed with EncodeAll can be decoded with the Decoder, -// using either a stream or DecodeAll. -func (e *Encoder) EncodeAll(src, dst []byte) []byte { - if len(src) == 0 { - if e.o.fullZero { - // Add frame header. - fh := frameHeader{ - ContentSize: 0, - WindowSize: MinWindowSize, - SingleSegment: true, - // Adding a checksum would be a waste of space. - Checksum: false, - DictID: 0, - } - dst = fh.appendTo(dst) - - // Write raw block as last one only. - var blk blockHeader - blk.setSize(0) - blk.setType(blockTypeRaw) - blk.setLast(true) - dst = blk.appendTo(dst) - } - return dst - } - e.init.Do(e.initialize) - enc := <-e.encoders - defer func() { - // Release encoder reference to last block. - // If a non-single block is needed the encoder will reset again. - e.encoders <- enc - }() - // Use single segments when above minimum window and below window size. - single := len(src) <= e.o.windowSize && len(src) > MinWindowSize - if e.o.single != nil { - single = *e.o.single - } - fh := frameHeader{ - ContentSize: uint64(len(src)), - WindowSize: uint32(enc.WindowSize(int64(len(src)))), - SingleSegment: single, - Checksum: e.o.crc, - DictID: e.o.dict.ID(), - } - - // If less than 1MB, allocate a buffer up front. - if len(dst) == 0 && cap(dst) == 0 && len(src) < 1<<20 && !e.o.lowMem { - dst = make([]byte, 0, len(src)) - } - dst = fh.appendTo(dst) - - // If we can do everything in one block, prefer that. - if len(src) <= e.o.blockSize { - enc.Reset(e.o.dict, true) - // Slightly faster with no history and everything in one block. - if e.o.crc { - _, _ = enc.CRC().Write(src) - } - blk := enc.Block() - blk.last = true - if e.o.dict == nil { - enc.EncodeNoHist(blk, src) - } else { - enc.Encode(blk, src) - } - - // If we got the exact same number of literals as input, - // assume the literals cannot be compressed. - oldout := blk.output - // Output directly to dst - blk.output = dst - - err := blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) - if err != nil { - panic(err) - } - dst = blk.output - blk.output = oldout - } else { - enc.Reset(e.o.dict, false) - blk := enc.Block() - for len(src) > 0 { - todo := src - if len(todo) > e.o.blockSize { - todo = todo[:e.o.blockSize] - } - src = src[len(todo):] - if e.o.crc { - _, _ = enc.CRC().Write(todo) - } - blk.pushOffsets() - enc.Encode(blk, todo) - if len(src) == 0 { - blk.last = true - } - err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy) - if err != nil { - panic(err) - } - dst = append(dst, blk.output...) - blk.reset(nil) - } - } - if e.o.crc { - dst = enc.AppendCRC(dst) - } - // Add padding with content from crypto/rand.Reader - if e.o.pad > 0 { - add := calcSkippableFrame(int64(len(dst)), int64(e.o.pad)) - var err error - dst, err = skippableFrame(dst, add, rand.Reader) - if err != nil { - panic(err) - } - } - return dst -} - -// MaxEncodedSize returns the expected maximum -// size of an encoded block or stream. -func (e *Encoder) MaxEncodedSize(size int) int { - frameHeader := 4 + 2 // magic + frame header & window descriptor - if e.o.dict != nil { - frameHeader += 4 - } - // Frame content size: - if size < 256 { - frameHeader++ - } else if size < 65536+256 { - frameHeader += 2 - } else if size < math.MaxInt32 { - frameHeader += 4 - } else { - frameHeader += 8 - } - // Final crc - if e.o.crc { - frameHeader += 4 - } - - // Max overhead is 3 bytes/block. - // There cannot be 0 blocks. - blocks := (size + e.o.blockSize) / e.o.blockSize - - // Combine, add padding. - maxSz := frameHeader + 3*blocks + size - if e.o.pad > 1 { - maxSz += calcSkippableFrame(int64(maxSz), int64(e.o.pad)) - } - return maxSz -} diff --git a/vendor/github.com/klauspost/compress/zstd/encoder_options.go b/vendor/github.com/klauspost/compress/zstd/encoder_options.go deleted file mode 100644 index 20671dcb9..000000000 --- a/vendor/github.com/klauspost/compress/zstd/encoder_options.go +++ /dev/null @@ -1,339 +0,0 @@ -package zstd - -import ( - "errors" - "fmt" - "math" - "math/bits" - "runtime" - "strings" -) - -// EOption is an option for creating a encoder. -type EOption func(*encoderOptions) error - -// options retains accumulated state of multiple options. -type encoderOptions struct { - concurrent int - level EncoderLevel - single *bool - pad int - blockSize int - windowSize int - crc bool - fullZero bool - noEntropy bool - allLitEntropy bool - customWindow bool - customALEntropy bool - customBlockSize bool - lowMem bool - dict *dict -} - -func (o *encoderOptions) setDefault() { - *o = encoderOptions{ - concurrent: runtime.GOMAXPROCS(0), - crc: true, - single: nil, - blockSize: maxCompressedBlockSize, - windowSize: 8 << 20, - level: SpeedDefault, - allLitEntropy: false, - lowMem: false, - } -} - -// encoder returns an encoder with the selected options. -func (o encoderOptions) encoder() encoder { - switch o.level { - case SpeedFastest: - if o.dict != nil { - return &fastEncoderDict{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} - } - return &fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} - - case SpeedDefault: - if o.dict != nil { - return &doubleFastEncoderDict{fastEncoderDict: fastEncoderDict{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}}} - } - return &doubleFastEncoder{fastEncoder: fastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} - case SpeedBetterCompression: - if o.dict != nil { - return &betterFastEncoderDict{betterFastEncoder: betterFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}}} - } - return &betterFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} - case SpeedBestCompression: - return &bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(o.windowSize), bufferReset: math.MaxInt32 - int32(o.windowSize*2), lowMem: o.lowMem}} - } - panic("unknown compression level") -} - -// WithEncoderCRC will add CRC value to output. -// Output will be 4 bytes larger. -func WithEncoderCRC(b bool) EOption { - return func(o *encoderOptions) error { o.crc = b; return nil } -} - -// WithEncoderConcurrency will set the concurrency, -// meaning the maximum number of encoders to run concurrently. -// The value supplied must be at least 1. -// For streams, setting a value of 1 will disable async compression. -// By default this will be set to GOMAXPROCS. -func WithEncoderConcurrency(n int) EOption { - return func(o *encoderOptions) error { - if n <= 0 { - return fmt.Errorf("concurrency must be at least 1") - } - o.concurrent = n - return nil - } -} - -// WithWindowSize will set the maximum allowed back-reference distance. -// The value must be a power of two between MinWindowSize and MaxWindowSize. -// A larger value will enable better compression but allocate more memory and, -// for above-default values, take considerably longer. -// The default value is determined by the compression level and max 8MB. -func WithWindowSize(n int) EOption { - return func(o *encoderOptions) error { - switch { - case n < MinWindowSize: - return fmt.Errorf("window size must be at least %d", MinWindowSize) - case n > MaxWindowSize: - return fmt.Errorf("window size must be at most %d", MaxWindowSize) - case (n & (n - 1)) != 0: - return errors.New("window size must be a power of 2") - } - - o.windowSize = n - o.customWindow = true - if o.blockSize > o.windowSize { - o.blockSize = o.windowSize - o.customBlockSize = true - } - return nil - } -} - -// WithEncoderPadding will add padding to all output so the size will be a multiple of n. -// This can be used to obfuscate the exact output size or make blocks of a certain size. -// The contents will be a skippable frame, so it will be invisible by the decoder. -// n must be > 0 and <= 1GB, 1<<30 bytes. -// The padded area will be filled with data from crypto/rand.Reader. -// If `EncodeAll` is used with data already in the destination, the total size will be multiple of this. -func WithEncoderPadding(n int) EOption { - return func(o *encoderOptions) error { - if n <= 0 { - return fmt.Errorf("padding must be at least 1") - } - // No need to waste our time. - if n == 1 { - n = 0 - } - if n > 1<<30 { - return fmt.Errorf("padding must less than 1GB (1<<30 bytes) ") - } - o.pad = n - return nil - } -} - -// EncoderLevel predefines encoder compression levels. -// Only use the constants made available, since the actual mapping -// of these values are very likely to change and your compression could change -// unpredictably when upgrading the library. -type EncoderLevel int - -const ( - speedNotSet EncoderLevel = iota - - // SpeedFastest will choose the fastest reasonable compression. - // This is roughly equivalent to the fastest Zstandard mode. - SpeedFastest - - // SpeedDefault is the default "pretty fast" compression option. - // This is roughly equivalent to the default Zstandard mode (level 3). - SpeedDefault - - // SpeedBetterCompression will yield better compression than the default. - // Currently it is about zstd level 7-8 with ~ 2x-3x the default CPU usage. - // By using this, notice that CPU usage may go up in the future. - SpeedBetterCompression - - // SpeedBestCompression will choose the best available compression option. - // This will offer the best compression no matter the CPU cost. - SpeedBestCompression - - // speedLast should be kept as the last actual compression option. - // The is not for external usage, but is used to keep track of the valid options. - speedLast -) - -// EncoderLevelFromString will convert a string representation of an encoding level back -// to a compression level. The compare is not case sensitive. -// If the string wasn't recognized, (false, SpeedDefault) will be returned. -func EncoderLevelFromString(s string) (bool, EncoderLevel) { - for l := speedNotSet + 1; l < speedLast; l++ { - if strings.EqualFold(s, l.String()) { - return true, l - } - } - return false, SpeedDefault -} - -// EncoderLevelFromZstd will return an encoder level that closest matches the compression -// ratio of a specific zstd compression level. -// Many input values will provide the same compression level. -func EncoderLevelFromZstd(level int) EncoderLevel { - switch { - case level < 3: - return SpeedFastest - case level >= 3 && level < 6: - return SpeedDefault - case level >= 6 && level < 10: - return SpeedBetterCompression - default: - return SpeedBestCompression - } -} - -// String provides a string representation of the compression level. -func (e EncoderLevel) String() string { - switch e { - case SpeedFastest: - return "fastest" - case SpeedDefault: - return "default" - case SpeedBetterCompression: - return "better" - case SpeedBestCompression: - return "best" - default: - return "invalid" - } -} - -// WithEncoderLevel specifies a predefined compression level. -func WithEncoderLevel(l EncoderLevel) EOption { - return func(o *encoderOptions) error { - switch { - case l <= speedNotSet || l >= speedLast: - return fmt.Errorf("unknown encoder level") - } - o.level = l - if !o.customWindow { - switch o.level { - case SpeedFastest: - o.windowSize = 4 << 20 - if !o.customBlockSize { - o.blockSize = 1 << 16 - } - case SpeedDefault: - o.windowSize = 8 << 20 - case SpeedBetterCompression: - o.windowSize = 8 << 20 - case SpeedBestCompression: - o.windowSize = 8 << 20 - } - } - if !o.customALEntropy { - o.allLitEntropy = l > SpeedDefault - } - - return nil - } -} - -// WithZeroFrames will encode 0 length input as full frames. -// This can be needed for compatibility with zstandard usage, -// but is not needed for this package. -func WithZeroFrames(b bool) EOption { - return func(o *encoderOptions) error { - o.fullZero = b - return nil - } -} - -// WithAllLitEntropyCompression will apply entropy compression if no matches are found. -// Disabling this will skip incompressible data faster, but in cases with no matches but -// skewed character distribution compression is lost. -// Default value depends on the compression level selected. -func WithAllLitEntropyCompression(b bool) EOption { - return func(o *encoderOptions) error { - o.customALEntropy = true - o.allLitEntropy = b - return nil - } -} - -// WithNoEntropyCompression will always skip entropy compression of literals. -// This can be useful if content has matches, but unlikely to benefit from entropy -// compression. Usually the slight speed improvement is not worth enabling this. -func WithNoEntropyCompression(b bool) EOption { - return func(o *encoderOptions) error { - o.noEntropy = b - return nil - } -} - -// WithSingleSegment will set the "single segment" flag when EncodeAll is used. -// If this flag is set, data must be regenerated within a single continuous memory segment. -// In this case, Window_Descriptor byte is skipped, but Frame_Content_Size is necessarily present. -// As a consequence, the decoder must allocate a memory segment of size equal or larger than size of your content. -// In order to preserve the decoder from unreasonable memory requirements, -// a decoder is allowed to reject a compressed frame which requests a memory size beyond decoder's authorized range. -// For broader compatibility, decoders are recommended to support memory sizes of at least 8 MB. -// This is only a recommendation, each decoder is free to support higher or lower limits, depending on local limitations. -// If this is not specified, block encodes will automatically choose this based on the input size and the window size. -// This setting has no effect on streamed encodes. -func WithSingleSegment(b bool) EOption { - return func(o *encoderOptions) error { - o.single = &b - return nil - } -} - -// WithLowerEncoderMem will trade in some memory cases trade less memory usage for -// slower encoding speed. -// This will not change the window size which is the primary function for reducing -// memory usage. See WithWindowSize. -func WithLowerEncoderMem(b bool) EOption { - return func(o *encoderOptions) error { - o.lowMem = b - return nil - } -} - -// WithEncoderDict allows to register a dictionary that will be used for the encode. -// -// The slice dict must be in the [dictionary format] produced by -// "zstd --train" from the Zstandard reference implementation. -// -// The encoder *may* choose to use no dictionary instead for certain payloads. -// -// [dictionary format]: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary-format -func WithEncoderDict(dict []byte) EOption { - return func(o *encoderOptions) error { - d, err := loadDict(dict) - if err != nil { - return err - } - o.dict = d - return nil - } -} - -// WithEncoderDictRaw registers a dictionary that may be used by the encoder. -// -// The slice content may contain arbitrary data. It will be used as an initial -// history. -func WithEncoderDictRaw(id uint32, content []byte) EOption { - return func(o *encoderOptions) error { - if bits.UintSize > 32 && uint(len(content)) > dictMaxLength { - return fmt.Errorf("dictionary of size %d > 2GiB too large", len(content)) - } - o.dict = &dict{id: id, content: content, offsets: [3]int{1, 4, 8}} - return nil - } -} diff --git a/vendor/github.com/klauspost/compress/zstd/framedec.go b/vendor/github.com/klauspost/compress/zstd/framedec.go deleted file mode 100644 index 53e160f7e..000000000 --- a/vendor/github.com/klauspost/compress/zstd/framedec.go +++ /dev/null @@ -1,413 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "encoding/hex" - "errors" - "io" - - "github.com/klauspost/compress/zstd/internal/xxhash" -) - -type frameDec struct { - o decoderOptions - crc *xxhash.Digest - - WindowSize uint64 - - // Frame history passed between blocks - history history - - rawInput byteBuffer - - // Byte buffer that can be reused for small input blocks. - bBuf byteBuf - - FrameContentSize uint64 - - DictionaryID uint32 - HasCheckSum bool - SingleSegment bool -} - -const ( - // MinWindowSize is the minimum Window Size, which is 1 KB. - MinWindowSize = 1 << 10 - - // MaxWindowSize is the maximum encoder window size - // and the default decoder maximum window size. - MaxWindowSize = 1 << 29 -) - -const ( - frameMagic = "\x28\xb5\x2f\xfd" - skippableFrameMagic = "\x2a\x4d\x18" -) - -func newFrameDec(o decoderOptions) *frameDec { - if o.maxWindowSize > o.maxDecodedSize { - o.maxWindowSize = o.maxDecodedSize - } - d := frameDec{ - o: o, - } - return &d -} - -// reset will read the frame header and prepare for block decoding. -// If nothing can be read from the input, io.EOF will be returned. -// Any other error indicated that the stream contained data, but -// there was a problem. -func (d *frameDec) reset(br byteBuffer) error { - d.HasCheckSum = false - d.WindowSize = 0 - var signature [4]byte - for { - var err error - // Check if we can read more... - b, err := br.readSmall(1) - switch err { - case io.EOF, io.ErrUnexpectedEOF: - return io.EOF - case nil: - signature[0] = b[0] - default: - return err - } - // Read the rest, don't allow io.ErrUnexpectedEOF - b, err = br.readSmall(3) - switch err { - case io.EOF: - return io.EOF - case nil: - copy(signature[1:], b) - default: - return err - } - - if string(signature[1:4]) != skippableFrameMagic || signature[0]&0xf0 != 0x50 { - if debugDecoder { - println("Not skippable", hex.EncodeToString(signature[:]), hex.EncodeToString([]byte(skippableFrameMagic))) - } - // Break if not skippable frame. - break - } - // Read size to skip - b, err = br.readSmall(4) - if err != nil { - if debugDecoder { - println("Reading Frame Size", err) - } - return err - } - n := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - println("Skipping frame with", n, "bytes.") - err = br.skipN(int64(n)) - if err != nil { - if debugDecoder { - println("Reading discarded frame", err) - } - return err - } - } - if string(signature[:]) != frameMagic { - if debugDecoder { - println("Got magic numbers: ", signature, "want:", []byte(frameMagic)) - } - return ErrMagicMismatch - } - - // Read Frame_Header_Descriptor - fhd, err := br.readByte() - if err != nil { - if debugDecoder { - println("Reading Frame_Header_Descriptor", err) - } - return err - } - d.SingleSegment = fhd&(1<<5) != 0 - - if fhd&(1<<3) != 0 { - return errors.New("reserved bit set on frame header") - } - - // Read Window_Descriptor - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#window_descriptor - d.WindowSize = 0 - if !d.SingleSegment { - wd, err := br.readByte() - if err != nil { - if debugDecoder { - println("Reading Window_Descriptor", err) - } - return err - } - printf("raw: %x, mantissa: %d, exponent: %d\n", wd, wd&7, wd>>3) - windowLog := 10 + (wd >> 3) - windowBase := uint64(1) << windowLog - windowAdd := (windowBase / 8) * uint64(wd&0x7) - d.WindowSize = windowBase + windowAdd - } - - // Read Dictionary_ID - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#dictionary_id - d.DictionaryID = 0 - if size := fhd & 3; size != 0 { - if size == 3 { - size = 4 - } - - b, err := br.readSmall(int(size)) - if err != nil { - println("Reading Dictionary_ID", err) - return err - } - var id uint32 - switch len(b) { - case 1: - id = uint32(b[0]) - case 2: - id = uint32(b[0]) | (uint32(b[1]) << 8) - case 4: - id = uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - } - if debugDecoder { - println("Dict size", size, "ID:", id) - } - d.DictionaryID = id - } - - // Read Frame_Content_Size - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frame_content_size - var fcsSize int - v := fhd >> 6 - switch v { - case 0: - if d.SingleSegment { - fcsSize = 1 - } - default: - fcsSize = 1 << v - } - d.FrameContentSize = fcsUnknown - if fcsSize > 0 { - b, err := br.readSmall(fcsSize) - if err != nil { - println("Reading Frame content", err) - return err - } - switch len(b) { - case 1: - d.FrameContentSize = uint64(b[0]) - case 2: - // When FCS_Field_Size is 2, the offset of 256 is added. - d.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) + 256 - case 4: - d.FrameContentSize = uint64(b[0]) | (uint64(b[1]) << 8) | (uint64(b[2]) << 16) | (uint64(b[3]) << 24) - case 8: - d1 := uint32(b[0]) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24) - d2 := uint32(b[4]) | (uint32(b[5]) << 8) | (uint32(b[6]) << 16) | (uint32(b[7]) << 24) - d.FrameContentSize = uint64(d1) | (uint64(d2) << 32) - } - if debugDecoder { - println("Read FCS:", d.FrameContentSize) - } - } - - // Move this to shared. - d.HasCheckSum = fhd&(1<<2) != 0 - if d.HasCheckSum { - if d.crc == nil { - d.crc = xxhash.New() - } - d.crc.Reset() - } - - if d.WindowSize > d.o.maxWindowSize { - if debugDecoder { - printf("window size %d > max %d\n", d.WindowSize, d.o.maxWindowSize) - } - return ErrWindowSizeExceeded - } - - if d.WindowSize == 0 && d.SingleSegment { - // We may not need window in this case. - d.WindowSize = d.FrameContentSize - if d.WindowSize < MinWindowSize { - d.WindowSize = MinWindowSize - } - if d.WindowSize > d.o.maxDecodedSize { - if debugDecoder { - printf("window size %d > max %d\n", d.WindowSize, d.o.maxWindowSize) - } - return ErrDecoderSizeExceeded - } - } - - // The minimum Window_Size is 1 KB. - if d.WindowSize < MinWindowSize { - if debugDecoder { - println("got window size: ", d.WindowSize) - } - return ErrWindowSizeTooSmall - } - d.history.windowSize = int(d.WindowSize) - if !d.o.lowMem || d.history.windowSize < maxBlockSize { - // Alloc 2x window size if not low-mem, or window size below 2MB. - d.history.allocFrameBuffer = d.history.windowSize * 2 - } else { - if d.o.lowMem { - // Alloc with 1MB extra. - d.history.allocFrameBuffer = d.history.windowSize + maxBlockSize/2 - } else { - // Alloc with 2MB extra. - d.history.allocFrameBuffer = d.history.windowSize + maxBlockSize - } - } - - if debugDecoder { - println("Frame: Dict:", d.DictionaryID, "FrameContentSize:", d.FrameContentSize, "singleseg:", d.SingleSegment, "window:", d.WindowSize, "crc:", d.HasCheckSum) - } - - // history contains input - maybe we do something - d.rawInput = br - return nil -} - -// next will start decoding the next block from stream. -func (d *frameDec) next(block *blockDec) error { - if debugDecoder { - println("decoding new block") - } - err := block.reset(d.rawInput, d.WindowSize) - if err != nil { - println("block error:", err) - // Signal the frame decoder we have a problem. - block.sendErr(err) - return err - } - return nil -} - -// checkCRC will check the checksum, assuming the frame has one. -// Will return ErrCRCMismatch if crc check failed, otherwise nil. -func (d *frameDec) checkCRC() error { - // We can overwrite upper tmp now - buf, err := d.rawInput.readSmall(4) - if err != nil { - println("CRC missing?", err) - return err - } - - want := binary.LittleEndian.Uint32(buf[:4]) - got := uint32(d.crc.Sum64()) - - if got != want { - if debugDecoder { - printf("CRC check failed: got %08x, want %08x\n", got, want) - } - return ErrCRCMismatch - } - if debugDecoder { - printf("CRC ok %08x\n", got) - } - return nil -} - -// consumeCRC skips over the checksum, assuming the frame has one. -func (d *frameDec) consumeCRC() error { - _, err := d.rawInput.readSmall(4) - if err != nil { - println("CRC missing?", err) - } - return err -} - -// runDecoder will run the decoder for the remainder of the frame. -func (d *frameDec) runDecoder(dst []byte, dec *blockDec) ([]byte, error) { - saved := d.history.b - - // We use the history for output to avoid copying it. - d.history.b = dst - d.history.ignoreBuffer = len(dst) - // Store input length, so we only check new data. - crcStart := len(dst) - d.history.decoders.maxSyncLen = 0 - if d.o.limitToCap { - d.history.decoders.maxSyncLen = uint64(cap(dst) - len(dst)) - } - if d.FrameContentSize != fcsUnknown { - if !d.o.limitToCap || d.FrameContentSize+uint64(len(dst)) < d.history.decoders.maxSyncLen { - d.history.decoders.maxSyncLen = d.FrameContentSize + uint64(len(dst)) - } - if d.history.decoders.maxSyncLen > d.o.maxDecodedSize { - if debugDecoder { - println("maxSyncLen:", d.history.decoders.maxSyncLen, "> maxDecodedSize:", d.o.maxDecodedSize) - } - return dst, ErrDecoderSizeExceeded - } - if debugDecoder { - println("maxSyncLen:", d.history.decoders.maxSyncLen) - } - if !d.o.limitToCap && uint64(cap(dst)) < d.history.decoders.maxSyncLen { - // Alloc for output - dst2 := make([]byte, len(dst), d.history.decoders.maxSyncLen+compressedBlockOverAlloc) - copy(dst2, dst) - dst = dst2 - } - } - var err error - for { - err = dec.reset(d.rawInput, d.WindowSize) - if err != nil { - break - } - if debugDecoder { - println("next block:", dec) - } - err = dec.decodeBuf(&d.history) - if err != nil { - break - } - if uint64(len(d.history.b)-crcStart) > d.o.maxDecodedSize { - println("runDecoder: maxDecodedSize exceeded", uint64(len(d.history.b)-crcStart), ">", d.o.maxDecodedSize) - err = ErrDecoderSizeExceeded - break - } - if d.o.limitToCap && len(d.history.b) > cap(dst) { - println("runDecoder: cap exceeded", uint64(len(d.history.b)), ">", cap(dst)) - err = ErrDecoderSizeExceeded - break - } - if uint64(len(d.history.b)-crcStart) > d.FrameContentSize { - println("runDecoder: FrameContentSize exceeded", uint64(len(d.history.b)-crcStart), ">", d.FrameContentSize) - err = ErrFrameSizeExceeded - break - } - if dec.Last { - break - } - if debugDecoder { - println("runDecoder: FrameContentSize", uint64(len(d.history.b)-crcStart), "<=", d.FrameContentSize) - } - } - dst = d.history.b - if err == nil { - if d.FrameContentSize != fcsUnknown && uint64(len(d.history.b)-crcStart) != d.FrameContentSize { - err = ErrFrameSizeMismatch - } else if d.HasCheckSum { - if d.o.ignoreChecksum { - err = d.consumeCRC() - } else { - d.crc.Write(dst[crcStart:]) - err = d.checkCRC() - } - } - } - d.history.b = saved - return dst, err -} diff --git a/vendor/github.com/klauspost/compress/zstd/frameenc.go b/vendor/github.com/klauspost/compress/zstd/frameenc.go deleted file mode 100644 index 667ca0679..000000000 --- a/vendor/github.com/klauspost/compress/zstd/frameenc.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "fmt" - "io" - "math" - "math/bits" -) - -type frameHeader struct { - ContentSize uint64 - WindowSize uint32 - SingleSegment bool - Checksum bool - DictID uint32 -} - -const maxHeaderSize = 14 - -func (f frameHeader) appendTo(dst []byte) []byte { - dst = append(dst, frameMagic...) - var fhd uint8 - if f.Checksum { - fhd |= 1 << 2 - } - if f.SingleSegment { - fhd |= 1 << 5 - } - - var dictIDContent []byte - if f.DictID > 0 { - var tmp [4]byte - if f.DictID < 256 { - fhd |= 1 - tmp[0] = uint8(f.DictID) - dictIDContent = tmp[:1] - } else if f.DictID < 1<<16 { - fhd |= 2 - binary.LittleEndian.PutUint16(tmp[:2], uint16(f.DictID)) - dictIDContent = tmp[:2] - } else { - fhd |= 3 - binary.LittleEndian.PutUint32(tmp[:4], f.DictID) - dictIDContent = tmp[:4] - } - } - var fcs uint8 - if f.ContentSize >= 256 { - fcs++ - } - if f.ContentSize >= 65536+256 { - fcs++ - } - if f.ContentSize >= 0xffffffff { - fcs++ - } - - fhd |= fcs << 6 - - dst = append(dst, fhd) - if !f.SingleSegment { - const winLogMin = 10 - windowLog := (bits.Len32(f.WindowSize-1) - winLogMin) << 3 - dst = append(dst, uint8(windowLog)) - } - if f.DictID > 0 { - dst = append(dst, dictIDContent...) - } - switch fcs { - case 0: - if f.SingleSegment { - dst = append(dst, uint8(f.ContentSize)) - } - // Unless SingleSegment is set, framessizes < 256 are not stored. - case 1: - f.ContentSize -= 256 - dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8)) - case 2: - dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8), uint8(f.ContentSize>>16), uint8(f.ContentSize>>24)) - case 3: - dst = append(dst, uint8(f.ContentSize), uint8(f.ContentSize>>8), uint8(f.ContentSize>>16), uint8(f.ContentSize>>24), - uint8(f.ContentSize>>32), uint8(f.ContentSize>>40), uint8(f.ContentSize>>48), uint8(f.ContentSize>>56)) - default: - panic("invalid fcs") - } - return dst -} - -const skippableFrameHeader = 4 + 4 - -// calcSkippableFrame will return a total size to be added for written -// to be divisible by multiple. -// The value will always be > skippableFrameHeader. -// The function will panic if written < 0 or wantMultiple <= 0. -func calcSkippableFrame(written, wantMultiple int64) int { - if wantMultiple <= 0 { - panic("wantMultiple <= 0") - } - if written < 0 { - panic("written < 0") - } - leftOver := written % wantMultiple - if leftOver == 0 { - return 0 - } - toAdd := wantMultiple - leftOver - for toAdd < skippableFrameHeader { - toAdd += wantMultiple - } - return int(toAdd) -} - -// skippableFrame will add a skippable frame with a total size of bytes. -// total should be >= skippableFrameHeader and < math.MaxUint32. -func skippableFrame(dst []byte, total int, r io.Reader) ([]byte, error) { - if total == 0 { - return dst, nil - } - if total < skippableFrameHeader { - return dst, fmt.Errorf("requested skippable frame (%d) < 8", total) - } - if int64(total) > math.MaxUint32 { - return dst, fmt.Errorf("requested skippable frame (%d) > max uint32", total) - } - dst = append(dst, 0x50, 0x2a, 0x4d, 0x18) - f := uint32(total - skippableFrameHeader) - dst = append(dst, uint8(f), uint8(f>>8), uint8(f>>16), uint8(f>>24)) - start := len(dst) - dst = append(dst, make([]byte, f)...) - _, err := io.ReadFull(r, dst[start:]) - return dst, err -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder.go deleted file mode 100644 index 2f8860a72..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder.go +++ /dev/null @@ -1,307 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "errors" - "fmt" - "io" -) - -const ( - tablelogAbsoluteMax = 9 -) - -const ( - /*!MEMORY_USAGE : - * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - * Increasing memory usage improves compression ratio - * Reduced memory usage can improve speed, due to cache effect - * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ - maxMemoryUsage = tablelogAbsoluteMax + 2 - - maxTableLog = maxMemoryUsage - 2 - maxTablesize = 1 << maxTableLog - maxTableMask = (1 << maxTableLog) - 1 - minTablelog = 5 - maxSymbolValue = 255 -) - -// fseDecoder provides temporary storage for compression and decompression. -type fseDecoder struct { - dt [maxTablesize]decSymbol // Decompression table. - symbolLen uint16 // Length of active part of the symbol table. - actualTableLog uint8 // Selected tablelog. - maxBits uint8 // Maximum number of additional bits - - // used for table creation to avoid allocations. - stateTable [256]uint16 - norm [maxSymbolValue + 1]int16 - preDefined bool -} - -// tableStep returns the next table index. -func tableStep(tableSize uint32) uint32 { - return (tableSize >> 1) + (tableSize >> 3) + 3 -} - -// readNCount will read the symbol distribution so decoding tables can be constructed. -func (s *fseDecoder) readNCount(b *byteReader, maxSymbol uint16) error { - var ( - charnum uint16 - previous0 bool - ) - if b.remain() < 4 { - return errors.New("input too small") - } - bitStream := b.Uint32NC() - nbBits := uint((bitStream & 0xF) + minTablelog) // extract tableLog - if nbBits > tablelogAbsoluteMax { - println("Invalid tablelog:", nbBits) - return errors.New("tableLog too large") - } - bitStream >>= 4 - bitCount := uint(4) - - s.actualTableLog = uint8(nbBits) - remaining := int32((1 << nbBits) + 1) - threshold := int32(1 << nbBits) - gotTotal := int32(0) - nbBits++ - - for remaining > 1 && charnum <= maxSymbol { - if previous0 { - //println("prev0") - n0 := charnum - for (bitStream & 0xFFFF) == 0xFFFF { - //println("24 x 0") - n0 += 24 - if r := b.remain(); r > 5 { - b.advance(2) - // The check above should make sure we can read 32 bits - bitStream = b.Uint32NC() >> bitCount - } else { - // end of bit stream - bitStream >>= 16 - bitCount += 16 - } - } - //printf("bitstream: %d, 0b%b", bitStream&3, bitStream) - for (bitStream & 3) == 3 { - n0 += 3 - bitStream >>= 2 - bitCount += 2 - } - n0 += uint16(bitStream & 3) - bitCount += 2 - - if n0 > maxSymbolValue { - return errors.New("maxSymbolValue too small") - } - //println("inserting ", n0-charnum, "zeroes from idx", charnum, "ending before", n0) - for charnum < n0 { - s.norm[uint8(charnum)] = 0 - charnum++ - } - - if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 { - b.advance(bitCount >> 3) - bitCount &= 7 - // The check above should make sure we can read 32 bits - bitStream = b.Uint32NC() >> bitCount - } else { - bitStream >>= 2 - } - } - - max := (2*threshold - 1) - remaining - var count int32 - - if int32(bitStream)&(threshold-1) < max { - count = int32(bitStream) & (threshold - 1) - if debugAsserts && nbBits < 1 { - panic("nbBits underflow") - } - bitCount += nbBits - 1 - } else { - count = int32(bitStream) & (2*threshold - 1) - if count >= threshold { - count -= max - } - bitCount += nbBits - } - - // extra accuracy - count-- - if count < 0 { - // -1 means +1 - remaining += count - gotTotal -= count - } else { - remaining -= count - gotTotal += count - } - s.norm[charnum&0xff] = int16(count) - charnum++ - previous0 = count == 0 - for remaining < threshold { - nbBits-- - threshold >>= 1 - } - - if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 { - b.advance(bitCount >> 3) - bitCount &= 7 - // The check above should make sure we can read 32 bits - bitStream = b.Uint32NC() >> (bitCount & 31) - } else { - bitCount -= (uint)(8 * (len(b.b) - 4 - b.off)) - b.off = len(b.b) - 4 - bitStream = b.Uint32() >> (bitCount & 31) - } - } - s.symbolLen = charnum - if s.symbolLen <= 1 { - return fmt.Errorf("symbolLen (%d) too small", s.symbolLen) - } - if s.symbolLen > maxSymbolValue+1 { - return fmt.Errorf("symbolLen (%d) too big", s.symbolLen) - } - if remaining != 1 { - return fmt.Errorf("corruption detected (remaining %d != 1)", remaining) - } - if bitCount > 32 { - return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount) - } - if gotTotal != 1<> 3) - return s.buildDtable() -} - -func (s *fseDecoder) mustReadFrom(r io.Reader) { - fatalErr := func(err error) { - if err != nil { - panic(err) - } - } - // dt [maxTablesize]decSymbol // Decompression table. - // symbolLen uint16 // Length of active part of the symbol table. - // actualTableLog uint8 // Selected tablelog. - // maxBits uint8 // Maximum number of additional bits - // // used for table creation to avoid allocations. - // stateTable [256]uint16 - // norm [maxSymbolValue + 1]int16 - // preDefined bool - fatalErr(binary.Read(r, binary.LittleEndian, &s.dt)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.symbolLen)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.actualTableLog)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.maxBits)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.stateTable)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.norm)) - fatalErr(binary.Read(r, binary.LittleEndian, &s.preDefined)) -} - -// decSymbol contains information about a state entry, -// Including the state offset base, the output symbol and -// the number of bits to read for the low part of the destination state. -// Using a composite uint64 is faster than a struct with separate members. -type decSymbol uint64 - -func newDecSymbol(nbits, addBits uint8, newState uint16, baseline uint32) decSymbol { - return decSymbol(nbits) | (decSymbol(addBits) << 8) | (decSymbol(newState) << 16) | (decSymbol(baseline) << 32) -} - -func (d decSymbol) nbBits() uint8 { - return uint8(d) -} - -func (d decSymbol) addBits() uint8 { - return uint8(d >> 8) -} - -func (d decSymbol) newState() uint16 { - return uint16(d >> 16) -} - -func (d decSymbol) baselineInt() int { - return int(d >> 32) -} - -func (d *decSymbol) setNBits(nBits uint8) { - const mask = 0xffffffffffffff00 - *d = (*d & mask) | decSymbol(nBits) -} - -func (d *decSymbol) setAddBits(addBits uint8) { - const mask = 0xffffffffffff00ff - *d = (*d & mask) | (decSymbol(addBits) << 8) -} - -func (d *decSymbol) setNewState(state uint16) { - const mask = 0xffffffff0000ffff - *d = (*d & mask) | decSymbol(state)<<16 -} - -func (d *decSymbol) setExt(addBits uint8, baseline uint32) { - const mask = 0xffff00ff - *d = (*d & mask) | (decSymbol(addBits) << 8) | (decSymbol(baseline) << 32) -} - -// decSymbolValue returns the transformed decSymbol for the given symbol. -func decSymbolValue(symb uint8, t []baseOffset) (decSymbol, error) { - if int(symb) >= len(t) { - return 0, fmt.Errorf("rle symbol %d >= max %d", symb, len(t)) - } - lu := t[symb] - return newDecSymbol(0, lu.addBits, 0, lu.baseLine), nil -} - -// setRLE will set the decoder til RLE mode. -func (s *fseDecoder) setRLE(symbol decSymbol) { - s.actualTableLog = 0 - s.maxBits = symbol.addBits() - s.dt[0] = symbol -} - -// transform will transform the decoder table into a table usable for -// decoding without having to apply the transformation while decoding. -// The state will contain the base value and the number of bits to read. -func (s *fseDecoder) transform(t []baseOffset) error { - tableSize := uint16(1 << s.actualTableLog) - s.maxBits = 0 - for i, v := range s.dt[:tableSize] { - add := v.addBits() - if int(add) >= len(t) { - return fmt.Errorf("invalid decoding table entry %d, symbol %d >= max (%d)", i, v.addBits(), len(t)) - } - lu := t[add] - if lu.addBits > s.maxBits { - s.maxBits = lu.addBits - } - v.setExt(lu.addBits, lu.baseLine) - s.dt[i] = v - } - return nil -} - -type fseState struct { - dt []decSymbol - state decSymbol -} - -// Initialize and decodeAsync first state and symbol. -func (s *fseState) init(br *bitReader, tableLog uint8, dt []decSymbol) { - s.dt = dt - br.fill() - s.state = dt[br.getBits(tableLog)] -} - -// final returns the current state symbol without decoding the next. -func (s decSymbol) final() (int, uint8) { - return s.baselineInt(), s.addBits() -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go deleted file mode 100644 index d04a829b0..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.go +++ /dev/null @@ -1,65 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -package zstd - -import ( - "fmt" -) - -type buildDtableAsmContext struct { - // inputs - stateTable *uint16 - norm *int16 - dt *uint64 - - // outputs --- set by the procedure in the case of error; - // for interpretation please see the error handling part below - errParam1 uint64 - errParam2 uint64 -} - -// buildDtable_asm is an x86 assembly implementation of fseDecoder.buildDtable. -// Function returns non-zero exit code on error. -// -//go:noescape -func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int - -// please keep in sync with _generate/gen_fse.go -const ( - errorCorruptedNormalizedCounter = 1 - errorNewStateTooBig = 2 - errorNewStateNoBits = 3 -) - -// buildDtable will build the decoding table. -func (s *fseDecoder) buildDtable() error { - ctx := buildDtableAsmContext{ - stateTable: &s.stateTable[0], - norm: &s.norm[0], - dt: (*uint64)(&s.dt[0]), - } - code := buildDtable_asm(s, &ctx) - - if code != 0 { - switch code { - case errorCorruptedNormalizedCounter: - position := ctx.errParam1 - return fmt.Errorf("corrupted input (position=%d, expected 0)", position) - - case errorNewStateTooBig: - newState := decSymbol(ctx.errParam1) - size := ctx.errParam2 - return fmt.Errorf("newState (%d) outside table size (%d)", newState, size) - - case errorNewStateNoBits: - newState := decSymbol(ctx.errParam1) - oldState := decSymbol(ctx.errParam2) - return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, oldState) - - default: - return fmt.Errorf("buildDtable_asm returned unhandled nonzero code = %d", code) - } - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s b/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s deleted file mode 100644 index bcde39869..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_amd64.s +++ /dev/null @@ -1,126 +0,0 @@ -// Code generated by command: go run gen_fse.go -out ../fse_decoder_amd64.s -pkg=zstd. DO NOT EDIT. - -//go:build !appengine && !noasm && gc && !noasm - -// func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int -TEXT ·buildDtable_asm(SB), $0-24 - MOVQ ctx+8(FP), CX - MOVQ s+0(FP), DI - - // Load values - MOVBQZX 4098(DI), DX - XORQ AX, AX - BTSQ DX, AX - MOVQ (CX), BX - MOVQ 16(CX), SI - LEAQ -1(AX), R8 - MOVQ 8(CX), CX - MOVWQZX 4096(DI), DI - - // End load values - // Init, lay down lowprob symbols - XORQ R9, R9 - JMP init_main_loop_condition - -init_main_loop: - MOVWQSX (CX)(R9*2), R10 - CMPW R10, $-1 - JNE do_not_update_high_threshold - MOVB R9, 1(SI)(R8*8) - DECQ R8 - MOVQ $0x0000000000000001, R10 - -do_not_update_high_threshold: - MOVW R10, (BX)(R9*2) - INCQ R9 - -init_main_loop_condition: - CMPQ R9, DI - JL init_main_loop - - // Spread symbols - // Calculate table step - MOVQ AX, R9 - SHRQ $0x01, R9 - MOVQ AX, R10 - SHRQ $0x03, R10 - LEAQ 3(R9)(R10*1), R9 - - // Fill add bits values - LEAQ -1(AX), R10 - XORQ R11, R11 - XORQ R12, R12 - JMP spread_main_loop_condition - -spread_main_loop: - XORQ R13, R13 - MOVWQSX (CX)(R12*2), R14 - JMP spread_inner_loop_condition - -spread_inner_loop: - MOVB R12, 1(SI)(R11*8) - -adjust_position: - ADDQ R9, R11 - ANDQ R10, R11 - CMPQ R11, R8 - JG adjust_position - INCQ R13 - -spread_inner_loop_condition: - CMPQ R13, R14 - JL spread_inner_loop - INCQ R12 - -spread_main_loop_condition: - CMPQ R12, DI - JL spread_main_loop - TESTQ R11, R11 - JZ spread_check_ok - MOVQ ctx+8(FP), AX - MOVQ R11, 24(AX) - MOVQ $+1, ret+16(FP) - RET - -spread_check_ok: - // Build Decoding table - XORQ DI, DI - -build_table_main_table: - MOVBQZX 1(SI)(DI*8), CX - MOVWQZX (BX)(CX*2), R8 - LEAQ 1(R8), R9 - MOVW R9, (BX)(CX*2) - MOVQ R8, R9 - BSRQ R9, R9 - MOVQ DX, CX - SUBQ R9, CX - SHLQ CL, R8 - SUBQ AX, R8 - MOVB CL, (SI)(DI*8) - MOVW R8, 2(SI)(DI*8) - CMPQ R8, AX - JLE build_table_check1_ok - MOVQ ctx+8(FP), CX - MOVQ R8, 24(CX) - MOVQ AX, 32(CX) - MOVQ $+2, ret+16(FP) - RET - -build_table_check1_ok: - TESTB CL, CL - JNZ build_table_check2_ok - CMPW R8, DI - JNE build_table_check2_ok - MOVQ ctx+8(FP), AX - MOVQ R8, 24(AX) - MOVQ DI, 32(AX) - MOVQ $+3, ret+16(FP) - RET - -build_table_check2_ok: - INCQ DI - CMPQ DI, AX - JL build_table_main_table - MOVQ $+0, ret+16(FP) - RET diff --git a/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go b/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go deleted file mode 100644 index 8adfebb02..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_decoder_generic.go +++ /dev/null @@ -1,73 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -package zstd - -import ( - "errors" - "fmt" -) - -// buildDtable will build the decoding table. -func (s *fseDecoder) buildDtable() error { - tableSize := uint32(1 << s.actualTableLog) - highThreshold := tableSize - 1 - symbolNext := s.stateTable[:256] - - // Init, lay down lowprob symbols - { - for i, v := range s.norm[:s.symbolLen] { - if v == -1 { - s.dt[highThreshold].setAddBits(uint8(i)) - highThreshold-- - v = 1 - } - symbolNext[i] = uint16(v) - } - } - - // Spread symbols - { - tableMask := tableSize - 1 - step := tableStep(tableSize) - position := uint32(0) - for ss, v := range s.norm[:s.symbolLen] { - for i := 0; i < int(v); i++ { - s.dt[position].setAddBits(uint8(ss)) - for { - // lowprob area - position = (position + step) & tableMask - if position <= highThreshold { - break - } - } - } - } - if position != 0 { - // position must reach all cells once, otherwise normalizedCounter is incorrect - return errors.New("corrupted input (position != 0)") - } - } - - // Build Decoding table - { - tableSize := uint16(1 << s.actualTableLog) - for u, v := range s.dt[:tableSize] { - symbol := v.addBits() - nextState := symbolNext[symbol] - symbolNext[symbol] = nextState + 1 - nBits := s.actualTableLog - byte(highBits(uint32(nextState))) - s.dt[u&maxTableMask].setNBits(nBits) - newState := (nextState << nBits) - tableSize - if newState > tableSize { - return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize) - } - if newState == uint16(u) && nBits == 0 { - // Seems weird that this is possible with nbits > 0. - return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u) - } - s.dt[u&maxTableMask].setNewState(newState) - } - } - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_encoder.go b/vendor/github.com/klauspost/compress/zstd/fse_encoder.go deleted file mode 100644 index ab26326a8..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_encoder.go +++ /dev/null @@ -1,701 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "fmt" - "math" -) - -const ( - // For encoding we only support up to - maxEncTableLog = 8 - maxEncTablesize = 1 << maxTableLog - maxEncTableMask = (1 << maxTableLog) - 1 - minEncTablelog = 5 - maxEncSymbolValue = maxMatchLengthSymbol -) - -// Scratch provides temporary storage for compression and decompression. -type fseEncoder struct { - symbolLen uint16 // Length of active part of the symbol table. - actualTableLog uint8 // Selected tablelog. - ct cTable // Compression tables. - maxCount int // count of the most probable symbol - zeroBits bool // no bits has prob > 50%. - clearCount bool // clear count - useRLE bool // This encoder is for RLE - preDefined bool // This encoder is predefined. - reUsed bool // Set to know when the encoder has been reused. - rleVal uint8 // RLE Symbol - maxBits uint8 // Maximum output bits after transform. - - // TODO: Technically zstd should be fine with 64 bytes. - count [256]uint32 - norm [256]int16 -} - -// cTable contains tables used for compression. -type cTable struct { - tableSymbol []byte - stateTable []uint16 - symbolTT []symbolTransform -} - -// symbolTransform contains the state transform for a symbol. -type symbolTransform struct { - deltaNbBits uint32 - deltaFindState int16 - outBits uint8 -} - -// String prints values as a human readable string. -func (s symbolTransform) String() string { - return fmt.Sprintf("{deltabits: %08x, findstate:%d outbits:%d}", s.deltaNbBits, s.deltaFindState, s.outBits) -} - -// Histogram allows to populate the histogram and skip that step in the compression, -// It otherwise allows to inspect the histogram when compression is done. -// To indicate that you have populated the histogram call HistogramFinished -// with the value of the highest populated symbol, as well as the number of entries -// in the most populated entry. These are accepted at face value. -func (s *fseEncoder) Histogram() *[256]uint32 { - return &s.count -} - -// HistogramFinished can be called to indicate that the histogram has been populated. -// maxSymbol is the index of the highest set symbol of the next data segment. -// maxCount is the number of entries in the most populated entry. -// These are accepted at face value. -func (s *fseEncoder) HistogramFinished(maxSymbol uint8, maxCount int) { - s.maxCount = maxCount - s.symbolLen = uint16(maxSymbol) + 1 - s.clearCount = maxCount != 0 -} - -// allocCtable will allocate tables needed for compression. -// If existing tables a re big enough, they are simply re-used. -func (s *fseEncoder) allocCtable() { - tableSize := 1 << s.actualTableLog - // get tableSymbol that is big enough. - if cap(s.ct.tableSymbol) < tableSize { - s.ct.tableSymbol = make([]byte, tableSize) - } - s.ct.tableSymbol = s.ct.tableSymbol[:tableSize] - - ctSize := tableSize - if cap(s.ct.stateTable) < ctSize { - s.ct.stateTable = make([]uint16, ctSize) - } - s.ct.stateTable = s.ct.stateTable[:ctSize] - - if cap(s.ct.symbolTT) < 256 { - s.ct.symbolTT = make([]symbolTransform, 256) - } - s.ct.symbolTT = s.ct.symbolTT[:256] -} - -// buildCTable will populate the compression table so it is ready to be used. -func (s *fseEncoder) buildCTable() error { - tableSize := uint32(1 << s.actualTableLog) - highThreshold := tableSize - 1 - var cumul [256]int16 - - s.allocCtable() - tableSymbol := s.ct.tableSymbol[:tableSize] - // symbol start positions - { - cumul[0] = 0 - for ui, v := range s.norm[:s.symbolLen-1] { - u := byte(ui) // one less than reference - if v == -1 { - // Low proba symbol - cumul[u+1] = cumul[u] + 1 - tableSymbol[highThreshold] = u - highThreshold-- - } else { - cumul[u+1] = cumul[u] + v - } - } - // Encode last symbol separately to avoid overflowing u - u := int(s.symbolLen - 1) - v := s.norm[s.symbolLen-1] - if v == -1 { - // Low proba symbol - cumul[u+1] = cumul[u] + 1 - tableSymbol[highThreshold] = byte(u) - highThreshold-- - } else { - cumul[u+1] = cumul[u] + v - } - if uint32(cumul[s.symbolLen]) != tableSize { - return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize) - } - cumul[s.symbolLen] = int16(tableSize) + 1 - } - // Spread symbols - s.zeroBits = false - { - step := tableStep(tableSize) - tableMask := tableSize - 1 - var position uint32 - // if any symbol > largeLimit, we may have 0 bits output. - largeLimit := int16(1 << (s.actualTableLog - 1)) - for ui, v := range s.norm[:s.symbolLen] { - symbol := byte(ui) - if v > largeLimit { - s.zeroBits = true - } - for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ { - tableSymbol[position] = symbol - position = (position + step) & tableMask - for position > highThreshold { - position = (position + step) & tableMask - } /* Low proba area */ - } - } - - // Check if we have gone through all positions - if position != 0 { - return errors.New("position!=0") - } - } - - // Build table - table := s.ct.stateTable - { - tsi := int(tableSize) - for u, v := range tableSymbol { - // TableU16 : sorted by symbol order; gives next state value - table[cumul[v]] = uint16(tsi + u) - cumul[v]++ - } - } - - // Build Symbol Transformation Table - { - total := int16(0) - symbolTT := s.ct.symbolTT[:s.symbolLen] - tableLog := s.actualTableLog - tl := (uint32(tableLog) << 16) - (1 << tableLog) - for i, v := range s.norm[:s.symbolLen] { - switch v { - case 0: - case -1, 1: - symbolTT[i].deltaNbBits = tl - symbolTT[i].deltaFindState = total - 1 - total++ - default: - maxBitsOut := uint32(tableLog) - highBit(uint32(v-1)) - minStatePlus := uint32(v) << maxBitsOut - symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus - symbolTT[i].deltaFindState = total - v - total += v - } - } - if total != int16(tableSize) { - return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize) - } - } - return nil -} - -var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000} - -func (s *fseEncoder) setRLE(val byte) { - s.allocCtable() - s.actualTableLog = 0 - s.ct.stateTable = s.ct.stateTable[:1] - s.ct.symbolTT[val] = symbolTransform{ - deltaFindState: 0, - deltaNbBits: 0, - } - if debugEncoder { - println("setRLE: val", val, "symbolTT", s.ct.symbolTT[val]) - } - s.rleVal = val - s.useRLE = true -} - -// setBits will set output bits for the transform. -// if nil is provided, the number of bits is equal to the index. -func (s *fseEncoder) setBits(transform []byte) { - if s.reUsed || s.preDefined { - return - } - if s.useRLE { - if transform == nil { - s.ct.symbolTT[s.rleVal].outBits = s.rleVal - s.maxBits = s.rleVal - return - } - s.maxBits = transform[s.rleVal] - s.ct.symbolTT[s.rleVal].outBits = s.maxBits - return - } - if transform == nil { - for i := range s.ct.symbolTT[:s.symbolLen] { - s.ct.symbolTT[i].outBits = uint8(i) - } - s.maxBits = uint8(s.symbolLen - 1) - return - } - s.maxBits = 0 - for i, v := range transform[:s.symbolLen] { - s.ct.symbolTT[i].outBits = v - if v > s.maxBits { - // We could assume bits always going up, but we play safe. - s.maxBits = v - } - } -} - -// normalizeCount will normalize the count of the symbols so -// the total is equal to the table size. -// If successful, compression tables will also be made ready. -func (s *fseEncoder) normalizeCount(length int) error { - if s.reUsed { - return nil - } - s.optimalTableLog(length) - var ( - tableLog = s.actualTableLog - scale = 62 - uint64(tableLog) - step = (1 << 62) / uint64(length) - vStep = uint64(1) << (scale - 20) - stillToDistribute = int16(1 << tableLog) - largest int - largestP int16 - lowThreshold = (uint32)(length >> tableLog) - ) - if s.maxCount == length { - s.useRLE = true - return nil - } - s.useRLE = false - for i, cnt := range s.count[:s.symbolLen] { - // already handled - // if (count[s] == s.length) return 0; /* rle special case */ - - if cnt == 0 { - s.norm[i] = 0 - continue - } - if cnt <= lowThreshold { - s.norm[i] = -1 - stillToDistribute-- - } else { - proba := (int16)((uint64(cnt) * step) >> scale) - if proba < 8 { - restToBeat := vStep * uint64(rtbTable[proba]) - v := uint64(cnt)*step - (uint64(proba) << scale) - if v > restToBeat { - proba++ - } - } - if proba > largestP { - largestP = proba - largest = i - } - s.norm[i] = proba - stillToDistribute -= proba - } - } - - if -stillToDistribute >= (s.norm[largest] >> 1) { - // corner case, need another normalization method - err := s.normalizeCount2(length) - if err != nil { - return err - } - if debugAsserts { - err = s.validateNorm() - if err != nil { - return err - } - } - return s.buildCTable() - } - s.norm[largest] += stillToDistribute - if debugAsserts { - err := s.validateNorm() - if err != nil { - return err - } - } - return s.buildCTable() -} - -// Secondary normalization method. -// To be used when primary method fails. -func (s *fseEncoder) normalizeCount2(length int) error { - const notYetAssigned = -2 - var ( - distributed uint32 - total = uint32(length) - tableLog = s.actualTableLog - lowThreshold = total >> tableLog - lowOne = (total * 3) >> (tableLog + 1) - ) - for i, cnt := range s.count[:s.symbolLen] { - if cnt == 0 { - s.norm[i] = 0 - continue - } - if cnt <= lowThreshold { - s.norm[i] = -1 - distributed++ - total -= cnt - continue - } - if cnt <= lowOne { - s.norm[i] = 1 - distributed++ - total -= cnt - continue - } - s.norm[i] = notYetAssigned - } - toDistribute := (1 << tableLog) - distributed - - if (total / toDistribute) > lowOne { - // risk of rounding to zero - lowOne = (total * 3) / (toDistribute * 2) - for i, cnt := range s.count[:s.symbolLen] { - if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) { - s.norm[i] = 1 - distributed++ - total -= cnt - continue - } - } - toDistribute = (1 << tableLog) - distributed - } - if distributed == uint32(s.symbolLen)+1 { - // all values are pretty poor; - // probably incompressible data (should have already been detected); - // find max, then give all remaining points to max - var maxV int - var maxC uint32 - for i, cnt := range s.count[:s.symbolLen] { - if cnt > maxC { - maxV = i - maxC = cnt - } - } - s.norm[maxV] += int16(toDistribute) - return nil - } - - if total == 0 { - // all of the symbols were low enough for the lowOne or lowThreshold - for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) { - if s.norm[i] > 0 { - toDistribute-- - s.norm[i]++ - } - } - return nil - } - - var ( - vStepLog = 62 - uint64(tableLog) - mid = uint64((1 << (vStepLog - 1)) - 1) - rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining - tmpTotal = mid - ) - for i, cnt := range s.count[:s.symbolLen] { - if s.norm[i] == notYetAssigned { - var ( - end = tmpTotal + uint64(cnt)*rStep - sStart = uint32(tmpTotal >> vStepLog) - sEnd = uint32(end >> vStepLog) - weight = sEnd - sStart - ) - if weight < 1 { - return errors.New("weight < 1") - } - s.norm[i] = int16(weight) - tmpTotal = end - } - } - return nil -} - -// optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog -func (s *fseEncoder) optimalTableLog(length int) { - tableLog := uint8(maxEncTableLog) - minBitsSrc := highBit(uint32(length)) + 1 - minBitsSymbols := highBit(uint32(s.symbolLen-1)) + 2 - minBits := uint8(minBitsSymbols) - if minBitsSrc < minBitsSymbols { - minBits = uint8(minBitsSrc) - } - - maxBitsSrc := uint8(highBit(uint32(length-1))) - 2 - if maxBitsSrc < tableLog { - // Accuracy can be reduced - tableLog = maxBitsSrc - } - if minBits > tableLog { - tableLog = minBits - } - // Need a minimum to safely represent all symbol values - if tableLog < minEncTablelog { - tableLog = minEncTablelog - } - if tableLog > maxEncTableLog { - tableLog = maxEncTableLog - } - s.actualTableLog = tableLog -} - -// validateNorm validates the normalized histogram table. -func (s *fseEncoder) validateNorm() (err error) { - var total int - for _, v := range s.norm[:s.symbolLen] { - if v >= 0 { - total += int(v) - } else { - total -= int(v) - } - } - defer func() { - if err == nil { - return - } - fmt.Printf("selected TableLog: %d, Symbol length: %d\n", s.actualTableLog, s.symbolLen) - for i, v := range s.norm[:s.symbolLen] { - fmt.Printf("%3d: %5d -> %4d \n", i, s.count[i], v) - } - }() - if total != (1 << s.actualTableLog) { - return fmt.Errorf("warning: Total == %d != %d", total, 1<> 3) + 3 + 2 - - // Write Table Size - bitStream = uint32(tableLog - minEncTablelog) - bitCount = uint(4) - remaining = int16(tableSize + 1) /* +1 for extra accuracy */ - threshold = int16(tableSize) - nbBits = uint(tableLog + 1) - outP = len(out) - ) - if cap(out) < outP+maxHeaderSize { - out = append(out, make([]byte, maxHeaderSize*3)...) - out = out[:len(out)-maxHeaderSize*3] - } - out = out[:outP+maxHeaderSize] - - // stops at 1 - for remaining > 1 { - if previous0 { - start := charnum - for s.norm[charnum] == 0 { - charnum++ - } - for charnum >= start+24 { - start += 24 - bitStream += uint32(0xFFFF) << bitCount - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - } - for charnum >= start+3 { - start += 3 - bitStream += 3 << bitCount - bitCount += 2 - } - bitStream += uint32(charnum-start) << bitCount - bitCount += 2 - if bitCount > 16 { - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - bitCount -= 16 - } - } - - count := s.norm[charnum] - charnum++ - max := (2*threshold - 1) - remaining - if count < 0 { - remaining += count - } else { - remaining -= count - } - count++ // +1 for extra accuracy - if count >= threshold { - count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ - } - bitStream += uint32(count) << bitCount - bitCount += nbBits - if count < max { - bitCount-- - } - - previous0 = count == 1 - if remaining < 1 { - return nil, errors.New("internal error: remaining < 1") - } - for remaining < threshold { - nbBits-- - threshold >>= 1 - } - - if bitCount > 16 { - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += 2 - bitStream >>= 16 - bitCount -= 16 - } - } - - if outP+2 > len(out) { - return nil, fmt.Errorf("internal error: %d > %d, maxheader: %d, sl: %d, tl: %d, normcount: %v", outP+2, len(out), maxHeaderSize, s.symbolLen, int(tableLog), s.norm[:s.symbolLen]) - } - out[outP] = byte(bitStream) - out[outP+1] = byte(bitStream >> 8) - outP += int((bitCount + 7) / 8) - - if charnum > s.symbolLen { - return nil, errors.New("internal error: charnum > s.symbolLen") - } - return out[:outP], nil -} - -// Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits) -// note 1 : assume symbolValue is valid (<= maxSymbolValue) -// note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits * -func (s *fseEncoder) bitCost(symbolValue uint8, accuracyLog uint32) uint32 { - minNbBits := s.ct.symbolTT[symbolValue].deltaNbBits >> 16 - threshold := (minNbBits + 1) << 16 - if debugAsserts { - if !(s.actualTableLog < 16) { - panic("!s.actualTableLog < 16") - } - // ensure enough room for renormalization double shift - if !(uint8(accuracyLog) < 31-s.actualTableLog) { - panic("!uint8(accuracyLog) < 31-s.actualTableLog") - } - } - tableSize := uint32(1) << s.actualTableLog - deltaFromThreshold := threshold - (s.ct.symbolTT[symbolValue].deltaNbBits + tableSize) - // linear interpolation (very approximate) - normalizedDeltaFromThreshold := (deltaFromThreshold << accuracyLog) >> s.actualTableLog - bitMultiplier := uint32(1) << accuracyLog - if debugAsserts { - if s.ct.symbolTT[symbolValue].deltaNbBits+tableSize > threshold { - panic("s.ct.symbolTT[symbolValue].deltaNbBits+tableSize > threshold") - } - if normalizedDeltaFromThreshold > bitMultiplier { - panic("normalizedDeltaFromThreshold > bitMultiplier") - } - } - return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold -} - -// Returns the cost in bits of encoding the distribution in count using ctable. -// Histogram should only be up to the last non-zero symbol. -// Returns an -1 if ctable cannot represent all the symbols in count. -func (s *fseEncoder) approxSize(hist []uint32) uint32 { - if int(s.symbolLen) < len(hist) { - // More symbols than we have. - return math.MaxUint32 - } - if s.useRLE { - // We will never reuse RLE encoders. - return math.MaxUint32 - } - const kAccuracyLog = 8 - badCost := (uint32(s.actualTableLog) + 1) << kAccuracyLog - var cost uint32 - for i, v := range hist { - if v == 0 { - continue - } - if s.norm[i] == 0 { - return math.MaxUint32 - } - bitCost := s.bitCost(uint8(i), kAccuracyLog) - if bitCost > badCost { - return math.MaxUint32 - } - cost += v * bitCost - } - return cost >> kAccuracyLog -} - -// maxHeaderSize returns the maximum header size in bits. -// This is not exact size, but we want a penalty for new tables anyway. -func (s *fseEncoder) maxHeaderSize() uint32 { - if s.preDefined { - return 0 - } - if s.useRLE { - return 8 - } - return (((uint32(s.symbolLen) * uint32(s.actualTableLog)) >> 3) + 3) * 8 -} - -// cState contains the compression state of a stream. -type cState struct { - bw *bitWriter - stateTable []uint16 - state uint16 -} - -// init will initialize the compression state to the first symbol of the stream. -func (c *cState) init(bw *bitWriter, ct *cTable, first symbolTransform) { - c.bw = bw - c.stateTable = ct.stateTable - if len(c.stateTable) == 1 { - // RLE - c.stateTable[0] = uint16(0) - c.state = 0 - return - } - nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16 - im := int32((nbBitsOut << 16) - first.deltaNbBits) - lu := (im >> nbBitsOut) + int32(first.deltaFindState) - c.state = c.stateTable[lu] -} - -// flush will write the tablelog to the output and flush the remaining full bytes. -func (c *cState) flush(tableLog uint8) { - c.bw.flush32() - c.bw.addBits16NC(c.state, tableLog) -} diff --git a/vendor/github.com/klauspost/compress/zstd/fse_predefined.go b/vendor/github.com/klauspost/compress/zstd/fse_predefined.go deleted file mode 100644 index 474cb77d2..000000000 --- a/vendor/github.com/klauspost/compress/zstd/fse_predefined.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "fmt" - "math" - "sync" -) - -var ( - // fsePredef are the predefined fse tables as defined here: - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions - // These values are already transformed. - fsePredef [3]fseDecoder - - // fsePredefEnc are the predefined encoder based on fse tables as defined here: - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions - // These values are already transformed. - fsePredefEnc [3]fseEncoder - - // symbolTableX contain the transformations needed for each type as defined in - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#the-codes-for-literals-lengths-match-lengths-and-offsets - symbolTableX [3][]baseOffset - - // maxTableSymbol is the biggest supported symbol for each table type - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#the-codes-for-literals-lengths-match-lengths-and-offsets - maxTableSymbol = [3]uint8{tableLiteralLengths: maxLiteralLengthSymbol, tableOffsets: maxOffsetLengthSymbol, tableMatchLengths: maxMatchLengthSymbol} - - // bitTables is the bits table for each table. - bitTables = [3][]byte{tableLiteralLengths: llBitsTable[:], tableOffsets: nil, tableMatchLengths: mlBitsTable[:]} -) - -type tableIndex uint8 - -const ( - // indexes for fsePredef and symbolTableX - tableLiteralLengths tableIndex = 0 - tableOffsets tableIndex = 1 - tableMatchLengths tableIndex = 2 - - maxLiteralLengthSymbol = 35 - maxOffsetLengthSymbol = 30 - maxMatchLengthSymbol = 52 -) - -// baseOffset is used for calculating transformations. -type baseOffset struct { - baseLine uint32 - addBits uint8 -} - -// fillBase will precalculate base offsets with the given bit distributions. -func fillBase(dst []baseOffset, base uint32, bits ...uint8) { - if len(bits) != len(dst) { - panic(fmt.Sprintf("len(dst) (%d) != len(bits) (%d)", len(dst), len(bits))) - } - for i, bit := range bits { - if base > math.MaxInt32 { - panic("invalid decoding table, base overflows int32") - } - - dst[i] = baseOffset{ - baseLine: base, - addBits: bit, - } - base += 1 << bit - } -} - -var predef sync.Once - -func initPredefined() { - predef.Do(func() { - // Literals length codes - tmp := make([]baseOffset, 36) - for i := range tmp[:16] { - tmp[i] = baseOffset{ - baseLine: uint32(i), - addBits: 0, - } - } - fillBase(tmp[16:], 16, 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) - symbolTableX[tableLiteralLengths] = tmp - - // Match length codes - tmp = make([]baseOffset, 53) - for i := range tmp[:32] { - tmp[i] = baseOffset{ - // The transformation adds the 3 length. - baseLine: uint32(i) + 3, - addBits: 0, - } - } - fillBase(tmp[32:], 35, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) - symbolTableX[tableMatchLengths] = tmp - - // Offset codes - tmp = make([]baseOffset, maxOffsetBits+1) - tmp[1] = baseOffset{ - baseLine: 1, - addBits: 1, - } - fillBase(tmp[2:], 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) - symbolTableX[tableOffsets] = tmp - - // Fill predefined tables and transform them. - // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#default-distributions - for i := range fsePredef[:] { - f := &fsePredef[i] - switch tableIndex(i) { - case tableLiteralLengths: - // https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L243 - f.actualTableLog = 6 - copy(f.norm[:], []int16{4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, - -1, -1, -1, -1}) - f.symbolLen = 36 - case tableOffsets: - // https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L281 - f.actualTableLog = 5 - copy(f.norm[:], []int16{ - 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1}) - f.symbolLen = 29 - case tableMatchLengths: - //https://github.com/facebook/zstd/blob/ededcfca57366461021c922720878c81a5854a0a/lib/decompress/zstd_decompress_block.c#L304 - f.actualTableLog = 6 - copy(f.norm[:], []int16{ - 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, - -1, -1, -1, -1, -1}) - f.symbolLen = 53 - } - if err := f.buildDtable(); err != nil { - panic(fmt.Errorf("building table %v: %v", tableIndex(i), err)) - } - if err := f.transform(symbolTableX[i]); err != nil { - panic(fmt.Errorf("building table %v: %v", tableIndex(i), err)) - } - f.preDefined = true - - // Create encoder as well - enc := &fsePredefEnc[i] - copy(enc.norm[:], f.norm[:]) - enc.symbolLen = f.symbolLen - enc.actualTableLog = f.actualTableLog - if err := enc.buildCTable(); err != nil { - panic(fmt.Errorf("building encoding table %v: %v", tableIndex(i), err)) - } - enc.setBits(bitTables[i]) - enc.preDefined = true - } - }) -} diff --git a/vendor/github.com/klauspost/compress/zstd/hash.go b/vendor/github.com/klauspost/compress/zstd/hash.go deleted file mode 100644 index 5d73c21eb..000000000 --- a/vendor/github.com/klauspost/compress/zstd/hash.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -const ( - prime3bytes = 506832829 - prime4bytes = 2654435761 - prime5bytes = 889523592379 - prime6bytes = 227718039650203 - prime7bytes = 58295818150454627 - prime8bytes = 0xcf1bbcdcb7a56463 -) - -// hashLen returns a hash of the lowest mls bytes of with length output bits. -// mls must be >=3 and <=8. Any other value will return hash for 4 bytes. -// length should always be < 32. -// Preferably length and mls should be a constant for inlining. -func hashLen(u uint64, length, mls uint8) uint32 { - switch mls { - case 3: - return (uint32(u<<8) * prime3bytes) >> (32 - length) - case 5: - return uint32(((u << (64 - 40)) * prime5bytes) >> (64 - length)) - case 6: - return uint32(((u << (64 - 48)) * prime6bytes) >> (64 - length)) - case 7: - return uint32(((u << (64 - 56)) * prime7bytes) >> (64 - length)) - case 8: - return uint32((u * prime8bytes) >> (64 - length)) - default: - return (uint32(u) * prime4bytes) >> (32 - length) - } -} diff --git a/vendor/github.com/klauspost/compress/zstd/history.go b/vendor/github.com/klauspost/compress/zstd/history.go deleted file mode 100644 index 09164856d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/history.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "github.com/klauspost/compress/huff0" -) - -// history contains the information transferred between blocks. -type history struct { - // Literal decompression - huffTree *huff0.Scratch - - // Sequence decompression - decoders sequenceDecs - recentOffsets [3]int - - // History buffer... - b []byte - - // ignoreBuffer is meant to ignore a number of bytes - // when checking for matches in history - ignoreBuffer int - - windowSize int - allocFrameBuffer int // needed? - error bool - dict *dict -} - -// reset will reset the history to initial state of a frame. -// The history must already have been initialized to the desired size. -func (h *history) reset() { - h.b = h.b[:0] - h.ignoreBuffer = 0 - h.error = false - h.recentOffsets = [3]int{1, 4, 8} - h.decoders.freeDecoders() - h.decoders = sequenceDecs{br: h.decoders.br} - h.freeHuffDecoder() - h.huffTree = nil - h.dict = nil - //printf("history created: %+v (l: %d, c: %d)", *h, len(h.b), cap(h.b)) -} - -func (h *history) freeHuffDecoder() { - if h.huffTree != nil { - if h.dict == nil || h.dict.litEnc != h.huffTree { - huffDecoderPool.Put(h.huffTree) - h.huffTree = nil - } - } -} - -func (h *history) setDict(dict *dict) { - if dict == nil { - return - } - h.dict = dict - h.decoders.litLengths = dict.llDec - h.decoders.offsets = dict.ofDec - h.decoders.matchLengths = dict.mlDec - h.decoders.dict = dict.content - h.recentOffsets = dict.offsets - h.huffTree = dict.litEnc -} - -// append bytes to history. -// This function will make sure there is space for it, -// if the buffer has been allocated with enough extra space. -func (h *history) append(b []byte) { - if len(b) >= h.windowSize { - // Discard all history by simply overwriting - h.b = h.b[:h.windowSize] - copy(h.b, b[len(b)-h.windowSize:]) - return - } - - // If there is space, append it. - if len(b) < cap(h.b)-len(h.b) { - h.b = append(h.b, b...) - return - } - - // Move data down so we only have window size left. - // We know we have less than window size in b at this point. - discard := len(b) + len(h.b) - h.windowSize - copy(h.b, h.b[discard:]) - h.b = h.b[:h.windowSize] - copy(h.b[h.windowSize-len(b):], b) -} - -// ensureBlock will ensure there is space for at least one block... -func (h *history) ensureBlock() { - if cap(h.b) < h.allocFrameBuffer { - h.b = make([]byte, 0, h.allocFrameBuffer) - return - } - - avail := cap(h.b) - len(h.b) - if avail >= h.windowSize || avail > maxCompressedBlockSize { - return - } - // Move data down so we only have window size left. - // We know we have less than window size in b at this point. - discard := len(h.b) - h.windowSize - copy(h.b, h.b[discard:]) - h.b = h.b[:h.windowSize] -} - -// append bytes to history without ever discarding anything. -func (h *history) appendKeep(b []byte) { - h.b = append(h.b, b...) -} diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt deleted file mode 100644 index 24b53065f..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2016 Caleb Spare - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md deleted file mode 100644 index 777290d44..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/README.md +++ /dev/null @@ -1,71 +0,0 @@ -# xxhash - -VENDORED: Go to [github.com/cespare/xxhash](https://github.com/cespare/xxhash) for original package. - -xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a -high-quality hashing algorithm that is much faster than anything in the Go -standard library. - -This package provides a straightforward API: - -``` -func Sum64(b []byte) uint64 -func Sum64String(s string) uint64 -type Digest struct{ ... } - func New() *Digest -``` - -The `Digest` type implements hash.Hash64. Its key methods are: - -``` -func (*Digest) Write([]byte) (int, error) -func (*Digest) WriteString(string) (int, error) -func (*Digest) Sum64() uint64 -``` - -The package is written with optimized pure Go and also contains even faster -assembly implementations for amd64 and arm64. If desired, the `purego` build tag -opts into using the Go code even on those architectures. - -[xxHash]: http://cyan4973.github.io/xxHash/ - -## Compatibility - -This package is in a module and the latest code is in version 2 of the module. -You need a version of Go with at least "minimal module compatibility" to use -github.com/cespare/xxhash/v2: - -* 1.9.7+ for Go 1.9 -* 1.10.3+ for Go 1.10 -* Go 1.11 or later - -I recommend using the latest release of Go. - -## Benchmarks - -Here are some quick benchmarks comparing the pure-Go and assembly -implementations of Sum64. - -| input size | purego | asm | -| ---------- | --------- | --------- | -| 4 B | 1.3 GB/s | 1.2 GB/s | -| 16 B | 2.9 GB/s | 3.5 GB/s | -| 100 B | 6.9 GB/s | 8.1 GB/s | -| 4 KB | 11.7 GB/s | 16.7 GB/s | -| 10 MB | 12.0 GB/s | 17.3 GB/s | - -These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C -CPU using the following commands under Go 1.19.2: - -``` -benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') -benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') -``` - -## Projects using this package - -- [InfluxDB](https://github.com/influxdata/influxdb) -- [Prometheus](https://github.com/prometheus/prometheus) -- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics) -- [FreeCache](https://github.com/coocood/freecache) -- [FastCache](https://github.com/VictoriaMetrics/fastcache) diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go deleted file mode 100644 index fc40c8200..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash.go +++ /dev/null @@ -1,230 +0,0 @@ -// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described -// at http://cyan4973.github.io/xxHash/. -// THIS IS VENDORED: Go to github.com/cespare/xxhash for original package. - -package xxhash - -import ( - "encoding/binary" - "errors" - "math/bits" -) - -const ( - prime1 uint64 = 11400714785074694791 - prime2 uint64 = 14029467366897019727 - prime3 uint64 = 1609587929392839161 - prime4 uint64 = 9650029242287828579 - prime5 uint64 = 2870177450012600261 -) - -// Store the primes in an array as well. -// -// The consts are used when possible in Go code to avoid MOVs but we need a -// contiguous array of the assembly code. -var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5} - -// Digest implements hash.Hash64. -type Digest struct { - v1 uint64 - v2 uint64 - v3 uint64 - v4 uint64 - total uint64 - mem [32]byte - n int // how much of mem is used -} - -// New creates a new Digest that computes the 64-bit xxHash algorithm. -func New() *Digest { - var d Digest - d.Reset() - return &d -} - -// Reset clears the Digest's state so that it can be reused. -func (d *Digest) Reset() { - d.v1 = primes[0] + prime2 - d.v2 = prime2 - d.v3 = 0 - d.v4 = -primes[0] - d.total = 0 - d.n = 0 -} - -// Size always returns 8 bytes. -func (d *Digest) Size() int { return 8 } - -// BlockSize always returns 32 bytes. -func (d *Digest) BlockSize() int { return 32 } - -// Write adds more data to d. It always returns len(b), nil. -func (d *Digest) Write(b []byte) (n int, err error) { - n = len(b) - d.total += uint64(n) - - memleft := d.mem[d.n&(len(d.mem)-1):] - - if d.n+n < 32 { - // This new data doesn't even fill the current block. - copy(memleft, b) - d.n += n - return - } - - if d.n > 0 { - // Finish off the partial block. - c := copy(memleft, b) - d.v1 = round(d.v1, u64(d.mem[0:8])) - d.v2 = round(d.v2, u64(d.mem[8:16])) - d.v3 = round(d.v3, u64(d.mem[16:24])) - d.v4 = round(d.v4, u64(d.mem[24:32])) - b = b[c:] - d.n = 0 - } - - if len(b) >= 32 { - // One or more full blocks left. - nw := writeBlocks(d, b) - b = b[nw:] - } - - // Store any remaining partial block. - copy(d.mem[:], b) - d.n = len(b) - - return -} - -// Sum appends the current hash to b and returns the resulting slice. -func (d *Digest) Sum(b []byte) []byte { - s := d.Sum64() - return append( - b, - byte(s>>56), - byte(s>>48), - byte(s>>40), - byte(s>>32), - byte(s>>24), - byte(s>>16), - byte(s>>8), - byte(s), - ) -} - -// Sum64 returns the current hash. -func (d *Digest) Sum64() uint64 { - var h uint64 - - if d.total >= 32 { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = d.v3 + prime5 - } - - h += d.total - - b := d.mem[:d.n&(len(d.mem)-1)] - for ; len(b) >= 8; b = b[8:] { - k1 := round(0, u64(b[:8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if len(b) >= 4 { - h ^= uint64(u32(b[:4])) * prime1 - h = rol23(h)*prime2 + prime3 - b = b[4:] - } - for ; len(b) > 0; b = b[1:] { - h ^= uint64(b[0]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -const ( - magic = "xxh\x06" - marshaledSize = len(magic) + 8*5 + 32 -) - -// MarshalBinary implements the encoding.BinaryMarshaler interface. -func (d *Digest) MarshalBinary() ([]byte, error) { - b := make([]byte, 0, marshaledSize) - b = append(b, magic...) - b = appendUint64(b, d.v1) - b = appendUint64(b, d.v2) - b = appendUint64(b, d.v3) - b = appendUint64(b, d.v4) - b = appendUint64(b, d.total) - b = append(b, d.mem[:d.n]...) - b = b[:len(b)+len(d.mem)-d.n] - return b, nil -} - -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. -func (d *Digest) UnmarshalBinary(b []byte) error { - if len(b) < len(magic) || string(b[:len(magic)]) != magic { - return errors.New("xxhash: invalid hash state identifier") - } - if len(b) != marshaledSize { - return errors.New("xxhash: invalid hash state size") - } - b = b[len(magic):] - b, d.v1 = consumeUint64(b) - b, d.v2 = consumeUint64(b) - b, d.v3 = consumeUint64(b) - b, d.v4 = consumeUint64(b) - b, d.total = consumeUint64(b) - copy(d.mem[:], b) - d.n = int(d.total % uint64(len(d.mem))) - return nil -} - -func appendUint64(b []byte, x uint64) []byte { - var a [8]byte - binary.LittleEndian.PutUint64(a[:], x) - return append(b, a[:]...) -} - -func consumeUint64(b []byte) ([]byte, uint64) { - x := u64(b) - return b[8:], x -} - -func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } -func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } - -func round(acc, input uint64) uint64 { - acc += input * prime2 - acc = rol31(acc) - acc *= prime1 - return acc -} - -func mergeRound(acc, val uint64) uint64 { - val = round(0, val) - acc ^= val - acc = acc*prime1 + prime4 - return acc -} - -func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } -func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } -func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) } -func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) } -func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) } -func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) } -func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) } -func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) } diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s deleted file mode 100644 index ddb63aa91..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_amd64.s +++ /dev/null @@ -1,210 +0,0 @@ -//go:build !appengine && gc && !purego && !noasm -// +build !appengine -// +build gc -// +build !purego -// +build !noasm - -#include "textflag.h" - -// Registers: -#define h AX -#define d AX -#define p SI // pointer to advance through b -#define n DX -#define end BX // loop end -#define v1 R8 -#define v2 R9 -#define v3 R10 -#define v4 R11 -#define x R12 -#define prime1 R13 -#define prime2 R14 -#define prime4 DI - -#define round(acc, x) \ - IMULQ prime2, x \ - ADDQ x, acc \ - ROLQ $31, acc \ - IMULQ prime1, acc - -// round0 performs the operation x = round(0, x). -#define round0(x) \ - IMULQ prime2, x \ - ROLQ $31, x \ - IMULQ prime1, x - -// mergeRound applies a merge round on the two registers acc and x. -// It assumes that prime1, prime2, and prime4 have been loaded. -#define mergeRound(acc, x) \ - round0(x) \ - XORQ x, acc \ - IMULQ prime1, acc \ - ADDQ prime4, acc - -// blockLoop processes as many 32-byte blocks as possible, -// updating v1, v2, v3, and v4. It assumes that there is at least one block -// to process. -#define blockLoop() \ -loop: \ - MOVQ +0(p), x \ - round(v1, x) \ - MOVQ +8(p), x \ - round(v2, x) \ - MOVQ +16(p), x \ - round(v3, x) \ - MOVQ +24(p), x \ - round(v4, x) \ - ADDQ $32, p \ - CMPQ p, end \ - JLE loop - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 - // Load fixed primes. - MOVQ ·primes+0(SB), prime1 - MOVQ ·primes+8(SB), prime2 - MOVQ ·primes+24(SB), prime4 - - // Load slice. - MOVQ b_base+0(FP), p - MOVQ b_len+8(FP), n - LEAQ (p)(n*1), end - - // The first loop limit will be len(b)-32. - SUBQ $32, end - - // Check whether we have at least one block. - CMPQ n, $32 - JLT noBlocks - - // Set up initial state (v1, v2, v3, v4). - MOVQ prime1, v1 - ADDQ prime2, v1 - MOVQ prime2, v2 - XORQ v3, v3 - XORQ v4, v4 - SUBQ prime1, v4 - - blockLoop() - - MOVQ v1, h - ROLQ $1, h - MOVQ v2, x - ROLQ $7, x - ADDQ x, h - MOVQ v3, x - ROLQ $12, x - ADDQ x, h - MOVQ v4, x - ROLQ $18, x - ADDQ x, h - - mergeRound(h, v1) - mergeRound(h, v2) - mergeRound(h, v3) - mergeRound(h, v4) - - JMP afterBlocks - -noBlocks: - MOVQ ·primes+32(SB), h - -afterBlocks: - ADDQ n, h - - ADDQ $24, end - CMPQ p, end - JG try4 - -loop8: - MOVQ (p), x - ADDQ $8, p - round0(x) - XORQ x, h - ROLQ $27, h - IMULQ prime1, h - ADDQ prime4, h - - CMPQ p, end - JLE loop8 - -try4: - ADDQ $4, end - CMPQ p, end - JG try1 - - MOVL (p), x - ADDQ $4, p - IMULQ prime1, x - XORQ x, h - - ROLQ $23, h - IMULQ prime2, h - ADDQ ·primes+16(SB), h - -try1: - ADDQ $4, end - CMPQ p, end - JGE finalize - -loop1: - MOVBQZX (p), x - ADDQ $1, p - IMULQ ·primes+32(SB), x - XORQ x, h - ROLQ $11, h - IMULQ prime1, h - - CMPQ p, end - JL loop1 - -finalize: - MOVQ h, x - SHRQ $33, x - XORQ x, h - IMULQ prime2, h - MOVQ h, x - SHRQ $29, x - XORQ x, h - IMULQ ·primes+16(SB), h - MOVQ h, x - SHRQ $32, x - XORQ x, h - - MOVQ h, ret+24(FP) - RET - -// func writeBlocks(d *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 - // Load fixed primes needed for round. - MOVQ ·primes+0(SB), prime1 - MOVQ ·primes+8(SB), prime2 - - // Load slice. - MOVQ b_base+8(FP), p - MOVQ b_len+16(FP), n - LEAQ (p)(n*1), end - SUBQ $32, end - - // Load vN from d. - MOVQ s+0(FP), d - MOVQ 0(d), v1 - MOVQ 8(d), v2 - MOVQ 16(d), v3 - MOVQ 24(d), v4 - - // We don't need to check the loop condition here; this function is - // always called with at least one block of data to process. - blockLoop() - - // Copy vN back to d. - MOVQ v1, 0(d) - MOVQ v2, 8(d) - MOVQ v3, 16(d) - MOVQ v4, 24(d) - - // The number of bytes written is p minus the old base pointer. - SUBQ b_base+8(FP), p - MOVQ p, ret+32(FP) - - RET diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s deleted file mode 100644 index ae7d4d329..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_arm64.s +++ /dev/null @@ -1,184 +0,0 @@ -//go:build !appengine && gc && !purego && !noasm -// +build !appengine -// +build gc -// +build !purego -// +build !noasm - -#include "textflag.h" - -// Registers: -#define digest R1 -#define h R2 // return value -#define p R3 // input pointer -#define n R4 // input length -#define nblocks R5 // n / 32 -#define prime1 R7 -#define prime2 R8 -#define prime3 R9 -#define prime4 R10 -#define prime5 R11 -#define v1 R12 -#define v2 R13 -#define v3 R14 -#define v4 R15 -#define x1 R20 -#define x2 R21 -#define x3 R22 -#define x4 R23 - -#define round(acc, x) \ - MADD prime2, acc, x, acc \ - ROR $64-31, acc \ - MUL prime1, acc - -// round0 performs the operation x = round(0, x). -#define round0(x) \ - MUL prime2, x \ - ROR $64-31, x \ - MUL prime1, x - -#define mergeRound(acc, x) \ - round0(x) \ - EOR x, acc \ - MADD acc, prime4, prime1, acc - -// blockLoop processes as many 32-byte blocks as possible, -// updating v1, v2, v3, and v4. It assumes that n >= 32. -#define blockLoop() \ - LSR $5, n, nblocks \ - PCALIGN $16 \ - loop: \ - LDP.P 16(p), (x1, x2) \ - LDP.P 16(p), (x3, x4) \ - round(v1, x1) \ - round(v2, x2) \ - round(v3, x3) \ - round(v4, x4) \ - SUB $1, nblocks \ - CBNZ nblocks, loop - -// func Sum64(b []byte) uint64 -TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 - LDP b_base+0(FP), (p, n) - - LDP ·primes+0(SB), (prime1, prime2) - LDP ·primes+16(SB), (prime3, prime4) - MOVD ·primes+32(SB), prime5 - - CMP $32, n - CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 } - BLT afterLoop - - ADD prime1, prime2, v1 - MOVD prime2, v2 - MOVD $0, v3 - NEG prime1, v4 - - blockLoop() - - ROR $64-1, v1, x1 - ROR $64-7, v2, x2 - ADD x1, x2 - ROR $64-12, v3, x3 - ROR $64-18, v4, x4 - ADD x3, x4 - ADD x2, x4, h - - mergeRound(h, v1) - mergeRound(h, v2) - mergeRound(h, v3) - mergeRound(h, v4) - -afterLoop: - ADD n, h - - TBZ $4, n, try8 - LDP.P 16(p), (x1, x2) - - round0(x1) - - // NOTE: here and below, sequencing the EOR after the ROR (using a - // rotated register) is worth a small but measurable speedup for small - // inputs. - ROR $64-27, h - EOR x1 @> 64-27, h, h - MADD h, prime4, prime1, h - - round0(x2) - ROR $64-27, h - EOR x2 @> 64-27, h, h - MADD h, prime4, prime1, h - -try8: - TBZ $3, n, try4 - MOVD.P 8(p), x1 - - round0(x1) - ROR $64-27, h - EOR x1 @> 64-27, h, h - MADD h, prime4, prime1, h - -try4: - TBZ $2, n, try2 - MOVWU.P 4(p), x2 - - MUL prime1, x2 - ROR $64-23, h - EOR x2 @> 64-23, h, h - MADD h, prime3, prime2, h - -try2: - TBZ $1, n, try1 - MOVHU.P 2(p), x3 - AND $255, x3, x1 - LSR $8, x3, x2 - - MUL prime5, x1 - ROR $64-11, h - EOR x1 @> 64-11, h, h - MUL prime1, h - - MUL prime5, x2 - ROR $64-11, h - EOR x2 @> 64-11, h, h - MUL prime1, h - -try1: - TBZ $0, n, finalize - MOVBU (p), x4 - - MUL prime5, x4 - ROR $64-11, h - EOR x4 @> 64-11, h, h - MUL prime1, h - -finalize: - EOR h >> 33, h - MUL prime2, h - EOR h >> 29, h - MUL prime3, h - EOR h >> 32, h - - MOVD h, ret+24(FP) - RET - -// func writeBlocks(s *Digest, b []byte) int -TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 - LDP ·primes+0(SB), (prime1, prime2) - - // Load state. Assume v[1-4] are stored contiguously. - MOVD s+0(FP), digest - LDP 0(digest), (v1, v2) - LDP 16(digest), (v3, v4) - - LDP b_base+8(FP), (p, n) - - blockLoop() - - // Store updated state. - STP (v1, v2), 0(digest) - STP (v3, v4), 16(digest) - - BIC $31, n - MOVD n, ret+32(FP) - RET diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go deleted file mode 100644 index d4221edf4..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_asm.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build (amd64 || arm64) && !appengine && gc && !purego && !noasm -// +build amd64 arm64 -// +build !appengine -// +build gc -// +build !purego -// +build !noasm - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b. -// -//go:noescape -func Sum64(b []byte) uint64 - -//go:noescape -func writeBlocks(s *Digest, b []byte) int diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go deleted file mode 100644 index 0be16cefc..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_other.go +++ /dev/null @@ -1,76 +0,0 @@ -//go:build (!amd64 && !arm64) || appengine || !gc || purego || noasm -// +build !amd64,!arm64 appengine !gc purego noasm - -package xxhash - -// Sum64 computes the 64-bit xxHash digest of b. -func Sum64(b []byte) uint64 { - // A simpler version would be - // d := New() - // d.Write(b) - // return d.Sum64() - // but this is faster, particularly for small inputs. - - n := len(b) - var h uint64 - - if n >= 32 { - v1 := primes[0] + prime2 - v2 := prime2 - v3 := uint64(0) - v4 := -primes[0] - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - h = mergeRound(h, v1) - h = mergeRound(h, v2) - h = mergeRound(h, v3) - h = mergeRound(h, v4) - } else { - h = prime5 - } - - h += uint64(n) - - for ; len(b) >= 8; b = b[8:] { - k1 := round(0, u64(b[:8])) - h ^= k1 - h = rol27(h)*prime1 + prime4 - } - if len(b) >= 4 { - h ^= uint64(u32(b[:4])) * prime1 - h = rol23(h)*prime2 + prime3 - b = b[4:] - } - for ; len(b) > 0; b = b[1:] { - h ^= uint64(b[0]) * prime5 - h = rol11(h) * prime1 - } - - h ^= h >> 33 - h *= prime2 - h ^= h >> 29 - h *= prime3 - h ^= h >> 32 - - return h -} - -func writeBlocks(d *Digest, b []byte) int { - v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 - n := len(b) - for len(b) >= 32 { - v1 = round(v1, u64(b[0:8:len(b)])) - v2 = round(v2, u64(b[8:16:len(b)])) - v3 = round(v3, u64(b[16:24:len(b)])) - v4 = round(v4, u64(b[24:32:len(b)])) - b = b[32:len(b):len(b)] - } - d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4 - return n - len(b) -} diff --git a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go b/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go deleted file mode 100644 index 6f3b0cb10..000000000 --- a/vendor/github.com/klauspost/compress/zstd/internal/xxhash/xxhash_safe.go +++ /dev/null @@ -1,11 +0,0 @@ -package xxhash - -// Sum64String computes the 64-bit xxHash digest of s. -func Sum64String(s string) uint64 { - return Sum64([]byte(s)) -} - -// WriteString adds more data to d. It always returns len(s), nil. -func (d *Digest) WriteString(s string) (n int, err error) { - return d.Write([]byte(s)) -} diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go deleted file mode 100644 index f41932b7a..000000000 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package zstd - -// matchLen returns how many bytes match in a and b -// -// It assumes that: -// -// len(a) <= len(b) and len(a) > 0 -// -//go:noescape -func matchLen(a []byte, b []byte) int diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s b/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s deleted file mode 100644 index 0782b86e3..000000000 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_amd64.s +++ /dev/null @@ -1,66 +0,0 @@ -// Copied from S2 implementation. - -//go:build !appengine && !noasm && gc && !noasm - -#include "textflag.h" - -// func matchLen(a []byte, b []byte) int -TEXT ·matchLen(SB), NOSPLIT, $0-56 - MOVQ a_base+0(FP), AX - MOVQ b_base+24(FP), CX - MOVQ a_len+8(FP), DX - - // matchLen - XORL SI, SI - CMPL DX, $0x08 - JB matchlen_match4_standalone - -matchlen_loopback_standalone: - MOVQ (AX)(SI*1), BX - XORQ (CX)(SI*1), BX - JZ matchlen_loop_standalone - -#ifdef GOAMD64_v3 - TZCNTQ BX, BX -#else - BSFQ BX, BX -#endif - SHRL $0x03, BX - LEAL (SI)(BX*1), SI - JMP gen_match_len_end - -matchlen_loop_standalone: - LEAL -8(DX), DX - LEAL 8(SI), SI - CMPL DX, $0x08 - JAE matchlen_loopback_standalone - -matchlen_match4_standalone: - CMPL DX, $0x04 - JB matchlen_match2_standalone - MOVL (AX)(SI*1), BX - CMPL (CX)(SI*1), BX - JNE matchlen_match2_standalone - LEAL -4(DX), DX - LEAL 4(SI), SI - -matchlen_match2_standalone: - CMPL DX, $0x02 - JB matchlen_match1_standalone - MOVW (AX)(SI*1), BX - CMPW (CX)(SI*1), BX - JNE matchlen_match1_standalone - LEAL -2(DX), DX - LEAL 2(SI), SI - -matchlen_match1_standalone: - CMPL DX, $0x01 - JB gen_match_len_end - MOVB (AX)(SI*1), BL - CMPB (CX)(SI*1), BL - JNE gen_match_len_end - INCL SI - -gen_match_len_end: - MOVQ SI, ret+48(FP) - RET diff --git a/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go b/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go deleted file mode 100644 index 57b9c31c0..000000000 --- a/vendor/github.com/klauspost/compress/zstd/matchlen_generic.go +++ /dev/null @@ -1,33 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package zstd - -import ( - "encoding/binary" - "math/bits" -) - -// matchLen returns the maximum common prefix length of a and b. -// a must be the shortest of the two. -func matchLen(a, b []byte) (n int) { - for ; len(a) >= 8 && len(b) >= 8; a, b = a[8:], b[8:] { - diff := binary.LittleEndian.Uint64(a) ^ binary.LittleEndian.Uint64(b) - if diff != 0 { - return n + bits.TrailingZeros64(diff)>>3 - } - n += 8 - } - - for i := range a { - if a[i] != b[i] { - break - } - n++ - } - return n - -} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec.go b/vendor/github.com/klauspost/compress/zstd/seqdec.go deleted file mode 100644 index d7fe6d82d..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqdec.go +++ /dev/null @@ -1,503 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "fmt" - "io" -) - -type seq struct { - litLen uint32 - matchLen uint32 - offset uint32 - - // Codes are stored here for the encoder - // so they only have to be looked up once. - llCode, mlCode, ofCode uint8 -} - -type seqVals struct { - ll, ml, mo int -} - -func (s seq) String() string { - if s.offset <= 3 { - if s.offset == 0 { - return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset: INVALID (0)") - } - return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset:", s.offset, " (repeat)") - } - return fmt.Sprint("litLen:", s.litLen, ", matchLen:", s.matchLen+zstdMinMatch, ", offset:", s.offset-3, " (new)") -} - -type seqCompMode uint8 - -const ( - compModePredefined seqCompMode = iota - compModeRLE - compModeFSE - compModeRepeat -) - -type sequenceDec struct { - // decoder keeps track of the current state and updates it from the bitstream. - fse *fseDecoder - state fseState - repeat bool -} - -// init the state of the decoder with input from stream. -func (s *sequenceDec) init(br *bitReader) error { - if s.fse == nil { - return errors.New("sequence decoder not defined") - } - s.state.init(br, s.fse.actualTableLog, s.fse.dt[:1< cap(s.out) { - addBytes := s.seqSize + len(s.out) - s.out = append(s.out, make([]byte, addBytes)...) - s.out = s.out[:len(s.out)-addBytes] - } - - if debugDecoder { - printf("Execute %d seqs with hist %d, dict %d, literals: %d into %d bytes\n", len(seqs), len(hist), len(s.dict), len(s.literals), s.seqSize) - } - - var t = len(s.out) - out := s.out[:t+s.seqSize] - - for _, seq := range seqs { - // Add literals - copy(out[t:], s.literals[:seq.ll]) - t += seq.ll - s.literals = s.literals[seq.ll:] - - // Copy from dictionary... - if seq.mo > t+len(hist) || seq.mo > s.windowSize { - if len(s.dict) == 0 { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", seq.mo, t+len(hist)) - } - - // we may be in dictionary. - dictO := len(s.dict) - (seq.mo - (t + len(hist))) - if dictO < 0 || dictO >= len(s.dict) { - return fmt.Errorf("match offset (%d) bigger than current history+dict (%d)", seq.mo, t+len(hist)+len(s.dict)) - } - end := dictO + seq.ml - if end > len(s.dict) { - n := len(s.dict) - dictO - copy(out[t:], s.dict[dictO:]) - t += n - seq.ml -= n - } else { - copy(out[t:], s.dict[dictO:end]) - t += end - dictO - continue - } - } - - // Copy from history. - if v := seq.mo - t; v > 0 { - // v is the start position in history from end. - start := len(hist) - v - if seq.ml > v { - // Some goes into current block. - // Copy remainder of history - copy(out[t:], hist[start:]) - t += v - seq.ml -= v - } else { - copy(out[t:], hist[start:start+seq.ml]) - t += seq.ml - continue - } - } - // We must be in current buffer now - if seq.ml > 0 { - start := t - seq.mo - if seq.ml <= t-start { - // No overlap - copy(out[t:], out[start:start+seq.ml]) - t += seq.ml - continue - } else { - // Overlapping copy - // Extend destination slice and copy one byte at the time. - src := out[start : start+seq.ml] - dst := out[t:] - dst = dst[:len(src)] - t += len(src) - // Destination is the space we just added. - for i := range src { - dst[i] = src[i] - } - } - } - } - - // Add final literals - copy(out[t:], s.literals) - if debugDecoder { - t += len(s.literals) - if t != len(out) { - panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) - } - } - s.out = out - - return nil -} - -// decode sequences from the stream with the provided history. -func (s *sequenceDecs) decodeSync(hist []byte) error { - supported, err := s.decodeSyncSimple(hist) - if supported { - return err - } - - br := s.br - seqs := s.nSeqs - startSize := len(s.out) - // Grab full sizes tables, to avoid bounds checks. - llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] - llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state - out := s.out - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } - - if debugDecoder { - println("decodeSync: decoding", seqs, "sequences", br.remain(), "bits remain on stream") - } - for i := seqs - 1; i >= 0; i-- { - if br.overread() { - printf("reading sequence %d, exceeded available data. Overread by %d\n", seqs-i, -br.remain()) - return io.ErrUnexpectedEOF - } - var ll, mo, ml int - if len(br.in) > 4+((maxOffsetBits+16+16)>>3) { - // inlined function: - // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) - - // Final will not read from stream. - var llB, mlB, moB uint8 - ll, llB = llState.final() - ml, mlB = mlState.final() - mo, moB = ofState.final() - - // extra bits are stored in reverse order. - br.fillFast() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fillFast() - } - ml += br.getBits(mlB) - ll += br.getBits(llB) - - if moB > 1 { - s.prevOffset[2] = s.prevOffset[1] - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = mo - } else { - // mo = s.adjustOffset(mo, ll, moB) - // Inlined for rather big speedup - if ll == 0 { - // There is an exception though, when current sequence's literals_length = 0. - // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, - // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. - mo++ - } - - if mo == 0 { - mo = s.prevOffset[0] - } else { - var temp int - if mo == 3 { - temp = s.prevOffset[0] - 1 - } else { - temp = s.prevOffset[mo] - } - - if temp == 0 { - // 0 is not valid; input is corrupted; force offset to 1 - println("WARNING: temp was 0") - temp = 1 - } - - if mo != 1 { - s.prevOffset[2] = s.prevOffset[1] - } - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = temp - mo = temp - } - } - br.fillFast() - } else { - ll, mo, ml = s.next(br, llState, mlState, ofState) - br.fill() - } - - if debugSequences { - println("Seq", seqs-i-1, "Litlen:", ll, "mo:", mo, "(abs) ml:", ml) - } - - if ll > len(s.literals) { - return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, len(s.literals)) - } - size := ll + ml + len(out) - if size-startSize > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - if size > cap(out) { - // Not enough size, which can happen under high volume block streaming conditions - // but could be if destination slice is too small for sync operations. - // over-allocating here can create a large amount of GC pressure so we try to keep - // it as contained as possible - used := len(out) - startSize - addBytes := 256 + ll + ml + used>>2 - // Clamp to max block size. - if used+addBytes > maxBlockSize { - addBytes = maxBlockSize - used - } - out = append(out, make([]byte, addBytes)...) - out = out[:len(out)-addBytes] - } - if ml > maxMatchLen { - return fmt.Errorf("match len (%d) bigger than max allowed length", ml) - } - - // Add literals - out = append(out, s.literals[:ll]...) - s.literals = s.literals[ll:] - - if mo == 0 && ml > 0 { - return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) - } - - if mo > len(out)+len(hist) || mo > s.windowSize { - if len(s.dict) == 0 { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)+len(hist)-startSize) - } - - // we may be in dictionary. - dictO := len(s.dict) - (mo - (len(out) + len(hist))) - if dictO < 0 || dictO >= len(s.dict) { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", mo, len(out)+len(hist)-startSize) - } - end := dictO + ml - if end > len(s.dict) { - out = append(out, s.dict[dictO:]...) - ml -= len(s.dict) - dictO - } else { - out = append(out, s.dict[dictO:end]...) - mo = 0 - ml = 0 - } - } - - // Copy from history. - // TODO: Blocks without history could be made to ignore this completely. - if v := mo - len(out); v > 0 { - // v is the start position in history from end. - start := len(hist) - v - if ml > v { - // Some goes into current block. - // Copy remainder of history - out = append(out, hist[start:]...) - ml -= v - } else { - out = append(out, hist[start:start+ml]...) - ml = 0 - } - } - // We must be in current buffer now - if ml > 0 { - start := len(out) - mo - if ml <= len(out)-start { - // No overlap - out = append(out, out[start:start+ml]...) - } else { - // Overlapping copy - // Extend destination slice and copy one byte at the time. - out = out[:len(out)+ml] - src := out[start : start+ml] - // Destination is the space we just added. - dst := out[len(out)-ml:] - dst = dst[:len(src)] - for i := range src { - dst[i] = src[i] - } - } - } - if i == 0 { - // This is the last sequence, so we shouldn't update state. - break - } - - // Manually inlined, ~ 5-20% faster - // Update all 3 states at once. Approx 20% faster. - nBits := llState.nbBits() + mlState.nbBits() + ofState.nbBits() - if nBits == 0 { - llState = llTable[llState.newState()&maxTableMask] - mlState = mlTable[mlState.newState()&maxTableMask] - ofState = ofTable[ofState.newState()&maxTableMask] - } else { - bits := br.get32BitsFast(nBits) - - lowBits := uint16(bits >> ((ofState.nbBits() + mlState.nbBits()) & 31)) - llState = llTable[(llState.newState()+lowBits)&maxTableMask] - - lowBits = uint16(bits >> (ofState.nbBits() & 31)) - lowBits &= bitMask[mlState.nbBits()&15] - mlState = mlTable[(mlState.newState()+lowBits)&maxTableMask] - - lowBits = uint16(bits) & bitMask[ofState.nbBits()&15] - ofState = ofTable[(ofState.newState()+lowBits)&maxTableMask] - } - } - - if size := len(s.literals) + len(out) - startSize; size > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - - // Add final literals - s.out = append(out, s.literals...) - return br.close() -} - -var bitMask [16]uint16 - -func init() { - for i := range bitMask[:] { - bitMask[i] = uint16((1 << uint(i)) - 1) - } -} - -func (s *sequenceDecs) next(br *bitReader, llState, mlState, ofState decSymbol) (ll, mo, ml int) { - // Final will not read from stream. - ll, llB := llState.final() - ml, mlB := mlState.final() - mo, moB := ofState.final() - - // extra bits are stored in reverse order. - br.fill() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fill() - } - // matchlength+literal length, max 32 bits - ml += br.getBits(mlB) - ll += br.getBits(llB) - mo = s.adjustOffset(mo, ll, moB) - return -} - -func (s *sequenceDecs) adjustOffset(offset, litLen int, offsetB uint8) int { - if offsetB > 1 { - s.prevOffset[2] = s.prevOffset[1] - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = offset - return offset - } - - if litLen == 0 { - // There is an exception though, when current sequence's literals_length = 0. - // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, - // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. - offset++ - } - - if offset == 0 { - return s.prevOffset[0] - } - var temp int - if offset == 3 { - temp = s.prevOffset[0] - 1 - } else { - temp = s.prevOffset[offset] - } - - if temp == 0 { - // 0 is not valid; input is corrupted; force offset to 1 - println("temp was 0") - temp = 1 - } - - if offset != 1 { - s.prevOffset[2] = s.prevOffset[1] - } - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = temp - return temp -} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go deleted file mode 100644 index 8adabd828..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go +++ /dev/null @@ -1,394 +0,0 @@ -//go:build amd64 && !appengine && !noasm && gc -// +build amd64,!appengine,!noasm,gc - -package zstd - -import ( - "fmt" - "io" - - "github.com/klauspost/compress/internal/cpuinfo" -) - -type decodeSyncAsmContext struct { - llTable []decSymbol - mlTable []decSymbol - ofTable []decSymbol - llState uint64 - mlState uint64 - ofState uint64 - iteration int - litRemain int - out []byte - outPosition int - literals []byte - litPosition int - history []byte - windowSize int - ll int // set on error (not for all errors, please refer to _generate/gen.go) - ml int // set on error (not for all errors, please refer to _generate/gen.go) - mo int // set on error (not for all errors, please refer to _generate/gen.go) -} - -// sequenceDecs_decodeSync_amd64 implements the main loop of sequenceDecs.decodeSync in x86 asm. -// -// Please refer to seqdec_generic.go for the reference implementation. -// -//go:noescape -func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int - -// sequenceDecs_decodeSync_bmi2 implements the main loop of sequenceDecs.decodeSync in x86 asm with BMI2 extensions. -// -//go:noescape -func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int - -// sequenceDecs_decodeSync_safe_amd64 does the same as above, but does not write more than output buffer. -// -//go:noescape -func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int - -// sequenceDecs_decodeSync_safe_bmi2 does the same as above, but does not write more than output buffer. -// -//go:noescape -func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int - -// decode sequences from the stream with the provided history but without a dictionary. -func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { - if len(s.dict) > 0 { - return false, nil - } - if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSize { - return false, nil - } - - // FIXME: Using unsafe memory copies leads to rare, random crashes - // with fuzz testing. It is therefore disabled for now. - const useSafe = true - /* - useSafe := false - if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSizeAlloc { - useSafe = true - } - if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < int(s.maxSyncLen) { - useSafe = true - } - if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc { - useSafe = true - } - */ - - br := s.br - - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } - - ctx := decodeSyncAsmContext{ - llTable: s.litLengths.fse.dt[:maxTablesize], - mlTable: s.matchLengths.fse.dt[:maxTablesize], - ofTable: s.offsets.fse.dt[:maxTablesize], - llState: uint64(s.litLengths.state.state), - mlState: uint64(s.matchLengths.state.state), - ofState: uint64(s.offsets.state.state), - iteration: s.nSeqs - 1, - litRemain: len(s.literals), - out: s.out, - outPosition: len(s.out), - literals: s.literals, - windowSize: s.windowSize, - history: hist, - } - - s.seqSize = 0 - startSize := len(s.out) - - var errCode int - if cpuinfo.HasBMI2() { - if useSafe { - errCode = sequenceDecs_decodeSync_safe_bmi2(s, br, &ctx) - } else { - errCode = sequenceDecs_decodeSync_bmi2(s, br, &ctx) - } - } else { - if useSafe { - errCode = sequenceDecs_decodeSync_safe_amd64(s, br, &ctx) - } else { - errCode = sequenceDecs_decodeSync_amd64(s, br, &ctx) - } - } - switch errCode { - case noError: - break - - case errorMatchLenOfsMismatch: - return true, fmt.Errorf("zero matchoff and matchlen (%d) > 0", ctx.ml) - - case errorMatchLenTooBig: - return true, fmt.Errorf("match len (%d) bigger than max allowed length", ctx.ml) - - case errorMatchOffTooBig: - return true, fmt.Errorf("match offset (%d) bigger than current history (%d)", - ctx.mo, ctx.outPosition+len(hist)-startSize) - - case errorNotEnoughLiterals: - return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", - ctx.ll, ctx.litRemain+ctx.ll) - - case errorOverread: - return true, io.ErrUnexpectedEOF - - case errorNotEnoughSpace: - size := ctx.outPosition + ctx.ll + ctx.ml - if debugDecoder { - println("msl:", s.maxSyncLen, "cap", cap(s.out), "bef:", startSize, "sz:", size-startSize, "mbs:", maxBlockSize, "outsz:", cap(s.out)-startSize) - } - return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - - default: - return true, fmt.Errorf("sequenceDecs_decode returned erronous code %d", errCode) - } - - s.seqSize += ctx.litRemain - if s.seqSize > maxBlockSize { - return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - err := br.close() - if err != nil { - printf("Closing sequences: %v, %+v\n", err, *br) - return true, err - } - - s.literals = s.literals[ctx.litPosition:] - t := ctx.outPosition - s.out = s.out[:t] - - // Add final literals - s.out = append(s.out, s.literals...) - if debugDecoder { - t += len(s.literals) - if t != len(s.out) { - panic(fmt.Errorf("length mismatch, want %d, got %d", len(s.out), t)) - } - } - - return true, nil -} - -// -------------------------------------------------------------------------------- - -type decodeAsmContext struct { - llTable []decSymbol - mlTable []decSymbol - ofTable []decSymbol - llState uint64 - mlState uint64 - ofState uint64 - iteration int - seqs []seqVals - litRemain int -} - -const noError = 0 - -// error reported when mo == 0 && ml > 0 -const errorMatchLenOfsMismatch = 1 - -// error reported when ml > maxMatchLen -const errorMatchLenTooBig = 2 - -// error reported when mo > available history or mo > s.windowSize -const errorMatchOffTooBig = 3 - -// error reported when the sum of literal lengths exeeceds the literal buffer size -const errorNotEnoughLiterals = 4 - -// error reported when capacity of `out` is too small -const errorNotEnoughSpace = 5 - -// error reported when bits are overread. -const errorOverread = 6 - -// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm. -// -// Please refer to seqdec_generic.go for the reference implementation. -// -//go:noescape -func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int - -// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm. -// -// Please refer to seqdec_generic.go for the reference implementation. -// -//go:noescape -func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int - -// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions. -// -//go:noescape -func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int - -// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions. -// -//go:noescape -func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int - -// decode sequences from the stream without the provided history. -func (s *sequenceDecs) decode(seqs []seqVals) error { - br := s.br - - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } - - ctx := decodeAsmContext{ - llTable: s.litLengths.fse.dt[:maxTablesize], - mlTable: s.matchLengths.fse.dt[:maxTablesize], - ofTable: s.offsets.fse.dt[:maxTablesize], - llState: uint64(s.litLengths.state.state), - mlState: uint64(s.matchLengths.state.state), - ofState: uint64(s.offsets.state.state), - seqs: seqs, - iteration: len(seqs) - 1, - litRemain: len(s.literals), - } - - if debugDecoder { - println("decode: decoding", len(seqs), "sequences", br.remain(), "bits remain on stream") - } - - s.seqSize = 0 - lte56bits := s.maxBits+s.offsets.fse.actualTableLog+s.matchLengths.fse.actualTableLog+s.litLengths.fse.actualTableLog <= 56 - var errCode int - if cpuinfo.HasBMI2() { - if lte56bits { - errCode = sequenceDecs_decode_56_bmi2(s, br, &ctx) - } else { - errCode = sequenceDecs_decode_bmi2(s, br, &ctx) - } - } else { - if lte56bits { - errCode = sequenceDecs_decode_56_amd64(s, br, &ctx) - } else { - errCode = sequenceDecs_decode_amd64(s, br, &ctx) - } - } - if errCode != 0 { - i := len(seqs) - ctx.iteration - 1 - switch errCode { - case errorMatchLenOfsMismatch: - ml := ctx.seqs[i].ml - return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) - - case errorMatchLenTooBig: - ml := ctx.seqs[i].ml - return fmt.Errorf("match len (%d) bigger than max allowed length", ml) - - case errorNotEnoughLiterals: - ll := ctx.seqs[i].ll - return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, ctx.litRemain+ll) - case errorOverread: - return io.ErrUnexpectedEOF - } - - return fmt.Errorf("sequenceDecs_decode_amd64 returned erronous code %d", errCode) - } - - if ctx.litRemain < 0 { - return fmt.Errorf("literal count is too big: total available %d, total requested %d", - len(s.literals), len(s.literals)-ctx.litRemain) - } - - s.seqSize += ctx.litRemain - if s.seqSize > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - if debugDecoder { - println("decode: ", br.remain(), "bits remain on stream. code:", errCode) - } - err := br.close() - if err != nil { - printf("Closing sequences: %v, %+v\n", err, *br) - } - return err -} - -// -------------------------------------------------------------------------------- - -type executeAsmContext struct { - seqs []seqVals - seqIndex int - out []byte - history []byte - literals []byte - outPosition int - litPosition int - windowSize int -} - -// sequenceDecs_executeSimple_amd64 implements the main loop of sequenceDecs.executeSimple in x86 asm. -// -// Returns false if a match offset is too big. -// -// Please refer to seqdec_generic.go for the reference implementation. -// -//go:noescape -func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool - -// Same as above, but with safe memcopies -// -//go:noescape -func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool - -// executeSimple handles cases when dictionary is not used. -func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { - // Ensure we have enough output size... - if len(s.out)+s.seqSize+compressedBlockOverAlloc > cap(s.out) { - addBytes := s.seqSize + len(s.out) + compressedBlockOverAlloc - s.out = append(s.out, make([]byte, addBytes)...) - s.out = s.out[:len(s.out)-addBytes] - } - - if debugDecoder { - printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize) - } - - var t = len(s.out) - out := s.out[:t+s.seqSize] - - ctx := executeAsmContext{ - seqs: seqs, - seqIndex: 0, - out: out, - history: hist, - outPosition: t, - litPosition: 0, - literals: s.literals, - windowSize: s.windowSize, - } - var ok bool - if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc { - ok = sequenceDecs_executeSimple_safe_amd64(&ctx) - } else { - ok = sequenceDecs_executeSimple_amd64(&ctx) - } - if !ok { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", - seqs[ctx.seqIndex].mo, ctx.outPosition+len(hist)) - } - s.literals = s.literals[ctx.litPosition:] - t = ctx.outPosition - - // Add final literals - copy(out[t:], s.literals) - if debugDecoder { - t += len(s.literals) - if t != len(out) { - panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) - } - } - s.out = out - - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s deleted file mode 100644 index 5b06174b8..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s +++ /dev/null @@ -1,4151 +0,0 @@ -// Code generated by command: go run gen.go -out ../seqdec_amd64.s -pkg=zstd. DO NOT EDIT. - -//go:build !appengine && !noasm && gc && !noasm - -// func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int -// Requires: CMOV -TEXT ·sequenceDecs_decode_amd64(SB), $8-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI - ADDQ SI, AX - MOVQ AX, (SP) - MOVQ ctx+16(FP), AX - MOVQ 72(AX), DI - MOVQ 80(AX), R8 - MOVQ 88(AX), R9 - MOVQ 104(AX), R10 - MOVQ s+0(FP), AX - MOVQ 144(AX), R11 - MOVQ 152(AX), R12 - MOVQ 160(AX), R13 - -sequenceDecs_decode_amd64_main_loop: - MOVQ (SP), R14 - - // Fill bitreader to have enough for the offset and match length. - CMPQ SI, $0x08 - JL sequenceDecs_decode_amd64_fill_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R14 - MOVQ (R14), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decode_amd64_fill_end - -sequenceDecs_decode_amd64_fill_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decode_amd64_fill_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decode_amd64_fill_end - SHLQ $0x08, DX - SUBQ $0x01, R14 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R14), AX - ORQ AX, DX - JMP sequenceDecs_decode_amd64_fill_byte_by_byte - -sequenceDecs_decode_amd64_fill_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decode_amd64_fill_end: - // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_of_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_of_update_zero: - MOVQ AX, 16(R10) - - // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_ml_update_zero: - MOVQ AX, 8(R10) - - // Fill bitreader to have enough for the remaining - CMPQ SI, $0x08 - JL sequenceDecs_decode_amd64_fill_2_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R14 - MOVQ (R14), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decode_amd64_fill_2_end - -sequenceDecs_decode_amd64_fill_2_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decode_amd64_fill_2_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decode_amd64_fill_2_end - SHLQ $0x08, DX - SUBQ $0x01, R14 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R14), AX - ORQ AX, DX - JMP sequenceDecs_decode_amd64_fill_2_byte_by_byte - -sequenceDecs_decode_amd64_fill_2_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decode_amd64_fill_2_end: - // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_amd64_ll_update_zero: - MOVQ AX, (R10) - - // Fill bitreader for state updates - MOVQ R14, (SP) - MOVQ R9, AX - SHRQ $0x08, AX - MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decode_amd64_skip_update - - // Update Literal Length State - MOVBQZX DI, R14 - SHRL $0x10, DI - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, DI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(DI*8), DI - - // Update Match Length State - MOVBQZX R8, R14 - SHRL $0x10, R8 - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, R8 - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Offset State - MOVBQZX R9, R14 - SHRL $0x10, R9 - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, R9 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R9*8), R9 - -sequenceDecs_decode_amd64_skip_update: - // Adjust offset - MOVQ 16(R10), CX - CMPQ AX, $0x01 - JBE sequenceDecs_decode_amd64_adjust_offsetB_1_or_0 - MOVQ R12, R13 - MOVQ R11, R12 - MOVQ CX, R11 - JMP sequenceDecs_decode_amd64_after_adjust - -sequenceDecs_decode_amd64_adjust_offsetB_1_or_0: - CMPQ (R10), $0x00000000 - JNE sequenceDecs_decode_amd64_adjust_offset_maybezero - INCQ CX - JMP sequenceDecs_decode_amd64_adjust_offset_nonzero - -sequenceDecs_decode_amd64_adjust_offset_maybezero: - TESTQ CX, CX - JNZ sequenceDecs_decode_amd64_adjust_offset_nonzero - MOVQ R11, CX - JMP sequenceDecs_decode_amd64_after_adjust - -sequenceDecs_decode_amd64_adjust_offset_nonzero: - CMPQ CX, $0x01 - JB sequenceDecs_decode_amd64_adjust_zero - JEQ sequenceDecs_decode_amd64_adjust_one - CMPQ CX, $0x02 - JA sequenceDecs_decode_amd64_adjust_three - JMP sequenceDecs_decode_amd64_adjust_two - -sequenceDecs_decode_amd64_adjust_zero: - MOVQ R11, AX - JMP sequenceDecs_decode_amd64_adjust_test_temp_valid - -sequenceDecs_decode_amd64_adjust_one: - MOVQ R12, AX - JMP sequenceDecs_decode_amd64_adjust_test_temp_valid - -sequenceDecs_decode_amd64_adjust_two: - MOVQ R13, AX - JMP sequenceDecs_decode_amd64_adjust_test_temp_valid - -sequenceDecs_decode_amd64_adjust_three: - LEAQ -1(R11), AX - -sequenceDecs_decode_amd64_adjust_test_temp_valid: - TESTQ AX, AX - JNZ sequenceDecs_decode_amd64_adjust_temp_valid - MOVQ $0x00000001, AX - -sequenceDecs_decode_amd64_adjust_temp_valid: - CMPQ CX, $0x01 - CMOVQNE R12, R13 - MOVQ R11, R12 - MOVQ AX, R11 - MOVQ AX, CX - -sequenceDecs_decode_amd64_after_adjust: - MOVQ CX, 16(R10) - - // Check values - MOVQ 8(R10), AX - MOVQ (R10), R14 - LEAQ (AX)(R14*1), R15 - MOVQ s+0(FP), BP - ADDQ R15, 256(BP) - MOVQ ctx+16(FP), R15 - SUBQ R14, 128(R15) - JS error_not_enough_literals - CMPQ AX, $0x00020002 - JA sequenceDecs_decode_amd64_error_match_len_too_big - TESTQ CX, CX - JNZ sequenceDecs_decode_amd64_match_len_ofs_ok - TESTQ AX, AX - JNZ sequenceDecs_decode_amd64_error_match_len_ofs_mismatch - -sequenceDecs_decode_amd64_match_len_ofs_ok: - ADDQ $0x18, R10 - MOVQ ctx+16(FP), AX - DECQ 96(AX) - JNS sequenceDecs_decode_amd64_main_loop - MOVQ s+0(FP), AX - MOVQ R11, 144(AX) - MOVQ R12, 152(AX) - MOVQ R13, 160(AX) - MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decode_amd64_error_match_len_ofs_mismatch: - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decode_amd64_error_match_len_too_big: - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - -// func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int -// Requires: CMOV -TEXT ·sequenceDecs_decode_56_amd64(SB), $8-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI - ADDQ SI, AX - MOVQ AX, (SP) - MOVQ ctx+16(FP), AX - MOVQ 72(AX), DI - MOVQ 80(AX), R8 - MOVQ 88(AX), R9 - MOVQ 104(AX), R10 - MOVQ s+0(FP), AX - MOVQ 144(AX), R11 - MOVQ 152(AX), R12 - MOVQ 160(AX), R13 - -sequenceDecs_decode_56_amd64_main_loop: - MOVQ (SP), R14 - - // Fill bitreader to have enough for the offset and match length. - CMPQ SI, $0x08 - JL sequenceDecs_decode_56_amd64_fill_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R14 - MOVQ (R14), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decode_56_amd64_fill_end - -sequenceDecs_decode_56_amd64_fill_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decode_56_amd64_fill_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decode_56_amd64_fill_end - SHLQ $0x08, DX - SUBQ $0x01, R14 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R14), AX - ORQ AX, DX - JMP sequenceDecs_decode_56_amd64_fill_byte_by_byte - -sequenceDecs_decode_56_amd64_fill_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decode_56_amd64_fill_end: - // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_of_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_of_update_zero: - MOVQ AX, 16(R10) - - // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_ml_update_zero: - MOVQ AX, 8(R10) - - // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R15 - SHLQ CL, R15 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decode_56_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decode_56_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decode_56_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R15 - ADDQ R15, AX - -sequenceDecs_decode_56_amd64_ll_update_zero: - MOVQ AX, (R10) - - // Fill bitreader for state updates - MOVQ R14, (SP) - MOVQ R9, AX - SHRQ $0x08, AX - MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decode_56_amd64_skip_update - - // Update Literal Length State - MOVBQZX DI, R14 - SHRL $0x10, DI - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, DI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(DI*8), DI - - // Update Match Length State - MOVBQZX R8, R14 - SHRL $0x10, R8 - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, R8 - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Offset State - MOVBQZX R9, R14 - SHRL $0x10, R9 - LEAQ (BX)(R14*1), CX - MOVQ DX, R15 - MOVQ CX, BX - ROLQ CL, R15 - MOVL $0x00000001, BP - MOVB R14, CL - SHLL CL, BP - DECL BP - ANDQ BP, R15 - ADDQ R15, R9 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R9*8), R9 - -sequenceDecs_decode_56_amd64_skip_update: - // Adjust offset - MOVQ 16(R10), CX - CMPQ AX, $0x01 - JBE sequenceDecs_decode_56_amd64_adjust_offsetB_1_or_0 - MOVQ R12, R13 - MOVQ R11, R12 - MOVQ CX, R11 - JMP sequenceDecs_decode_56_amd64_after_adjust - -sequenceDecs_decode_56_amd64_adjust_offsetB_1_or_0: - CMPQ (R10), $0x00000000 - JNE sequenceDecs_decode_56_amd64_adjust_offset_maybezero - INCQ CX - JMP sequenceDecs_decode_56_amd64_adjust_offset_nonzero - -sequenceDecs_decode_56_amd64_adjust_offset_maybezero: - TESTQ CX, CX - JNZ sequenceDecs_decode_56_amd64_adjust_offset_nonzero - MOVQ R11, CX - JMP sequenceDecs_decode_56_amd64_after_adjust - -sequenceDecs_decode_56_amd64_adjust_offset_nonzero: - CMPQ CX, $0x01 - JB sequenceDecs_decode_56_amd64_adjust_zero - JEQ sequenceDecs_decode_56_amd64_adjust_one - CMPQ CX, $0x02 - JA sequenceDecs_decode_56_amd64_adjust_three - JMP sequenceDecs_decode_56_amd64_adjust_two - -sequenceDecs_decode_56_amd64_adjust_zero: - MOVQ R11, AX - JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid - -sequenceDecs_decode_56_amd64_adjust_one: - MOVQ R12, AX - JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid - -sequenceDecs_decode_56_amd64_adjust_two: - MOVQ R13, AX - JMP sequenceDecs_decode_56_amd64_adjust_test_temp_valid - -sequenceDecs_decode_56_amd64_adjust_three: - LEAQ -1(R11), AX - -sequenceDecs_decode_56_amd64_adjust_test_temp_valid: - TESTQ AX, AX - JNZ sequenceDecs_decode_56_amd64_adjust_temp_valid - MOVQ $0x00000001, AX - -sequenceDecs_decode_56_amd64_adjust_temp_valid: - CMPQ CX, $0x01 - CMOVQNE R12, R13 - MOVQ R11, R12 - MOVQ AX, R11 - MOVQ AX, CX - -sequenceDecs_decode_56_amd64_after_adjust: - MOVQ CX, 16(R10) - - // Check values - MOVQ 8(R10), AX - MOVQ (R10), R14 - LEAQ (AX)(R14*1), R15 - MOVQ s+0(FP), BP - ADDQ R15, 256(BP) - MOVQ ctx+16(FP), R15 - SUBQ R14, 128(R15) - JS error_not_enough_literals - CMPQ AX, $0x00020002 - JA sequenceDecs_decode_56_amd64_error_match_len_too_big - TESTQ CX, CX - JNZ sequenceDecs_decode_56_amd64_match_len_ofs_ok - TESTQ AX, AX - JNZ sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch - -sequenceDecs_decode_56_amd64_match_len_ofs_ok: - ADDQ $0x18, R10 - MOVQ ctx+16(FP), AX - DECQ 96(AX) - JNS sequenceDecs_decode_56_amd64_main_loop - MOVQ s+0(FP), AX - MOVQ R11, 144(AX) - MOVQ R12, 152(AX) - MOVQ R13, 160(AX) - MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decode_56_amd64_error_match_len_ofs_mismatch: - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decode_56_amd64_error_match_len_too_big: - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - -// func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int -// Requires: BMI, BMI2, CMOV -TEXT ·sequenceDecs_decode_bmi2(SB), $8-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX - ADDQ BX, CX - MOVQ CX, (SP) - MOVQ ctx+16(FP), CX - MOVQ 72(CX), SI - MOVQ 80(CX), DI - MOVQ 88(CX), R8 - MOVQ 104(CX), R9 - MOVQ s+0(FP), CX - MOVQ 144(CX), R10 - MOVQ 152(CX), R11 - MOVQ 160(CX), R12 - -sequenceDecs_decode_bmi2_main_loop: - MOVQ (SP), R13 - - // Fill bitreader to have enough for the offset and match length. - CMPQ BX, $0x08 - JL sequenceDecs_decode_bmi2_fill_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R13 - MOVQ (R13), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decode_bmi2_fill_end - -sequenceDecs_decode_bmi2_fill_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decode_bmi2_fill_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decode_bmi2_fill_end - SHLQ $0x08, AX - SUBQ $0x01, R13 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R13), CX - ORQ CX, AX - JMP sequenceDecs_decode_bmi2_fill_byte_by_byte - -sequenceDecs_decode_bmi2_fill_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decode_bmi2_fill_end: - // Update offset - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ R8, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, 16(R9) - - // Update match length - MOVQ $0x00000808, CX - BEXTRQ CX, DI, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ DI, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, 8(R9) - - // Fill bitreader to have enough for the remaining - CMPQ BX, $0x08 - JL sequenceDecs_decode_bmi2_fill_2_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R13 - MOVQ (R13), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decode_bmi2_fill_2_end - -sequenceDecs_decode_bmi2_fill_2_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decode_bmi2_fill_2_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decode_bmi2_fill_2_end - SHLQ $0x08, AX - SUBQ $0x01, R13 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R13), CX - ORQ CX, AX - JMP sequenceDecs_decode_bmi2_fill_2_byte_by_byte - -sequenceDecs_decode_bmi2_fill_2_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decode_bmi2_fill_2_end: - // Update literal length - MOVQ $0x00000808, CX - BEXTRQ CX, SI, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ SI, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, (R9) - - // Fill bitreader for state updates - MOVQ R13, (SP) - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R13 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decode_bmi2_skip_update - LEAQ (SI)(DI*1), R14 - ADDQ R8, R14 - MOVBQZX R14, R14 - LEAQ (DX)(R14*1), CX - MOVQ AX, R15 - MOVQ CX, DX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - - // Update Offset State - BZHIQ R8, R15, CX - SHRXQ R8, R15, R15 - SHRL $0x10, R8 - ADDQ CX, R8 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Match Length State - BZHIQ DI, R15, CX - SHRXQ DI, R15, R15 - SHRL $0x10, DI - ADDQ CX, DI - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(DI*8), DI - - // Update Literal Length State - BZHIQ SI, R15, CX - SHRL $0x10, SI - ADDQ CX, SI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(SI*8), SI - -sequenceDecs_decode_bmi2_skip_update: - // Adjust offset - MOVQ 16(R9), CX - CMPQ R13, $0x01 - JBE sequenceDecs_decode_bmi2_adjust_offsetB_1_or_0 - MOVQ R11, R12 - MOVQ R10, R11 - MOVQ CX, R10 - JMP sequenceDecs_decode_bmi2_after_adjust - -sequenceDecs_decode_bmi2_adjust_offsetB_1_or_0: - CMPQ (R9), $0x00000000 - JNE sequenceDecs_decode_bmi2_adjust_offset_maybezero - INCQ CX - JMP sequenceDecs_decode_bmi2_adjust_offset_nonzero - -sequenceDecs_decode_bmi2_adjust_offset_maybezero: - TESTQ CX, CX - JNZ sequenceDecs_decode_bmi2_adjust_offset_nonzero - MOVQ R10, CX - JMP sequenceDecs_decode_bmi2_after_adjust - -sequenceDecs_decode_bmi2_adjust_offset_nonzero: - CMPQ CX, $0x01 - JB sequenceDecs_decode_bmi2_adjust_zero - JEQ sequenceDecs_decode_bmi2_adjust_one - CMPQ CX, $0x02 - JA sequenceDecs_decode_bmi2_adjust_three - JMP sequenceDecs_decode_bmi2_adjust_two - -sequenceDecs_decode_bmi2_adjust_zero: - MOVQ R10, R13 - JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_bmi2_adjust_one: - MOVQ R11, R13 - JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_bmi2_adjust_two: - MOVQ R12, R13 - JMP sequenceDecs_decode_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_bmi2_adjust_three: - LEAQ -1(R10), R13 - -sequenceDecs_decode_bmi2_adjust_test_temp_valid: - TESTQ R13, R13 - JNZ sequenceDecs_decode_bmi2_adjust_temp_valid - MOVQ $0x00000001, R13 - -sequenceDecs_decode_bmi2_adjust_temp_valid: - CMPQ CX, $0x01 - CMOVQNE R11, R12 - MOVQ R10, R11 - MOVQ R13, R10 - MOVQ R13, CX - -sequenceDecs_decode_bmi2_after_adjust: - MOVQ CX, 16(R9) - - // Check values - MOVQ 8(R9), R13 - MOVQ (R9), R14 - LEAQ (R13)(R14*1), R15 - MOVQ s+0(FP), BP - ADDQ R15, 256(BP) - MOVQ ctx+16(FP), R15 - SUBQ R14, 128(R15) - JS error_not_enough_literals - CMPQ R13, $0x00020002 - JA sequenceDecs_decode_bmi2_error_match_len_too_big - TESTQ CX, CX - JNZ sequenceDecs_decode_bmi2_match_len_ofs_ok - TESTQ R13, R13 - JNZ sequenceDecs_decode_bmi2_error_match_len_ofs_mismatch - -sequenceDecs_decode_bmi2_match_len_ofs_ok: - ADDQ $0x18, R9 - MOVQ ctx+16(FP), CX - DECQ 96(CX) - JNS sequenceDecs_decode_bmi2_main_loop - MOVQ s+0(FP), CX - MOVQ R10, 144(CX) - MOVQ R11, 152(CX) - MOVQ R12, 160(CX) - MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decode_bmi2_error_match_len_ofs_mismatch: - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decode_bmi2_error_match_len_too_big: - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - -// func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int -// Requires: BMI, BMI2, CMOV -TEXT ·sequenceDecs_decode_56_bmi2(SB), $8-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX - ADDQ BX, CX - MOVQ CX, (SP) - MOVQ ctx+16(FP), CX - MOVQ 72(CX), SI - MOVQ 80(CX), DI - MOVQ 88(CX), R8 - MOVQ 104(CX), R9 - MOVQ s+0(FP), CX - MOVQ 144(CX), R10 - MOVQ 152(CX), R11 - MOVQ 160(CX), R12 - -sequenceDecs_decode_56_bmi2_main_loop: - MOVQ (SP), R13 - - // Fill bitreader to have enough for the offset and match length. - CMPQ BX, $0x08 - JL sequenceDecs_decode_56_bmi2_fill_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R13 - MOVQ (R13), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decode_56_bmi2_fill_end - -sequenceDecs_decode_56_bmi2_fill_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decode_56_bmi2_fill_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decode_56_bmi2_fill_end - SHLQ $0x08, AX - SUBQ $0x01, R13 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R13), CX - ORQ CX, AX - JMP sequenceDecs_decode_56_bmi2_fill_byte_by_byte - -sequenceDecs_decode_56_bmi2_fill_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decode_56_bmi2_fill_end: - // Update offset - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ R8, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, 16(R9) - - // Update match length - MOVQ $0x00000808, CX - BEXTRQ CX, DI, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ DI, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, 8(R9) - - // Update literal length - MOVQ $0x00000808, CX - BEXTRQ CX, SI, R14 - MOVQ AX, R15 - LEAQ (DX)(R14*1), CX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - MOVQ CX, DX - MOVQ SI, CX - SHRQ $0x20, CX - ADDQ R15, CX - MOVQ CX, (R9) - - // Fill bitreader for state updates - MOVQ R13, (SP) - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R13 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decode_56_bmi2_skip_update - LEAQ (SI)(DI*1), R14 - ADDQ R8, R14 - MOVBQZX R14, R14 - LEAQ (DX)(R14*1), CX - MOVQ AX, R15 - MOVQ CX, DX - ROLQ CL, R15 - BZHIQ R14, R15, R15 - - // Update Offset State - BZHIQ R8, R15, CX - SHRXQ R8, R15, R15 - SHRL $0x10, R8 - ADDQ CX, R8 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Match Length State - BZHIQ DI, R15, CX - SHRXQ DI, R15, R15 - SHRL $0x10, DI - ADDQ CX, DI - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(DI*8), DI - - // Update Literal Length State - BZHIQ SI, R15, CX - SHRL $0x10, SI - ADDQ CX, SI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(SI*8), SI - -sequenceDecs_decode_56_bmi2_skip_update: - // Adjust offset - MOVQ 16(R9), CX - CMPQ R13, $0x01 - JBE sequenceDecs_decode_56_bmi2_adjust_offsetB_1_or_0 - MOVQ R11, R12 - MOVQ R10, R11 - MOVQ CX, R10 - JMP sequenceDecs_decode_56_bmi2_after_adjust - -sequenceDecs_decode_56_bmi2_adjust_offsetB_1_or_0: - CMPQ (R9), $0x00000000 - JNE sequenceDecs_decode_56_bmi2_adjust_offset_maybezero - INCQ CX - JMP sequenceDecs_decode_56_bmi2_adjust_offset_nonzero - -sequenceDecs_decode_56_bmi2_adjust_offset_maybezero: - TESTQ CX, CX - JNZ sequenceDecs_decode_56_bmi2_adjust_offset_nonzero - MOVQ R10, CX - JMP sequenceDecs_decode_56_bmi2_after_adjust - -sequenceDecs_decode_56_bmi2_adjust_offset_nonzero: - CMPQ CX, $0x01 - JB sequenceDecs_decode_56_bmi2_adjust_zero - JEQ sequenceDecs_decode_56_bmi2_adjust_one - CMPQ CX, $0x02 - JA sequenceDecs_decode_56_bmi2_adjust_three - JMP sequenceDecs_decode_56_bmi2_adjust_two - -sequenceDecs_decode_56_bmi2_adjust_zero: - MOVQ R10, R13 - JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_56_bmi2_adjust_one: - MOVQ R11, R13 - JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_56_bmi2_adjust_two: - MOVQ R12, R13 - JMP sequenceDecs_decode_56_bmi2_adjust_test_temp_valid - -sequenceDecs_decode_56_bmi2_adjust_three: - LEAQ -1(R10), R13 - -sequenceDecs_decode_56_bmi2_adjust_test_temp_valid: - TESTQ R13, R13 - JNZ sequenceDecs_decode_56_bmi2_adjust_temp_valid - MOVQ $0x00000001, R13 - -sequenceDecs_decode_56_bmi2_adjust_temp_valid: - CMPQ CX, $0x01 - CMOVQNE R11, R12 - MOVQ R10, R11 - MOVQ R13, R10 - MOVQ R13, CX - -sequenceDecs_decode_56_bmi2_after_adjust: - MOVQ CX, 16(R9) - - // Check values - MOVQ 8(R9), R13 - MOVQ (R9), R14 - LEAQ (R13)(R14*1), R15 - MOVQ s+0(FP), BP - ADDQ R15, 256(BP) - MOVQ ctx+16(FP), R15 - SUBQ R14, 128(R15) - JS error_not_enough_literals - CMPQ R13, $0x00020002 - JA sequenceDecs_decode_56_bmi2_error_match_len_too_big - TESTQ CX, CX - JNZ sequenceDecs_decode_56_bmi2_match_len_ofs_ok - TESTQ R13, R13 - JNZ sequenceDecs_decode_56_bmi2_error_match_len_ofs_mismatch - -sequenceDecs_decode_56_bmi2_match_len_ofs_ok: - ADDQ $0x18, R9 - MOVQ ctx+16(FP), CX - DECQ 96(CX) - JNS sequenceDecs_decode_56_bmi2_main_loop - MOVQ s+0(FP), CX - MOVQ R10, 144(CX) - MOVQ R11, 152(CX) - MOVQ R12, 160(CX) - MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decode_56_bmi2_error_match_len_ofs_mismatch: - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decode_56_bmi2_error_match_len_too_big: - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - -// func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool -// Requires: SSE -TEXT ·sequenceDecs_executeSimple_amd64(SB), $8-9 - MOVQ ctx+0(FP), R10 - MOVQ 8(R10), CX - TESTQ CX, CX - JZ empty_seqs - MOVQ (R10), AX - MOVQ 24(R10), DX - MOVQ 32(R10), BX - MOVQ 80(R10), SI - MOVQ 104(R10), DI - MOVQ 120(R10), R8 - MOVQ 56(R10), R9 - MOVQ 64(R10), R10 - ADDQ R10, R9 - - // seqsBase += 24 * seqIndex - LEAQ (DX)(DX*2), R11 - SHLQ $0x03, R11 - ADDQ R11, AX - - // outBase += outPosition - ADDQ DI, BX - -main_loop: - MOVQ (AX), R11 - MOVQ 16(AX), R12 - MOVQ 8(AX), R13 - - // Copy literals - TESTQ R11, R11 - JZ check_offset - XORQ R14, R14 - -copy_1: - MOVUPS (SI)(R14*1), X0 - MOVUPS X0, (BX)(R14*1) - ADDQ $0x10, R14 - CMPQ R14, R11 - JB copy_1 - ADDQ R11, SI - ADDQ R11, BX - ADDQ R11, DI - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - LEAQ (DI)(R10*1), R11 - CMPQ R12, R11 - JG error_match_off_too_big - CMPQ R12, R8 - JG error_match_off_too_big - - // Copy match from history - MOVQ R12, R11 - SUBQ DI, R11 - JLS copy_match - MOVQ R9, R14 - SUBQ R11, R14 - CMPQ R13, R11 - JG copy_all_from_history - MOVQ R13, R11 - SUBQ $0x10, R11 - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R14 - ADDQ $0x10, BX - SUBQ $0x10, R11 - JAE copy_4_loop - LEAQ 16(R14)(R11*1), R14 - LEAQ 16(BX)(R11*1), BX - MOVUPS -16(R14), X0 - MOVUPS X0, -16(BX) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), R11 - MOVB 2(R14), R12 - MOVW R11, (BX) - MOVB R12, 2(BX) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), R11 - MOVL -4(R14)(R13*1), R12 - MOVL R11, (BX) - MOVL R12, -4(BX)(R13*1) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), R11 - MOVQ -8(R14)(R13*1), R12 - MOVQ R11, (BX) - MOVQ R12, -8(BX)(R13*1) - ADDQ R13, R14 - ADDQ R13, BX - -copy_4_end: - ADDQ R13, DI - ADDQ $0x18, AX - INCQ DX - CMPQ DX, CX - JB main_loop - JMP loop_finished - -copy_all_from_history: - MOVQ R11, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R14 - ADDQ $0x10, BX - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(BX)(R15*1), BX - MOVUPS -16(R14), X0 - MOVUPS X0, -16(BX) - JMP copy_5_end - -copy_5_small: - CMPQ R11, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ R11, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(R11*1), BP - MOVB R15, (BX) - MOVB BP, -1(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (BX) - MOVB BP, 2(BX) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(R11*1), BP - MOVL R15, (BX) - MOVL BP, -4(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(R11*1), BP - MOVQ R15, (BX) - MOVQ BP, -8(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - -copy_5_end: - ADDQ R11, DI - SUBQ R11, R13 - - // Copy match from the current buffer -copy_match: - MOVQ BX, R11 - SUBQ R12, R11 - - // ml <= mo - CMPQ R13, R12 - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, DI - MOVQ BX, R12 - ADDQ R13, BX - -copy_2: - MOVUPS (R11), X0 - MOVUPS X0, (R12) - ADDQ $0x10, R11 - ADDQ $0x10, R12 - SUBQ $0x10, R13 - JHI copy_2 - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, DI - -copy_slow_3: - MOVB (R11), R12 - MOVB R12, (BX) - INCQ R11 - INCQ BX - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - ADDQ $0x18, AX - INCQ DX - CMPQ DX, CX - JB main_loop - -loop_finished: - // Return value - MOVB $0x01, ret+8(FP) - - // Update the context - MOVQ ctx+0(FP), AX - MOVQ DX, 24(AX) - MOVQ DI, 104(AX) - SUBQ 80(AX), SI - MOVQ SI, 112(AX) - RET - -error_match_off_too_big: - // Return value - MOVB $0x00, ret+8(FP) - - // Update the context - MOVQ ctx+0(FP), AX - MOVQ DX, 24(AX) - MOVQ DI, 104(AX) - SUBQ 80(AX), SI - MOVQ SI, 112(AX) - RET - -empty_seqs: - // Return value - MOVB $0x01, ret+8(FP) - RET - -// func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool -// Requires: SSE -TEXT ·sequenceDecs_executeSimple_safe_amd64(SB), $8-9 - MOVQ ctx+0(FP), R10 - MOVQ 8(R10), CX - TESTQ CX, CX - JZ empty_seqs - MOVQ (R10), AX - MOVQ 24(R10), DX - MOVQ 32(R10), BX - MOVQ 80(R10), SI - MOVQ 104(R10), DI - MOVQ 120(R10), R8 - MOVQ 56(R10), R9 - MOVQ 64(R10), R10 - ADDQ R10, R9 - - // seqsBase += 24 * seqIndex - LEAQ (DX)(DX*2), R11 - SHLQ $0x03, R11 - ADDQ R11, AX - - // outBase += outPosition - ADDQ DI, BX - -main_loop: - MOVQ (AX), R11 - MOVQ 16(AX), R12 - MOVQ 8(AX), R13 - - // Copy literals - TESTQ R11, R11 - JZ check_offset - MOVQ R11, R14 - SUBQ $0x10, R14 - JB copy_1_small - -copy_1_loop: - MOVUPS (SI), X0 - MOVUPS X0, (BX) - ADDQ $0x10, SI - ADDQ $0x10, BX - SUBQ $0x10, R14 - JAE copy_1_loop - LEAQ 16(SI)(R14*1), SI - LEAQ 16(BX)(R14*1), BX - MOVUPS -16(SI), X0 - MOVUPS X0, -16(BX) - JMP copy_1_end - -copy_1_small: - CMPQ R11, $0x03 - JE copy_1_move_3 - JB copy_1_move_1or2 - CMPQ R11, $0x08 - JB copy_1_move_4through7 - JMP copy_1_move_8through16 - -copy_1_move_1or2: - MOVB (SI), R14 - MOVB -1(SI)(R11*1), R15 - MOVB R14, (BX) - MOVB R15, -1(BX)(R11*1) - ADDQ R11, SI - ADDQ R11, BX - JMP copy_1_end - -copy_1_move_3: - MOVW (SI), R14 - MOVB 2(SI), R15 - MOVW R14, (BX) - MOVB R15, 2(BX) - ADDQ R11, SI - ADDQ R11, BX - JMP copy_1_end - -copy_1_move_4through7: - MOVL (SI), R14 - MOVL -4(SI)(R11*1), R15 - MOVL R14, (BX) - MOVL R15, -4(BX)(R11*1) - ADDQ R11, SI - ADDQ R11, BX - JMP copy_1_end - -copy_1_move_8through16: - MOVQ (SI), R14 - MOVQ -8(SI)(R11*1), R15 - MOVQ R14, (BX) - MOVQ R15, -8(BX)(R11*1) - ADDQ R11, SI - ADDQ R11, BX - -copy_1_end: - ADDQ R11, DI - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - LEAQ (DI)(R10*1), R11 - CMPQ R12, R11 - JG error_match_off_too_big - CMPQ R12, R8 - JG error_match_off_too_big - - // Copy match from history - MOVQ R12, R11 - SUBQ DI, R11 - JLS copy_match - MOVQ R9, R14 - SUBQ R11, R14 - CMPQ R13, R11 - JG copy_all_from_history - MOVQ R13, R11 - SUBQ $0x10, R11 - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R14 - ADDQ $0x10, BX - SUBQ $0x10, R11 - JAE copy_4_loop - LEAQ 16(R14)(R11*1), R14 - LEAQ 16(BX)(R11*1), BX - MOVUPS -16(R14), X0 - MOVUPS X0, -16(BX) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), R11 - MOVB 2(R14), R12 - MOVW R11, (BX) - MOVB R12, 2(BX) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), R11 - MOVL -4(R14)(R13*1), R12 - MOVL R11, (BX) - MOVL R12, -4(BX)(R13*1) - ADDQ R13, R14 - ADDQ R13, BX - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), R11 - MOVQ -8(R14)(R13*1), R12 - MOVQ R11, (BX) - MOVQ R12, -8(BX)(R13*1) - ADDQ R13, R14 - ADDQ R13, BX - -copy_4_end: - ADDQ R13, DI - ADDQ $0x18, AX - INCQ DX - CMPQ DX, CX - JB main_loop - JMP loop_finished - -copy_all_from_history: - MOVQ R11, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R14 - ADDQ $0x10, BX - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(BX)(R15*1), BX - MOVUPS -16(R14), X0 - MOVUPS X0, -16(BX) - JMP copy_5_end - -copy_5_small: - CMPQ R11, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ R11, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(R11*1), BP - MOVB R15, (BX) - MOVB BP, -1(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (BX) - MOVB BP, 2(BX) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(R11*1), BP - MOVL R15, (BX) - MOVL BP, -4(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(R11*1), BP - MOVQ R15, (BX) - MOVQ BP, -8(BX)(R11*1) - ADDQ R11, R14 - ADDQ R11, BX - -copy_5_end: - ADDQ R11, DI - SUBQ R11, R13 - - // Copy match from the current buffer -copy_match: - MOVQ BX, R11 - SUBQ R12, R11 - - // ml <= mo - CMPQ R13, R12 - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, DI - MOVQ R13, R12 - SUBQ $0x10, R12 - JB copy_2_small - -copy_2_loop: - MOVUPS (R11), X0 - MOVUPS X0, (BX) - ADDQ $0x10, R11 - ADDQ $0x10, BX - SUBQ $0x10, R12 - JAE copy_2_loop - LEAQ 16(R11)(R12*1), R11 - LEAQ 16(BX)(R12*1), BX - MOVUPS -16(R11), X0 - MOVUPS X0, -16(BX) - JMP copy_2_end - -copy_2_small: - CMPQ R13, $0x03 - JE copy_2_move_3 - JB copy_2_move_1or2 - CMPQ R13, $0x08 - JB copy_2_move_4through7 - JMP copy_2_move_8through16 - -copy_2_move_1or2: - MOVB (R11), R12 - MOVB -1(R11)(R13*1), R14 - MOVB R12, (BX) - MOVB R14, -1(BX)(R13*1) - ADDQ R13, R11 - ADDQ R13, BX - JMP copy_2_end - -copy_2_move_3: - MOVW (R11), R12 - MOVB 2(R11), R14 - MOVW R12, (BX) - MOVB R14, 2(BX) - ADDQ R13, R11 - ADDQ R13, BX - JMP copy_2_end - -copy_2_move_4through7: - MOVL (R11), R12 - MOVL -4(R11)(R13*1), R14 - MOVL R12, (BX) - MOVL R14, -4(BX)(R13*1) - ADDQ R13, R11 - ADDQ R13, BX - JMP copy_2_end - -copy_2_move_8through16: - MOVQ (R11), R12 - MOVQ -8(R11)(R13*1), R14 - MOVQ R12, (BX) - MOVQ R14, -8(BX)(R13*1) - ADDQ R13, R11 - ADDQ R13, BX - -copy_2_end: - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, DI - -copy_slow_3: - MOVB (R11), R12 - MOVB R12, (BX) - INCQ R11 - INCQ BX - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - ADDQ $0x18, AX - INCQ DX - CMPQ DX, CX - JB main_loop - -loop_finished: - // Return value - MOVB $0x01, ret+8(FP) - - // Update the context - MOVQ ctx+0(FP), AX - MOVQ DX, 24(AX) - MOVQ DI, 104(AX) - SUBQ 80(AX), SI - MOVQ SI, 112(AX) - RET - -error_match_off_too_big: - // Return value - MOVB $0x00, ret+8(FP) - - // Update the context - MOVQ ctx+0(FP), AX - MOVQ DX, 24(AX) - MOVQ DI, 104(AX) - SUBQ 80(AX), SI - MOVQ SI, 112(AX) - RET - -empty_seqs: - // Return value - MOVB $0x01, ret+8(FP) - RET - -// func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int -// Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_amd64(SB), $64-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI - ADDQ SI, AX - MOVQ AX, (SP) - MOVQ ctx+16(FP), AX - MOVQ 72(AX), DI - MOVQ 80(AX), R8 - MOVQ 88(AX), R9 - XORQ CX, CX - MOVQ CX, 8(SP) - MOVQ CX, 16(SP) - MOVQ CX, 24(SP) - MOVQ 112(AX), R10 - MOVQ 128(AX), CX - MOVQ CX, 32(SP) - MOVQ 144(AX), R11 - MOVQ 136(AX), R12 - MOVQ 200(AX), CX - MOVQ CX, 56(SP) - MOVQ 176(AX), CX - MOVQ CX, 48(SP) - MOVQ 184(AX), AX - MOVQ AX, 40(SP) - MOVQ 40(SP), AX - ADDQ AX, 48(SP) - - // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) - ADDQ R10, 32(SP) - - // outBase += outPosition - ADDQ R12, R10 - -sequenceDecs_decodeSync_amd64_main_loop: - MOVQ (SP), R13 - - // Fill bitreader to have enough for the offset and match length. - CMPQ SI, $0x08 - JL sequenceDecs_decodeSync_amd64_fill_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R13 - MOVQ (R13), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decodeSync_amd64_fill_end - -sequenceDecs_decodeSync_amd64_fill_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decodeSync_amd64_fill_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decodeSync_amd64_fill_end - SHLQ $0x08, DX - SUBQ $0x01, R13 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R13), AX - ORQ AX, DX - JMP sequenceDecs_decodeSync_amd64_fill_byte_by_byte - -sequenceDecs_decodeSync_amd64_fill_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_amd64_fill_end: - // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_of_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_of_update_zero: - MOVQ AX, 8(SP) - - // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_ml_update_zero: - MOVQ AX, 16(SP) - - // Fill bitreader to have enough for the remaining - CMPQ SI, $0x08 - JL sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R13 - MOVQ (R13), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decodeSync_amd64_fill_2_end - -sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decodeSync_amd64_fill_2_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decodeSync_amd64_fill_2_end - SHLQ $0x08, DX - SUBQ $0x01, R13 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R13), AX - ORQ AX, DX - JMP sequenceDecs_decodeSync_amd64_fill_2_byte_by_byte - -sequenceDecs_decodeSync_amd64_fill_2_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_amd64_fill_2_end: - // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_amd64_ll_update_zero: - MOVQ AX, 24(SP) - - // Fill bitreader for state updates - MOVQ R13, (SP) - MOVQ R9, AX - SHRQ $0x08, AX - MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decodeSync_amd64_skip_update - - // Update Literal Length State - MOVBQZX DI, R13 - SHRL $0x10, DI - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, DI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(DI*8), DI - - // Update Match Length State - MOVBQZX R8, R13 - SHRL $0x10, R8 - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, R8 - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Offset State - MOVBQZX R9, R13 - SHRL $0x10, R9 - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, R9 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R9*8), R9 - -sequenceDecs_decodeSync_amd64_skip_update: - // Adjust offset - MOVQ s+0(FP), CX - MOVQ 8(SP), R13 - CMPQ AX, $0x01 - JBE sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0 - MOVUPS 144(CX), X0 - MOVQ R13, 144(CX) - MOVUPS X0, 152(CX) - JMP sequenceDecs_decodeSync_amd64_after_adjust - -sequenceDecs_decodeSync_amd64_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 - JNE sequenceDecs_decodeSync_amd64_adjust_offset_maybezero - INCQ R13 - JMP sequenceDecs_decodeSync_amd64_adjust_offset_nonzero - -sequenceDecs_decodeSync_amd64_adjust_offset_maybezero: - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_amd64_adjust_offset_nonzero - MOVQ 144(CX), R13 - JMP sequenceDecs_decodeSync_amd64_after_adjust - -sequenceDecs_decodeSync_amd64_adjust_offset_nonzero: - MOVQ R13, AX - XORQ R14, R14 - MOVQ $-1, R15 - CMPQ R13, $0x03 - CMOVQEQ R14, AX - CMOVQEQ R15, R14 - ADDQ 144(CX)(AX*8), R14 - JNZ sequenceDecs_decodeSync_amd64_adjust_temp_valid - MOVQ $0x00000001, R14 - -sequenceDecs_decodeSync_amd64_adjust_temp_valid: - CMPQ R13, $0x01 - JZ sequenceDecs_decodeSync_amd64_adjust_skip - MOVQ 152(CX), AX - MOVQ AX, 160(CX) - -sequenceDecs_decodeSync_amd64_adjust_skip: - MOVQ 144(CX), AX - MOVQ AX, 152(CX) - MOVQ R14, 144(CX) - MOVQ R14, R13 - -sequenceDecs_decodeSync_amd64_after_adjust: - MOVQ R13, 8(SP) - - // Check values - MOVQ 16(SP), AX - MOVQ 24(SP), CX - LEAQ (AX)(CX*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) - MOVQ ctx+16(FP), R14 - SUBQ CX, 104(R14) - JS error_not_enough_literals - CMPQ AX, $0x00020002 - JA sequenceDecs_decodeSync_amd64_error_match_len_too_big - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_amd64_match_len_ofs_ok - TESTQ AX, AX - JNZ sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch - -sequenceDecs_decodeSync_amd64_match_len_ofs_ok: - MOVQ 24(SP), AX - MOVQ 8(SP), CX - MOVQ 16(SP), R13 - - // Check if we have enough space in s.out - LEAQ (AX)(R13*1), R14 - ADDQ R10, R14 - CMPQ R14, 32(SP) - JA error_not_enough_space - - // Copy literals - TESTQ AX, AX - JZ check_offset - XORQ R14, R14 - -copy_1: - MOVUPS (R11)(R14*1), X0 - MOVUPS X0, (R10)(R14*1) - ADDQ $0x10, R14 - CMPQ R14, AX - JB copy_1 - ADDQ AX, R11 - ADDQ AX, R10 - ADDQ AX, R12 - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R12, AX - ADDQ 40(SP), AX - CMPQ CX, AX - JG error_match_off_too_big - CMPQ CX, 56(SP) - JG error_match_off_too_big - - // Copy match from history - MOVQ CX, AX - SUBQ R12, AX - JLS copy_match - MOVQ 48(SP), R14 - SUBQ AX, R14 - CMPQ R13, AX - JG copy_all_from_history - MOVQ R13, AX - SUBQ $0x10, AX - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R14 - ADDQ $0x10, R10 - SUBQ $0x10, AX - JAE copy_4_loop - LEAQ 16(R14)(AX*1), R14 - LEAQ 16(R10)(AX*1), R10 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R10) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), AX - MOVB 2(R14), CL - MOVW AX, (R10) - MOVB CL, 2(R10) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), AX - MOVL -4(R14)(R13*1), CX - MOVL AX, (R10) - MOVL CX, -4(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), AX - MOVQ -8(R14)(R13*1), CX - MOVQ AX, (R10) - MOVQ CX, -8(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 - -copy_4_end: - ADDQ R13, R12 - JMP handle_loop - JMP loop_finished - -copy_all_from_history: - MOVQ AX, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R14 - ADDQ $0x10, R10 - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(R10)(R15*1), R10 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R10) - JMP copy_5_end - -copy_5_small: - CMPQ AX, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ AX, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(AX*1), BP - MOVB R15, (R10) - MOVB BP, -1(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R10) - MOVB BP, 2(R10) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(AX*1), BP - MOVL R15, (R10) - MOVL BP, -4(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(AX*1), BP - MOVQ R15, (R10) - MOVQ BP, -8(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - -copy_5_end: - ADDQ AX, R12 - SUBQ AX, R13 - - // Copy match from the current buffer -copy_match: - MOVQ R10, AX - SUBQ CX, AX - - // ml <= mo - CMPQ R13, CX - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, R12 - MOVQ R10, CX - ADDQ R13, R10 - -copy_2: - MOVUPS (AX), X0 - MOVUPS X0, (CX) - ADDQ $0x10, AX - ADDQ $0x10, CX - SUBQ $0x10, R13 - JHI copy_2 - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, R12 - -copy_slow_3: - MOVB (AX), CL - MOVB CL, (R10) - INCQ AX - INCQ R10 - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - MOVQ ctx+16(FP), AX - DECQ 96(AX) - JNS sequenceDecs_decodeSync_amd64_main_loop - -loop_finished: - MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) - - // Update the context - MOVQ ctx+16(FP), AX - MOVQ R12, 136(AX) - MOVQ 144(AX), CX - SUBQ CX, R11 - MOVQ R11, 168(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decodeSync_amd64_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX - MOVQ ctx+16(FP), CX - MOVQ AX, 216(CX) - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decodeSync_amd64_error_match_len_too_big: - MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error -error_match_off_too_big: - MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX - MOVQ CX, 224(AX) - MOVQ R12, 136(AX) - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - - // Return with not enough output space error -error_not_enough_space: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ R12, 136(AX) - MOVQ $0x00000005, ret+24(FP) - RET - -// func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int -// Requires: BMI, BMI2, CMOV, SSE -TEXT ·sequenceDecs_decodeSync_bmi2(SB), $64-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX - ADDQ BX, CX - MOVQ CX, (SP) - MOVQ ctx+16(FP), CX - MOVQ 72(CX), SI - MOVQ 80(CX), DI - MOVQ 88(CX), R8 - XORQ R9, R9 - MOVQ R9, 8(SP) - MOVQ R9, 16(SP) - MOVQ R9, 24(SP) - MOVQ 112(CX), R9 - MOVQ 128(CX), R10 - MOVQ R10, 32(SP) - MOVQ 144(CX), R10 - MOVQ 136(CX), R11 - MOVQ 200(CX), R12 - MOVQ R12, 56(SP) - MOVQ 176(CX), R12 - MOVQ R12, 48(SP) - MOVQ 184(CX), CX - MOVQ CX, 40(SP) - MOVQ 40(SP), CX - ADDQ CX, 48(SP) - - // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) - ADDQ R9, 32(SP) - - // outBase += outPosition - ADDQ R11, R9 - -sequenceDecs_decodeSync_bmi2_main_loop: - MOVQ (SP), R12 - - // Fill bitreader to have enough for the offset and match length. - CMPQ BX, $0x08 - JL sequenceDecs_decodeSync_bmi2_fill_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R12 - MOVQ (R12), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decodeSync_bmi2_fill_end - -sequenceDecs_decodeSync_bmi2_fill_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decodeSync_bmi2_fill_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decodeSync_bmi2_fill_end - SHLQ $0x08, AX - SUBQ $0x01, R12 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R12), CX - ORQ CX, AX - JMP sequenceDecs_decodeSync_bmi2_fill_byte_by_byte - -sequenceDecs_decodeSync_bmi2_fill_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_bmi2_fill_end: - // Update offset - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ R8, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 8(SP) - - // Update match length - MOVQ $0x00000808, CX - BEXTRQ CX, DI, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ DI, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 16(SP) - - // Fill bitreader to have enough for the remaining - CMPQ BX, $0x08 - JL sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R12 - MOVQ (R12), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decodeSync_bmi2_fill_2_end - -sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decodeSync_bmi2_fill_2_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decodeSync_bmi2_fill_2_end - SHLQ $0x08, AX - SUBQ $0x01, R12 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R12), CX - ORQ CX, AX - JMP sequenceDecs_decodeSync_bmi2_fill_2_byte_by_byte - -sequenceDecs_decodeSync_bmi2_fill_2_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_bmi2_fill_2_end: - // Update literal length - MOVQ $0x00000808, CX - BEXTRQ CX, SI, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ SI, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 24(SP) - - // Fill bitreader for state updates - MOVQ R12, (SP) - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R12 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decodeSync_bmi2_skip_update - LEAQ (SI)(DI*1), R13 - ADDQ R8, R13 - MOVBQZX R13, R13 - LEAQ (DX)(R13*1), CX - MOVQ AX, R14 - MOVQ CX, DX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - - // Update Offset State - BZHIQ R8, R14, CX - SHRXQ R8, R14, R14 - SHRL $0x10, R8 - ADDQ CX, R8 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Match Length State - BZHIQ DI, R14, CX - SHRXQ DI, R14, R14 - SHRL $0x10, DI - ADDQ CX, DI - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(DI*8), DI - - // Update Literal Length State - BZHIQ SI, R14, CX - SHRL $0x10, SI - ADDQ CX, SI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(SI*8), SI - -sequenceDecs_decodeSync_bmi2_skip_update: - // Adjust offset - MOVQ s+0(FP), CX - MOVQ 8(SP), R13 - CMPQ R12, $0x01 - JBE sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0 - MOVUPS 144(CX), X0 - MOVQ R13, 144(CX) - MOVUPS X0, 152(CX) - JMP sequenceDecs_decodeSync_bmi2_after_adjust - -sequenceDecs_decodeSync_bmi2_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 - JNE sequenceDecs_decodeSync_bmi2_adjust_offset_maybezero - INCQ R13 - JMP sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero - -sequenceDecs_decodeSync_bmi2_adjust_offset_maybezero: - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero - MOVQ 144(CX), R13 - JMP sequenceDecs_decodeSync_bmi2_after_adjust - -sequenceDecs_decodeSync_bmi2_adjust_offset_nonzero: - MOVQ R13, R12 - XORQ R14, R14 - MOVQ $-1, R15 - CMPQ R13, $0x03 - CMOVQEQ R14, R12 - CMOVQEQ R15, R14 - ADDQ 144(CX)(R12*8), R14 - JNZ sequenceDecs_decodeSync_bmi2_adjust_temp_valid - MOVQ $0x00000001, R14 - -sequenceDecs_decodeSync_bmi2_adjust_temp_valid: - CMPQ R13, $0x01 - JZ sequenceDecs_decodeSync_bmi2_adjust_skip - MOVQ 152(CX), R12 - MOVQ R12, 160(CX) - -sequenceDecs_decodeSync_bmi2_adjust_skip: - MOVQ 144(CX), R12 - MOVQ R12, 152(CX) - MOVQ R14, 144(CX) - MOVQ R14, R13 - -sequenceDecs_decodeSync_bmi2_after_adjust: - MOVQ R13, 8(SP) - - // Check values - MOVQ 16(SP), CX - MOVQ 24(SP), R12 - LEAQ (CX)(R12*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) - MOVQ ctx+16(FP), R14 - SUBQ R12, 104(R14) - JS error_not_enough_literals - CMPQ CX, $0x00020002 - JA sequenceDecs_decodeSync_bmi2_error_match_len_too_big - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_bmi2_match_len_ofs_ok - TESTQ CX, CX - JNZ sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch - -sequenceDecs_decodeSync_bmi2_match_len_ofs_ok: - MOVQ 24(SP), CX - MOVQ 8(SP), R12 - MOVQ 16(SP), R13 - - // Check if we have enough space in s.out - LEAQ (CX)(R13*1), R14 - ADDQ R9, R14 - CMPQ R14, 32(SP) - JA error_not_enough_space - - // Copy literals - TESTQ CX, CX - JZ check_offset - XORQ R14, R14 - -copy_1: - MOVUPS (R10)(R14*1), X0 - MOVUPS X0, (R9)(R14*1) - ADDQ $0x10, R14 - CMPQ R14, CX - JB copy_1 - ADDQ CX, R10 - ADDQ CX, R9 - ADDQ CX, R11 - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R11, CX - ADDQ 40(SP), CX - CMPQ R12, CX - JG error_match_off_too_big - CMPQ R12, 56(SP) - JG error_match_off_too_big - - // Copy match from history - MOVQ R12, CX - SUBQ R11, CX - JLS copy_match - MOVQ 48(SP), R14 - SUBQ CX, R14 - CMPQ R13, CX - JG copy_all_from_history - MOVQ R13, CX - SUBQ $0x10, CX - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R14 - ADDQ $0x10, R9 - SUBQ $0x10, CX - JAE copy_4_loop - LEAQ 16(R14)(CX*1), R14 - LEAQ 16(R9)(CX*1), R9 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R9) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), CX - MOVB 2(R14), R12 - MOVW CX, (R9) - MOVB R12, 2(R9) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), CX - MOVL -4(R14)(R13*1), R12 - MOVL CX, (R9) - MOVL R12, -4(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), CX - MOVQ -8(R14)(R13*1), R12 - MOVQ CX, (R9) - MOVQ R12, -8(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 - -copy_4_end: - ADDQ R13, R11 - JMP handle_loop - JMP loop_finished - -copy_all_from_history: - MOVQ CX, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R14 - ADDQ $0x10, R9 - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(R9)(R15*1), R9 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R9) - JMP copy_5_end - -copy_5_small: - CMPQ CX, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ CX, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(CX*1), BP - MOVB R15, (R9) - MOVB BP, -1(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R9) - MOVB BP, 2(R9) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(CX*1), BP - MOVL R15, (R9) - MOVL BP, -4(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(CX*1), BP - MOVQ R15, (R9) - MOVQ BP, -8(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - -copy_5_end: - ADDQ CX, R11 - SUBQ CX, R13 - - // Copy match from the current buffer -copy_match: - MOVQ R9, CX - SUBQ R12, CX - - // ml <= mo - CMPQ R13, R12 - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, R11 - MOVQ R9, R12 - ADDQ R13, R9 - -copy_2: - MOVUPS (CX), X0 - MOVUPS X0, (R12) - ADDQ $0x10, CX - ADDQ $0x10, R12 - SUBQ $0x10, R13 - JHI copy_2 - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, R11 - -copy_slow_3: - MOVB (CX), R12 - MOVB R12, (R9) - INCQ CX - INCQ R9 - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - MOVQ ctx+16(FP), CX - DECQ 96(CX) - JNS sequenceDecs_decodeSync_bmi2_main_loop - -loop_finished: - MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) - - // Update the context - MOVQ ctx+16(FP), AX - MOVQ R11, 136(AX) - MOVQ 144(AX), CX - SUBQ CX, R10 - MOVQ R10, 168(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decodeSync_bmi2_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX - MOVQ ctx+16(FP), CX - MOVQ AX, 216(CX) - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decodeSync_bmi2_error_match_len_too_big: - MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error -error_match_off_too_big: - MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX - MOVQ CX, 224(AX) - MOVQ R11, 136(AX) - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - - // Return with not enough output space error -error_not_enough_space: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ R11, 136(AX) - MOVQ $0x00000005, ret+24(FP) - RET - -// func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int -// Requires: CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $64-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI - ADDQ SI, AX - MOVQ AX, (SP) - MOVQ ctx+16(FP), AX - MOVQ 72(AX), DI - MOVQ 80(AX), R8 - MOVQ 88(AX), R9 - XORQ CX, CX - MOVQ CX, 8(SP) - MOVQ CX, 16(SP) - MOVQ CX, 24(SP) - MOVQ 112(AX), R10 - MOVQ 128(AX), CX - MOVQ CX, 32(SP) - MOVQ 144(AX), R11 - MOVQ 136(AX), R12 - MOVQ 200(AX), CX - MOVQ CX, 56(SP) - MOVQ 176(AX), CX - MOVQ CX, 48(SP) - MOVQ 184(AX), AX - MOVQ AX, 40(SP) - MOVQ 40(SP), AX - ADDQ AX, 48(SP) - - // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) - ADDQ R10, 32(SP) - - // outBase += outPosition - ADDQ R12, R10 - -sequenceDecs_decodeSync_safe_amd64_main_loop: - MOVQ (SP), R13 - - // Fill bitreader to have enough for the offset and match length. - CMPQ SI, $0x08 - JL sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R13 - MOVQ (R13), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decodeSync_safe_amd64_fill_end - -sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decodeSync_safe_amd64_fill_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decodeSync_safe_amd64_fill_end - SHLQ $0x08, DX - SUBQ $0x01, R13 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R13), AX - ORQ AX, DX - JMP sequenceDecs_decodeSync_safe_amd64_fill_byte_by_byte - -sequenceDecs_decodeSync_safe_amd64_fill_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_safe_amd64_fill_end: - // Update offset - MOVQ R9, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_of_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_of_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_of_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_of_update_zero: - MOVQ AX, 8(SP) - - // Update match length - MOVQ R8, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_ml_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_ml_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_ml_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_ml_update_zero: - MOVQ AX, 16(SP) - - // Fill bitreader to have enough for the remaining - CMPQ SI, $0x08 - JL sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte - MOVQ BX, AX - SHRQ $0x03, AX - SUBQ AX, R13 - MOVQ (R13), DX - SUBQ AX, SI - ANDQ $0x07, BX - JMP sequenceDecs_decodeSync_safe_amd64_fill_2_end - -sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte: - CMPQ SI, $0x00 - JLE sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread - CMPQ BX, $0x07 - JLE sequenceDecs_decodeSync_safe_amd64_fill_2_end - SHLQ $0x08, DX - SUBQ $0x01, R13 - SUBQ $0x01, SI - SUBQ $0x08, BX - MOVBQZX (R13), AX - ORQ AX, DX - JMP sequenceDecs_decodeSync_safe_amd64_fill_2_byte_by_byte - -sequenceDecs_decodeSync_safe_amd64_fill_2_check_overread: - CMPQ BX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_safe_amd64_fill_2_end: - // Update literal length - MOVQ DI, AX - MOVQ BX, CX - MOVQ DX, R14 - SHLQ CL, R14 - MOVB AH, CL - SHRQ $0x20, AX - TESTQ CX, CX - JZ sequenceDecs_decodeSync_safe_amd64_ll_update_zero - ADDQ CX, BX - CMPQ BX, $0x40 - JA sequenceDecs_decodeSync_safe_amd64_ll_update_zero - CMPQ CX, $0x40 - JAE sequenceDecs_decodeSync_safe_amd64_ll_update_zero - NEGQ CX - SHRQ CL, R14 - ADDQ R14, AX - -sequenceDecs_decodeSync_safe_amd64_ll_update_zero: - MOVQ AX, 24(SP) - - // Fill bitreader for state updates - MOVQ R13, (SP) - MOVQ R9, AX - SHRQ $0x08, AX - MOVBQZX AL, AX - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decodeSync_safe_amd64_skip_update - - // Update Literal Length State - MOVBQZX DI, R13 - SHRL $0x10, DI - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, DI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(DI*8), DI - - // Update Match Length State - MOVBQZX R8, R13 - SHRL $0x10, R8 - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, R8 - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Offset State - MOVBQZX R9, R13 - SHRL $0x10, R9 - LEAQ (BX)(R13*1), CX - MOVQ DX, R14 - MOVQ CX, BX - ROLQ CL, R14 - MOVL $0x00000001, R15 - MOVB R13, CL - SHLL CL, R15 - DECL R15 - ANDQ R15, R14 - ADDQ R14, R9 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R9*8), R9 - -sequenceDecs_decodeSync_safe_amd64_skip_update: - // Adjust offset - MOVQ s+0(FP), CX - MOVQ 8(SP), R13 - CMPQ AX, $0x01 - JBE sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0 - MOVUPS 144(CX), X0 - MOVQ R13, 144(CX) - MOVUPS X0, 152(CX) - JMP sequenceDecs_decodeSync_safe_amd64_after_adjust - -sequenceDecs_decodeSync_safe_amd64_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 - JNE sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero - INCQ R13 - JMP sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero - -sequenceDecs_decodeSync_safe_amd64_adjust_offset_maybezero: - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero - MOVQ 144(CX), R13 - JMP sequenceDecs_decodeSync_safe_amd64_after_adjust - -sequenceDecs_decodeSync_safe_amd64_adjust_offset_nonzero: - MOVQ R13, AX - XORQ R14, R14 - MOVQ $-1, R15 - CMPQ R13, $0x03 - CMOVQEQ R14, AX - CMOVQEQ R15, R14 - ADDQ 144(CX)(AX*8), R14 - JNZ sequenceDecs_decodeSync_safe_amd64_adjust_temp_valid - MOVQ $0x00000001, R14 - -sequenceDecs_decodeSync_safe_amd64_adjust_temp_valid: - CMPQ R13, $0x01 - JZ sequenceDecs_decodeSync_safe_amd64_adjust_skip - MOVQ 152(CX), AX - MOVQ AX, 160(CX) - -sequenceDecs_decodeSync_safe_amd64_adjust_skip: - MOVQ 144(CX), AX - MOVQ AX, 152(CX) - MOVQ R14, 144(CX) - MOVQ R14, R13 - -sequenceDecs_decodeSync_safe_amd64_after_adjust: - MOVQ R13, 8(SP) - - // Check values - MOVQ 16(SP), AX - MOVQ 24(SP), CX - LEAQ (AX)(CX*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) - MOVQ ctx+16(FP), R14 - SUBQ CX, 104(R14) - JS error_not_enough_literals - CMPQ AX, $0x00020002 - JA sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok - TESTQ AX, AX - JNZ sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch - -sequenceDecs_decodeSync_safe_amd64_match_len_ofs_ok: - MOVQ 24(SP), AX - MOVQ 8(SP), CX - MOVQ 16(SP), R13 - - // Check if we have enough space in s.out - LEAQ (AX)(R13*1), R14 - ADDQ R10, R14 - CMPQ R14, 32(SP) - JA error_not_enough_space - - // Copy literals - TESTQ AX, AX - JZ check_offset - MOVQ AX, R14 - SUBQ $0x10, R14 - JB copy_1_small - -copy_1_loop: - MOVUPS (R11), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R11 - ADDQ $0x10, R10 - SUBQ $0x10, R14 - JAE copy_1_loop - LEAQ 16(R11)(R14*1), R11 - LEAQ 16(R10)(R14*1), R10 - MOVUPS -16(R11), X0 - MOVUPS X0, -16(R10) - JMP copy_1_end - -copy_1_small: - CMPQ AX, $0x03 - JE copy_1_move_3 - JB copy_1_move_1or2 - CMPQ AX, $0x08 - JB copy_1_move_4through7 - JMP copy_1_move_8through16 - -copy_1_move_1or2: - MOVB (R11), R14 - MOVB -1(R11)(AX*1), R15 - MOVB R14, (R10) - MOVB R15, -1(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 - JMP copy_1_end - -copy_1_move_3: - MOVW (R11), R14 - MOVB 2(R11), R15 - MOVW R14, (R10) - MOVB R15, 2(R10) - ADDQ AX, R11 - ADDQ AX, R10 - JMP copy_1_end - -copy_1_move_4through7: - MOVL (R11), R14 - MOVL -4(R11)(AX*1), R15 - MOVL R14, (R10) - MOVL R15, -4(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 - JMP copy_1_end - -copy_1_move_8through16: - MOVQ (R11), R14 - MOVQ -8(R11)(AX*1), R15 - MOVQ R14, (R10) - MOVQ R15, -8(R10)(AX*1) - ADDQ AX, R11 - ADDQ AX, R10 - -copy_1_end: - ADDQ AX, R12 - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R12, AX - ADDQ 40(SP), AX - CMPQ CX, AX - JG error_match_off_too_big - CMPQ CX, 56(SP) - JG error_match_off_too_big - - // Copy match from history - MOVQ CX, AX - SUBQ R12, AX - JLS copy_match - MOVQ 48(SP), R14 - SUBQ AX, R14 - CMPQ R13, AX - JG copy_all_from_history - MOVQ R13, AX - SUBQ $0x10, AX - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R14 - ADDQ $0x10, R10 - SUBQ $0x10, AX - JAE copy_4_loop - LEAQ 16(R14)(AX*1), R14 - LEAQ 16(R10)(AX*1), R10 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R10) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), AX - MOVB 2(R14), CL - MOVW AX, (R10) - MOVB CL, 2(R10) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), AX - MOVL -4(R14)(R13*1), CX - MOVL AX, (R10) - MOVL CX, -4(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), AX - MOVQ -8(R14)(R13*1), CX - MOVQ AX, (R10) - MOVQ CX, -8(R10)(R13*1) - ADDQ R13, R14 - ADDQ R13, R10 - -copy_4_end: - ADDQ R13, R12 - JMP handle_loop - JMP loop_finished - -copy_all_from_history: - MOVQ AX, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R10) - ADDQ $0x10, R14 - ADDQ $0x10, R10 - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(R10)(R15*1), R10 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R10) - JMP copy_5_end - -copy_5_small: - CMPQ AX, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ AX, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(AX*1), BP - MOVB R15, (R10) - MOVB BP, -1(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R10) - MOVB BP, 2(R10) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(AX*1), BP - MOVL R15, (R10) - MOVL BP, -4(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(AX*1), BP - MOVQ R15, (R10) - MOVQ BP, -8(R10)(AX*1) - ADDQ AX, R14 - ADDQ AX, R10 - -copy_5_end: - ADDQ AX, R12 - SUBQ AX, R13 - - // Copy match from the current buffer -copy_match: - MOVQ R10, AX - SUBQ CX, AX - - // ml <= mo - CMPQ R13, CX - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, R12 - MOVQ R13, CX - SUBQ $0x10, CX - JB copy_2_small - -copy_2_loop: - MOVUPS (AX), X0 - MOVUPS X0, (R10) - ADDQ $0x10, AX - ADDQ $0x10, R10 - SUBQ $0x10, CX - JAE copy_2_loop - LEAQ 16(AX)(CX*1), AX - LEAQ 16(R10)(CX*1), R10 - MOVUPS -16(AX), X0 - MOVUPS X0, -16(R10) - JMP copy_2_end - -copy_2_small: - CMPQ R13, $0x03 - JE copy_2_move_3 - JB copy_2_move_1or2 - CMPQ R13, $0x08 - JB copy_2_move_4through7 - JMP copy_2_move_8through16 - -copy_2_move_1or2: - MOVB (AX), CL - MOVB -1(AX)(R13*1), R14 - MOVB CL, (R10) - MOVB R14, -1(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 - JMP copy_2_end - -copy_2_move_3: - MOVW (AX), CX - MOVB 2(AX), R14 - MOVW CX, (R10) - MOVB R14, 2(R10) - ADDQ R13, AX - ADDQ R13, R10 - JMP copy_2_end - -copy_2_move_4through7: - MOVL (AX), CX - MOVL -4(AX)(R13*1), R14 - MOVL CX, (R10) - MOVL R14, -4(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 - JMP copy_2_end - -copy_2_move_8through16: - MOVQ (AX), CX - MOVQ -8(AX)(R13*1), R14 - MOVQ CX, (R10) - MOVQ R14, -8(R10)(R13*1) - ADDQ R13, AX - ADDQ R13, R10 - -copy_2_end: - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, R12 - -copy_slow_3: - MOVB (AX), CL - MOVB CL, (R10) - INCQ AX - INCQ R10 - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - MOVQ ctx+16(FP), AX - DECQ 96(AX) - JNS sequenceDecs_decodeSync_safe_amd64_main_loop - -loop_finished: - MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) - - // Update the context - MOVQ ctx+16(FP), AX - MOVQ R12, 136(AX) - MOVQ 144(AX), CX - SUBQ CX, R11 - MOVQ R11, 168(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decodeSync_safe_amd64_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX - MOVQ ctx+16(FP), CX - MOVQ AX, 216(CX) - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decodeSync_safe_amd64_error_match_len_too_big: - MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error -error_match_off_too_big: - MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX - MOVQ CX, 224(AX) - MOVQ R12, 136(AX) - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - - // Return with not enough output space error -error_not_enough_space: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ R12, 136(AX) - MOVQ $0x00000005, ret+24(FP) - RET - -// func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int -// Requires: BMI, BMI2, CMOV, SSE -TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $64-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX - ADDQ BX, CX - MOVQ CX, (SP) - MOVQ ctx+16(FP), CX - MOVQ 72(CX), SI - MOVQ 80(CX), DI - MOVQ 88(CX), R8 - XORQ R9, R9 - MOVQ R9, 8(SP) - MOVQ R9, 16(SP) - MOVQ R9, 24(SP) - MOVQ 112(CX), R9 - MOVQ 128(CX), R10 - MOVQ R10, 32(SP) - MOVQ 144(CX), R10 - MOVQ 136(CX), R11 - MOVQ 200(CX), R12 - MOVQ R12, 56(SP) - MOVQ 176(CX), R12 - MOVQ R12, 48(SP) - MOVQ 184(CX), CX - MOVQ CX, 40(SP) - MOVQ 40(SP), CX - ADDQ CX, 48(SP) - - // Calculate poiter to s.out[cap(s.out)] (a past-end pointer) - ADDQ R9, 32(SP) - - // outBase += outPosition - ADDQ R11, R9 - -sequenceDecs_decodeSync_safe_bmi2_main_loop: - MOVQ (SP), R12 - - // Fill bitreader to have enough for the offset and match length. - CMPQ BX, $0x08 - JL sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R12 - MOVQ (R12), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decodeSync_safe_bmi2_fill_end - -sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decodeSync_safe_bmi2_fill_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decodeSync_safe_bmi2_fill_end - SHLQ $0x08, AX - SUBQ $0x01, R12 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R12), CX - ORQ CX, AX - JMP sequenceDecs_decodeSync_safe_bmi2_fill_byte_by_byte - -sequenceDecs_decodeSync_safe_bmi2_fill_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_safe_bmi2_fill_end: - // Update offset - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ R8, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 8(SP) - - // Update match length - MOVQ $0x00000808, CX - BEXTRQ CX, DI, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ DI, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 16(SP) - - // Fill bitreader to have enough for the remaining - CMPQ BX, $0x08 - JL sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte - MOVQ DX, CX - SHRQ $0x03, CX - SUBQ CX, R12 - MOVQ (R12), AX - SUBQ CX, BX - ANDQ $0x07, DX - JMP sequenceDecs_decodeSync_safe_bmi2_fill_2_end - -sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte: - CMPQ BX, $0x00 - JLE sequenceDecs_decodeSync_safe_bmi2_fill_2_check_overread - CMPQ DX, $0x07 - JLE sequenceDecs_decodeSync_safe_bmi2_fill_2_end - SHLQ $0x08, AX - SUBQ $0x01, R12 - SUBQ $0x01, BX - SUBQ $0x08, DX - MOVBQZX (R12), CX - ORQ CX, AX - JMP sequenceDecs_decodeSync_safe_bmi2_fill_2_byte_by_byte - -sequenceDecs_decodeSync_safe_bmi2_fill_2_check_overread: - CMPQ DX, $0x40 - JA error_overread - -sequenceDecs_decodeSync_safe_bmi2_fill_2_end: - // Update literal length - MOVQ $0x00000808, CX - BEXTRQ CX, SI, R13 - MOVQ AX, R14 - LEAQ (DX)(R13*1), CX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - MOVQ CX, DX - MOVQ SI, CX - SHRQ $0x20, CX - ADDQ R14, CX - MOVQ CX, 24(SP) - - // Fill bitreader for state updates - MOVQ R12, (SP) - MOVQ $0x00000808, CX - BEXTRQ CX, R8, R12 - MOVQ ctx+16(FP), CX - CMPQ 96(CX), $0x00 - JZ sequenceDecs_decodeSync_safe_bmi2_skip_update - LEAQ (SI)(DI*1), R13 - ADDQ R8, R13 - MOVBQZX R13, R13 - LEAQ (DX)(R13*1), CX - MOVQ AX, R14 - MOVQ CX, DX - ROLQ CL, R14 - BZHIQ R13, R14, R14 - - // Update Offset State - BZHIQ R8, R14, CX - SHRXQ R8, R14, R14 - SHRL $0x10, R8 - ADDQ CX, R8 - - // Load ctx.ofTable - MOVQ ctx+16(FP), CX - MOVQ 48(CX), CX - MOVQ (CX)(R8*8), R8 - - // Update Match Length State - BZHIQ DI, R14, CX - SHRXQ DI, R14, R14 - SHRL $0x10, DI - ADDQ CX, DI - - // Load ctx.mlTable - MOVQ ctx+16(FP), CX - MOVQ 24(CX), CX - MOVQ (CX)(DI*8), DI - - // Update Literal Length State - BZHIQ SI, R14, CX - SHRL $0x10, SI - ADDQ CX, SI - - // Load ctx.llTable - MOVQ ctx+16(FP), CX - MOVQ (CX), CX - MOVQ (CX)(SI*8), SI - -sequenceDecs_decodeSync_safe_bmi2_skip_update: - // Adjust offset - MOVQ s+0(FP), CX - MOVQ 8(SP), R13 - CMPQ R12, $0x01 - JBE sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0 - MOVUPS 144(CX), X0 - MOVQ R13, 144(CX) - MOVUPS X0, 152(CX) - JMP sequenceDecs_decodeSync_safe_bmi2_after_adjust - -sequenceDecs_decodeSync_safe_bmi2_adjust_offsetB_1_or_0: - CMPQ 24(SP), $0x00000000 - JNE sequenceDecs_decodeSync_safe_bmi2_adjust_offset_maybezero - INCQ R13 - JMP sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero - -sequenceDecs_decodeSync_safe_bmi2_adjust_offset_maybezero: - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero - MOVQ 144(CX), R13 - JMP sequenceDecs_decodeSync_safe_bmi2_after_adjust - -sequenceDecs_decodeSync_safe_bmi2_adjust_offset_nonzero: - MOVQ R13, R12 - XORQ R14, R14 - MOVQ $-1, R15 - CMPQ R13, $0x03 - CMOVQEQ R14, R12 - CMOVQEQ R15, R14 - ADDQ 144(CX)(R12*8), R14 - JNZ sequenceDecs_decodeSync_safe_bmi2_adjust_temp_valid - MOVQ $0x00000001, R14 - -sequenceDecs_decodeSync_safe_bmi2_adjust_temp_valid: - CMPQ R13, $0x01 - JZ sequenceDecs_decodeSync_safe_bmi2_adjust_skip - MOVQ 152(CX), R12 - MOVQ R12, 160(CX) - -sequenceDecs_decodeSync_safe_bmi2_adjust_skip: - MOVQ 144(CX), R12 - MOVQ R12, 152(CX) - MOVQ R14, 144(CX) - MOVQ R14, R13 - -sequenceDecs_decodeSync_safe_bmi2_after_adjust: - MOVQ R13, 8(SP) - - // Check values - MOVQ 16(SP), CX - MOVQ 24(SP), R12 - LEAQ (CX)(R12*1), R14 - MOVQ s+0(FP), R15 - ADDQ R14, 256(R15) - MOVQ ctx+16(FP), R14 - SUBQ R12, 104(R14) - JS error_not_enough_literals - CMPQ CX, $0x00020002 - JA sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big - TESTQ R13, R13 - JNZ sequenceDecs_decodeSync_safe_bmi2_match_len_ofs_ok - TESTQ CX, CX - JNZ sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch - -sequenceDecs_decodeSync_safe_bmi2_match_len_ofs_ok: - MOVQ 24(SP), CX - MOVQ 8(SP), R12 - MOVQ 16(SP), R13 - - // Check if we have enough space in s.out - LEAQ (CX)(R13*1), R14 - ADDQ R9, R14 - CMPQ R14, 32(SP) - JA error_not_enough_space - - // Copy literals - TESTQ CX, CX - JZ check_offset - MOVQ CX, R14 - SUBQ $0x10, R14 - JB copy_1_small - -copy_1_loop: - MOVUPS (R10), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R10 - ADDQ $0x10, R9 - SUBQ $0x10, R14 - JAE copy_1_loop - LEAQ 16(R10)(R14*1), R10 - LEAQ 16(R9)(R14*1), R9 - MOVUPS -16(R10), X0 - MOVUPS X0, -16(R9) - JMP copy_1_end - -copy_1_small: - CMPQ CX, $0x03 - JE copy_1_move_3 - JB copy_1_move_1or2 - CMPQ CX, $0x08 - JB copy_1_move_4through7 - JMP copy_1_move_8through16 - -copy_1_move_1or2: - MOVB (R10), R14 - MOVB -1(R10)(CX*1), R15 - MOVB R14, (R9) - MOVB R15, -1(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 - JMP copy_1_end - -copy_1_move_3: - MOVW (R10), R14 - MOVB 2(R10), R15 - MOVW R14, (R9) - MOVB R15, 2(R9) - ADDQ CX, R10 - ADDQ CX, R9 - JMP copy_1_end - -copy_1_move_4through7: - MOVL (R10), R14 - MOVL -4(R10)(CX*1), R15 - MOVL R14, (R9) - MOVL R15, -4(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 - JMP copy_1_end - -copy_1_move_8through16: - MOVQ (R10), R14 - MOVQ -8(R10)(CX*1), R15 - MOVQ R14, (R9) - MOVQ R15, -8(R9)(CX*1) - ADDQ CX, R10 - ADDQ CX, R9 - -copy_1_end: - ADDQ CX, R11 - - // Malformed input if seq.mo > t+len(hist) || seq.mo > s.windowSize) -check_offset: - MOVQ R11, CX - ADDQ 40(SP), CX - CMPQ R12, CX - JG error_match_off_too_big - CMPQ R12, 56(SP) - JG error_match_off_too_big - - // Copy match from history - MOVQ R12, CX - SUBQ R11, CX - JLS copy_match - MOVQ 48(SP), R14 - SUBQ CX, R14 - CMPQ R13, CX - JG copy_all_from_history - MOVQ R13, CX - SUBQ $0x10, CX - JB copy_4_small - -copy_4_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R14 - ADDQ $0x10, R9 - SUBQ $0x10, CX - JAE copy_4_loop - LEAQ 16(R14)(CX*1), R14 - LEAQ 16(R9)(CX*1), R9 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R9) - JMP copy_4_end - -copy_4_small: - CMPQ R13, $0x03 - JE copy_4_move_3 - CMPQ R13, $0x08 - JB copy_4_move_4through7 - JMP copy_4_move_8through16 - -copy_4_move_3: - MOVW (R14), CX - MOVB 2(R14), R12 - MOVW CX, (R9) - MOVB R12, 2(R9) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end - -copy_4_move_4through7: - MOVL (R14), CX - MOVL -4(R14)(R13*1), R12 - MOVL CX, (R9) - MOVL R12, -4(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 - JMP copy_4_end - -copy_4_move_8through16: - MOVQ (R14), CX - MOVQ -8(R14)(R13*1), R12 - MOVQ CX, (R9) - MOVQ R12, -8(R9)(R13*1) - ADDQ R13, R14 - ADDQ R13, R9 - -copy_4_end: - ADDQ R13, R11 - JMP handle_loop - JMP loop_finished - -copy_all_from_history: - MOVQ CX, R15 - SUBQ $0x10, R15 - JB copy_5_small - -copy_5_loop: - MOVUPS (R14), X0 - MOVUPS X0, (R9) - ADDQ $0x10, R14 - ADDQ $0x10, R9 - SUBQ $0x10, R15 - JAE copy_5_loop - LEAQ 16(R14)(R15*1), R14 - LEAQ 16(R9)(R15*1), R9 - MOVUPS -16(R14), X0 - MOVUPS X0, -16(R9) - JMP copy_5_end - -copy_5_small: - CMPQ CX, $0x03 - JE copy_5_move_3 - JB copy_5_move_1or2 - CMPQ CX, $0x08 - JB copy_5_move_4through7 - JMP copy_5_move_8through16 - -copy_5_move_1or2: - MOVB (R14), R15 - MOVB -1(R14)(CX*1), BP - MOVB R15, (R9) - MOVB BP, -1(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_3: - MOVW (R14), R15 - MOVB 2(R14), BP - MOVW R15, (R9) - MOVB BP, 2(R9) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_4through7: - MOVL (R14), R15 - MOVL -4(R14)(CX*1), BP - MOVL R15, (R9) - MOVL BP, -4(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - JMP copy_5_end - -copy_5_move_8through16: - MOVQ (R14), R15 - MOVQ -8(R14)(CX*1), BP - MOVQ R15, (R9) - MOVQ BP, -8(R9)(CX*1) - ADDQ CX, R14 - ADDQ CX, R9 - -copy_5_end: - ADDQ CX, R11 - SUBQ CX, R13 - - // Copy match from the current buffer -copy_match: - MOVQ R9, CX - SUBQ R12, CX - - // ml <= mo - CMPQ R13, R12 - JA copy_overlapping_match - - // Copy non-overlapping match - ADDQ R13, R11 - MOVQ R13, R12 - SUBQ $0x10, R12 - JB copy_2_small - -copy_2_loop: - MOVUPS (CX), X0 - MOVUPS X0, (R9) - ADDQ $0x10, CX - ADDQ $0x10, R9 - SUBQ $0x10, R12 - JAE copy_2_loop - LEAQ 16(CX)(R12*1), CX - LEAQ 16(R9)(R12*1), R9 - MOVUPS -16(CX), X0 - MOVUPS X0, -16(R9) - JMP copy_2_end - -copy_2_small: - CMPQ R13, $0x03 - JE copy_2_move_3 - JB copy_2_move_1or2 - CMPQ R13, $0x08 - JB copy_2_move_4through7 - JMP copy_2_move_8through16 - -copy_2_move_1or2: - MOVB (CX), R12 - MOVB -1(CX)(R13*1), R14 - MOVB R12, (R9) - MOVB R14, -1(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 - JMP copy_2_end - -copy_2_move_3: - MOVW (CX), R12 - MOVB 2(CX), R14 - MOVW R12, (R9) - MOVB R14, 2(R9) - ADDQ R13, CX - ADDQ R13, R9 - JMP copy_2_end - -copy_2_move_4through7: - MOVL (CX), R12 - MOVL -4(CX)(R13*1), R14 - MOVL R12, (R9) - MOVL R14, -4(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 - JMP copy_2_end - -copy_2_move_8through16: - MOVQ (CX), R12 - MOVQ -8(CX)(R13*1), R14 - MOVQ R12, (R9) - MOVQ R14, -8(R9)(R13*1) - ADDQ R13, CX - ADDQ R13, R9 - -copy_2_end: - JMP handle_loop - - // Copy overlapping match -copy_overlapping_match: - ADDQ R13, R11 - -copy_slow_3: - MOVB (CX), R12 - MOVB R12, (R9) - INCQ CX - INCQ R9 - DECQ R13 - JNZ copy_slow_3 - -handle_loop: - MOVQ ctx+16(FP), CX - DECQ 96(CX) - JNS sequenceDecs_decodeSync_safe_bmi2_main_loop - -loop_finished: - MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) - - // Update the context - MOVQ ctx+16(FP), AX - MOVQ R11, 136(AX) - MOVQ 144(AX), CX - SUBQ CX, R10 - MOVQ R10, 168(AX) - - // Return success - MOVQ $0x00000000, ret+24(FP) - RET - - // Return with match length error -sequenceDecs_decodeSync_safe_bmi2_error_match_len_ofs_mismatch: - MOVQ 16(SP), AX - MOVQ ctx+16(FP), CX - MOVQ AX, 216(CX) - MOVQ $0x00000001, ret+24(FP) - RET - - // Return with match too long error -sequenceDecs_decodeSync_safe_bmi2_error_match_len_too_big: - MOVQ ctx+16(FP), AX - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ $0x00000002, ret+24(FP) - RET - - // Return with match offset too long error -error_match_off_too_big: - MOVQ ctx+16(FP), AX - MOVQ 8(SP), CX - MOVQ CX, 224(AX) - MOVQ R11, 136(AX) - MOVQ $0x00000003, ret+24(FP) - RET - - // Return with not enough literals error -error_not_enough_literals: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ $0x00000004, ret+24(FP) - RET - - // Return with overread error -error_overread: - MOVQ $0x00000006, ret+24(FP) - RET - - // Return with not enough output space error -error_not_enough_space: - MOVQ ctx+16(FP), AX - MOVQ 24(SP), CX - MOVQ CX, 208(AX) - MOVQ 16(SP), CX - MOVQ CX, 216(AX) - MOVQ R11, 136(AX) - MOVQ $0x00000005, ret+24(FP) - RET diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go b/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go deleted file mode 100644 index 2fb35b788..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go +++ /dev/null @@ -1,237 +0,0 @@ -//go:build !amd64 || appengine || !gc || noasm -// +build !amd64 appengine !gc noasm - -package zstd - -import ( - "fmt" - "io" -) - -// decode sequences from the stream with the provided history but without dictionary. -func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { - return false, nil -} - -// decode sequences from the stream without the provided history. -func (s *sequenceDecs) decode(seqs []seqVals) error { - br := s.br - - // Grab full sizes tables, to avoid bounds checks. - llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] - llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state - s.seqSize = 0 - litRemain := len(s.literals) - - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } - for i := range seqs { - var ll, mo, ml int - if len(br.in) > 4+((maxOffsetBits+16+16)>>3) { - // inlined function: - // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) - - // Final will not read from stream. - var llB, mlB, moB uint8 - ll, llB = llState.final() - ml, mlB = mlState.final() - mo, moB = ofState.final() - - // extra bits are stored in reverse order. - br.fillFast() - mo += br.getBits(moB) - if s.maxBits > 32 { - br.fillFast() - } - ml += br.getBits(mlB) - ll += br.getBits(llB) - - if moB > 1 { - s.prevOffset[2] = s.prevOffset[1] - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = mo - } else { - // mo = s.adjustOffset(mo, ll, moB) - // Inlined for rather big speedup - if ll == 0 { - // There is an exception though, when current sequence's literals_length = 0. - // In this case, repeated offsets are shifted by one, so an offset_value of 1 means Repeated_Offset2, - // an offset_value of 2 means Repeated_Offset3, and an offset_value of 3 means Repeated_Offset1 - 1_byte. - mo++ - } - - if mo == 0 { - mo = s.prevOffset[0] - } else { - var temp int - if mo == 3 { - temp = s.prevOffset[0] - 1 - } else { - temp = s.prevOffset[mo] - } - - if temp == 0 { - // 0 is not valid; input is corrupted; force offset to 1 - println("WARNING: temp was 0") - temp = 1 - } - - if mo != 1 { - s.prevOffset[2] = s.prevOffset[1] - } - s.prevOffset[1] = s.prevOffset[0] - s.prevOffset[0] = temp - mo = temp - } - } - br.fillFast() - } else { - if br.overread() { - if debugDecoder { - printf("reading sequence %d, exceeded available data\n", i) - } - return io.ErrUnexpectedEOF - } - ll, mo, ml = s.next(br, llState, mlState, ofState) - br.fill() - } - - if debugSequences { - println("Seq", i, "Litlen:", ll, "mo:", mo, "(abs) ml:", ml) - } - // Evaluate. - // We might be doing this async, so do it early. - if mo == 0 && ml > 0 { - return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml) - } - if ml > maxMatchLen { - return fmt.Errorf("match len (%d) bigger than max allowed length", ml) - } - s.seqSize += ll + ml - if s.seqSize > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - litRemain -= ll - if litRemain < 0 { - return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, litRemain+ll) - } - seqs[i] = seqVals{ - ll: ll, - ml: ml, - mo: mo, - } - if i == len(seqs)-1 { - // This is the last sequence, so we shouldn't update state. - break - } - - // Manually inlined, ~ 5-20% faster - // Update all 3 states at once. Approx 20% faster. - nBits := llState.nbBits() + mlState.nbBits() + ofState.nbBits() - if nBits == 0 { - llState = llTable[llState.newState()&maxTableMask] - mlState = mlTable[mlState.newState()&maxTableMask] - ofState = ofTable[ofState.newState()&maxTableMask] - } else { - bits := br.get32BitsFast(nBits) - lowBits := uint16(bits >> ((ofState.nbBits() + mlState.nbBits()) & 31)) - llState = llTable[(llState.newState()+lowBits)&maxTableMask] - - lowBits = uint16(bits >> (ofState.nbBits() & 31)) - lowBits &= bitMask[mlState.nbBits()&15] - mlState = mlTable[(mlState.newState()+lowBits)&maxTableMask] - - lowBits = uint16(bits) & bitMask[ofState.nbBits()&15] - ofState = ofTable[(ofState.newState()+lowBits)&maxTableMask] - } - } - s.seqSize += litRemain - if s.seqSize > maxBlockSize { - return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } - err := br.close() - if err != nil { - printf("Closing sequences: %v, %+v\n", err, *br) - } - return err -} - -// executeSimple handles cases when a dictionary is not used. -func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error { - // Ensure we have enough output size... - if len(s.out)+s.seqSize > cap(s.out) { - addBytes := s.seqSize + len(s.out) - s.out = append(s.out, make([]byte, addBytes)...) - s.out = s.out[:len(s.out)-addBytes] - } - - if debugDecoder { - printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize) - } - - var t = len(s.out) - out := s.out[:t+s.seqSize] - - for _, seq := range seqs { - // Add literals - copy(out[t:], s.literals[:seq.ll]) - t += seq.ll - s.literals = s.literals[seq.ll:] - - // Malformed input - if seq.mo > t+len(hist) || seq.mo > s.windowSize { - return fmt.Errorf("match offset (%d) bigger than current history (%d)", seq.mo, t+len(hist)) - } - - // Copy from history. - if v := seq.mo - t; v > 0 { - // v is the start position in history from end. - start := len(hist) - v - if seq.ml > v { - // Some goes into the current block. - // Copy remainder of history - copy(out[t:], hist[start:]) - t += v - seq.ml -= v - } else { - copy(out[t:], hist[start:start+seq.ml]) - t += seq.ml - continue - } - } - - // We must be in the current buffer now - if seq.ml > 0 { - start := t - seq.mo - if seq.ml <= t-start { - // No overlap - copy(out[t:], out[start:start+seq.ml]) - t += seq.ml - } else { - // Overlapping copy - // Extend destination slice and copy one byte at the time. - src := out[start : start+seq.ml] - dst := out[t:] - dst = dst[:len(src)] - t += len(src) - // Destination is the space we just added. - for i := range src { - dst[i] = src[i] - } - } - } - } - // Add final literals - copy(out[t:], s.literals) - if debugDecoder { - t += len(s.literals) - if t != len(out) { - panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize)) - } - } - s.out = out - - return nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/seqenc.go b/vendor/github.com/klauspost/compress/zstd/seqenc.go deleted file mode 100644 index 8014174a7..000000000 --- a/vendor/github.com/klauspost/compress/zstd/seqenc.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import "math/bits" - -type seqCoders struct { - llEnc, ofEnc, mlEnc *fseEncoder - llPrev, ofPrev, mlPrev *fseEncoder -} - -// swap coders with another (block). -func (s *seqCoders) swap(other *seqCoders) { - *s, *other = *other, *s -} - -// setPrev will update the previous encoders to the actually used ones -// and make sure a fresh one is in the main slot. -func (s *seqCoders) setPrev(ll, ml, of *fseEncoder) { - compareSwap := func(used *fseEncoder, current, prev **fseEncoder) { - // We used the new one, more current to history and reuse the previous history - if *current == used { - *prev, *current = *current, *prev - c := *current - p := *prev - c.reUsed = false - p.reUsed = true - return - } - if used == *prev { - return - } - // Ensure we cannot reuse by accident - prevEnc := *prev - prevEnc.symbolLen = 0 - } - compareSwap(ll, &s.llEnc, &s.llPrev) - compareSwap(ml, &s.mlEnc, &s.mlPrev) - compareSwap(of, &s.ofEnc, &s.ofPrev) -} - -func highBit(val uint32) (n uint32) { - return uint32(bits.Len32(val) - 1) -} - -var llCodeTable = [64]byte{0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 16, 17, 17, 18, 18, 19, 19, - 20, 20, 20, 20, 21, 21, 21, 21, - 22, 22, 22, 22, 22, 22, 22, 22, - 23, 23, 23, 23, 23, 23, 23, 23, - 24, 24, 24, 24, 24, 24, 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24} - -// Up to 6 bits -const maxLLCode = 35 - -// llBitsTable translates from ll code to number of bits. -var llBitsTable = [maxLLCode + 1]byte{ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 2, 2, 3, 3, - 4, 6, 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16} - -// llCode returns the code that represents the literal length requested. -func llCode(litLength uint32) uint8 { - const llDeltaCode = 19 - if litLength <= 63 { - // Compiler insists on bounds check (Go 1.12) - return llCodeTable[litLength&63] - } - return uint8(highBit(litLength)) + llDeltaCode -} - -var mlCodeTable = [128]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37, - 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, - 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, - 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, - 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, - 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42} - -// Up to 6 bits -const maxMLCode = 52 - -// mlBitsTable translates from ml code to number of bits. -var mlBitsTable = [maxMLCode + 1]byte{ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 2, 2, 3, 3, - 4, 4, 5, 7, 8, 9, 10, 11, - 12, 13, 14, 15, 16} - -// note : mlBase = matchLength - MINMATCH; -// because it's the format it's stored in seqStore->sequences -func mlCode(mlBase uint32) uint8 { - const mlDeltaCode = 36 - if mlBase <= 127 { - // Compiler insists on bounds check (Go 1.12) - return mlCodeTable[mlBase&127] - } - return uint8(highBit(mlBase)) + mlDeltaCode -} - -func ofCode(offset uint32) uint8 { - // A valid offset will always be > 0. - return uint8(bits.Len32(offset) - 1) -} diff --git a/vendor/github.com/klauspost/compress/zstd/snappy.go b/vendor/github.com/klauspost/compress/zstd/snappy.go deleted file mode 100644 index ec13594e8..000000000 --- a/vendor/github.com/klauspost/compress/zstd/snappy.go +++ /dev/null @@ -1,434 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "encoding/binary" - "errors" - "hash/crc32" - "io" - - "github.com/klauspost/compress/huff0" - snappy "github.com/klauspost/compress/internal/snapref" -) - -const ( - snappyTagLiteral = 0x00 - snappyTagCopy1 = 0x01 - snappyTagCopy2 = 0x02 - snappyTagCopy4 = 0x03 -) - -const ( - snappyChecksumSize = 4 - snappyMagicBody = "sNaPpY" - - // snappyMaxBlockSize is the maximum size of the input to encodeBlock. It is not - // part of the wire format per se, but some parts of the encoder assume - // that an offset fits into a uint16. - // - // Also, for the framing format (Writer type instead of Encode function), - // https://github.com/google/snappy/blob/master/framing_format.txt says - // that "the uncompressed data in a chunk must be no longer than 65536 - // bytes". - snappyMaxBlockSize = 65536 - - // snappyMaxEncodedLenOfMaxBlockSize equals MaxEncodedLen(snappyMaxBlockSize), but is - // hard coded to be a const instead of a variable, so that obufLen can also - // be a const. Their equivalence is confirmed by - // TestMaxEncodedLenOfMaxBlockSize. - snappyMaxEncodedLenOfMaxBlockSize = 76490 -) - -const ( - chunkTypeCompressedData = 0x00 - chunkTypeUncompressedData = 0x01 - chunkTypePadding = 0xfe - chunkTypeStreamIdentifier = 0xff -) - -var ( - // ErrSnappyCorrupt reports that the input is invalid. - ErrSnappyCorrupt = errors.New("snappy: corrupt input") - // ErrSnappyTooLarge reports that the uncompressed length is too large. - ErrSnappyTooLarge = errors.New("snappy: decoded block is too large") - // ErrSnappyUnsupported reports that the input isn't supported. - ErrSnappyUnsupported = errors.New("snappy: unsupported input") - - errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") -) - -// SnappyConverter can read SnappyConverter-compressed streams and convert them to zstd. -// Conversion is done by converting the stream directly from Snappy without intermediate -// full decoding. -// Therefore the compression ratio is much less than what can be done by a full decompression -// and compression, and a faulty Snappy stream may lead to a faulty Zstandard stream without -// any errors being generated. -// No CRC value is being generated and not all CRC values of the Snappy stream are checked. -// However, it provides really fast recompression of Snappy streams. -// The converter can be reused to avoid allocations, even after errors. -type SnappyConverter struct { - r io.Reader - err error - buf []byte - block *blockEnc -} - -// Convert the Snappy stream supplied in 'in' and write the zStandard stream to 'w'. -// If any error is detected on the Snappy stream it is returned. -// The number of bytes written is returned. -func (r *SnappyConverter) Convert(in io.Reader, w io.Writer) (int64, error) { - initPredefined() - r.err = nil - r.r = in - if r.block == nil { - r.block = &blockEnc{} - r.block.init() - } - r.block.initNewEncode() - if len(r.buf) != snappyMaxEncodedLenOfMaxBlockSize+snappyChecksumSize { - r.buf = make([]byte, snappyMaxEncodedLenOfMaxBlockSize+snappyChecksumSize) - } - r.block.litEnc.Reuse = huff0.ReusePolicyNone - var written int64 - var readHeader bool - { - header := frameHeader{WindowSize: snappyMaxBlockSize}.appendTo(r.buf[:0]) - - var n int - n, r.err = w.Write(header) - if r.err != nil { - return written, r.err - } - written += int64(n) - } - - for { - if !r.readFull(r.buf[:4], true) { - // Add empty last block - r.block.reset(nil) - r.block.last = true - err := r.block.encodeLits(r.block.literals, false) - if err != nil { - return written, err - } - n, err := w.Write(r.block.output) - if err != nil { - return written, err - } - written += int64(n) - - return written, r.err - } - chunkType := r.buf[0] - if !readHeader { - if chunkType != chunkTypeStreamIdentifier { - println("chunkType != chunkTypeStreamIdentifier", chunkType) - r.err = ErrSnappyCorrupt - return written, r.err - } - readHeader = true - } - chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 - if chunkLen > len(r.buf) { - println("chunkLen > len(r.buf)", chunkType) - r.err = ErrSnappyUnsupported - return written, r.err - } - - // The chunk types are specified at - // https://github.com/google/snappy/blob/master/framing_format.txt - switch chunkType { - case chunkTypeCompressedData: - // Section 4.2. Compressed data (chunk type 0x00). - if chunkLen < snappyChecksumSize { - println("chunkLen < snappyChecksumSize", chunkLen, snappyChecksumSize) - r.err = ErrSnappyCorrupt - return written, r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf, false) { - return written, r.err - } - //checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - buf = buf[snappyChecksumSize:] - - n, hdr, err := snappyDecodedLen(buf) - if err != nil { - r.err = err - return written, r.err - } - buf = buf[hdr:] - if n > snappyMaxBlockSize { - println("n > snappyMaxBlockSize", n, snappyMaxBlockSize) - r.err = ErrSnappyCorrupt - return written, r.err - } - r.block.reset(nil) - r.block.pushOffsets() - if err := decodeSnappy(r.block, buf); err != nil { - r.err = err - return written, r.err - } - if r.block.size+r.block.extraLits != n { - printf("invalid size, want %d, got %d\n", n, r.block.size+r.block.extraLits) - r.err = ErrSnappyCorrupt - return written, r.err - } - err = r.block.encode(nil, false, false) - switch err { - case errIncompressible: - r.block.popOffsets() - r.block.reset(nil) - r.block.literals, err = snappy.Decode(r.block.literals[:n], r.buf[snappyChecksumSize:chunkLen]) - if err != nil { - return written, err - } - err = r.block.encodeLits(r.block.literals, false) - if err != nil { - return written, err - } - case nil: - default: - return written, err - } - - n, r.err = w.Write(r.block.output) - if r.err != nil { - return written, err - } - written += int64(n) - continue - case chunkTypeUncompressedData: - if debugEncoder { - println("Uncompressed, chunklen", chunkLen) - } - // Section 4.3. Uncompressed data (chunk type 0x01). - if chunkLen < snappyChecksumSize { - println("chunkLen < snappyChecksumSize", chunkLen, snappyChecksumSize) - r.err = ErrSnappyCorrupt - return written, r.err - } - r.block.reset(nil) - buf := r.buf[:snappyChecksumSize] - if !r.readFull(buf, false) { - return written, r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - // Read directly into r.decoded instead of via r.buf. - n := chunkLen - snappyChecksumSize - if n > snappyMaxBlockSize { - println("n > snappyMaxBlockSize", n, snappyMaxBlockSize) - r.err = ErrSnappyCorrupt - return written, r.err - } - r.block.literals = r.block.literals[:n] - if !r.readFull(r.block.literals, false) { - return written, r.err - } - if snappyCRC(r.block.literals) != checksum { - println("literals crc mismatch") - r.err = ErrSnappyCorrupt - return written, r.err - } - err := r.block.encodeLits(r.block.literals, false) - if err != nil { - return written, err - } - n, r.err = w.Write(r.block.output) - if r.err != nil { - return written, err - } - written += int64(n) - continue - - case chunkTypeStreamIdentifier: - if debugEncoder { - println("stream id", chunkLen, len(snappyMagicBody)) - } - // Section 4.1. Stream identifier (chunk type 0xff). - if chunkLen != len(snappyMagicBody) { - println("chunkLen != len(snappyMagicBody)", chunkLen, len(snappyMagicBody)) - r.err = ErrSnappyCorrupt - return written, r.err - } - if !r.readFull(r.buf[:len(snappyMagicBody)], false) { - return written, r.err - } - for i := 0; i < len(snappyMagicBody); i++ { - if r.buf[i] != snappyMagicBody[i] { - println("r.buf[i] != snappyMagicBody[i]", r.buf[i], snappyMagicBody[i], i) - r.err = ErrSnappyCorrupt - return written, r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - println("chunkType <= 0x7f") - r.err = ErrSnappyUnsupported - return written, r.err - } - // Section 4.4 Padding (chunk type 0xfe). - // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). - if !r.readFull(r.buf[:chunkLen], false) { - return written, r.err - } - } -} - -// decodeSnappy writes the decoding of src to dst. It assumes that the varint-encoded -// length of the decompressed bytes has already been read. -func decodeSnappy(blk *blockEnc, src []byte) error { - //decodeRef(make([]byte, snappyMaxBlockSize), src) - var s, length int - lits := blk.extraLits - var offset uint32 - for s < len(src) { - switch src[s] & 0x03 { - case snappyTagLiteral: - x := uint32(src[s] >> 2) - switch { - case x < 60: - s++ - case x == 60: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, src) - return ErrSnappyCorrupt - } - x = uint32(src[s-1]) - case x == 61: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, src) - return ErrSnappyCorrupt - } - x = uint32(src[s-2]) | uint32(src[s-1])<<8 - case x == 62: - s += 4 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, src) - return ErrSnappyCorrupt - } - x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - case x == 63: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, src) - return ErrSnappyCorrupt - } - x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - if x > snappyMaxBlockSize { - println("x > snappyMaxBlockSize", x, snappyMaxBlockSize) - return ErrSnappyCorrupt - } - length = int(x) + 1 - if length <= 0 { - println("length <= 0 ", length) - - return errUnsupportedLiteralLength - } - //if length > snappyMaxBlockSize-d || uint32(length) > len(src)-s { - // return ErrSnappyCorrupt - //} - - blk.literals = append(blk.literals, src[s:s+length]...) - //println(length, "litLen") - lits += length - s += length - continue - - case snappyTagCopy1: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, len(src)) - return ErrSnappyCorrupt - } - length = 4 + int(src[s-2])>>2&0x7 - offset = uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]) - - case snappyTagCopy2: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, len(src)) - return ErrSnappyCorrupt - } - length = 1 + int(src[s-3])>>2 - offset = uint32(src[s-2]) | uint32(src[s-1])<<8 - - case snappyTagCopy4: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - println("uint(s) > uint(len(src)", s, len(src)) - return ErrSnappyCorrupt - } - length = 1 + int(src[s-5])>>2 - offset = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - - if offset <= 0 || blk.size+lits < int(offset) /*|| length > len(blk)-d */ { - println("offset <= 0 || blk.size+lits < int(offset)", offset, blk.size+lits, int(offset), blk.size, lits) - - return ErrSnappyCorrupt - } - - // Check if offset is one of the recent offsets. - // Adjusts the output offset accordingly. - // Gives a tiny bit of compression, typically around 1%. - if false { - offset = blk.matchOffset(offset, uint32(lits)) - } else { - offset += 3 - } - - blk.sequences = append(blk.sequences, seq{ - litLen: uint32(lits), - offset: offset, - matchLen: uint32(length) - zstdMinMatch, - }) - blk.size += length + lits - lits = 0 - } - blk.extraLits = lits - return nil -} - -func (r *SnappyConverter) readFull(p []byte, allowEOF bool) (ok bool) { - if _, r.err = io.ReadFull(r.r, p); r.err != nil { - if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { - r.err = ErrSnappyCorrupt - } - return false - } - return true -} - -var crcTable = crc32.MakeTable(crc32.Castagnoli) - -// crc implements the checksum specified in section 3 of -// https://github.com/google/snappy/blob/master/framing_format.txt -func snappyCRC(b []byte) uint32 { - c := crc32.Update(0, crcTable, b) - return c>>15 | c<<17 + 0xa282ead8 -} - -// snappyDecodedLen returns the length of the decoded block and the number of bytes -// that the length header occupied. -func snappyDecodedLen(src []byte) (blockLen, headerLen int, err error) { - v, n := binary.Uvarint(src) - if n <= 0 || v > 0xffffffff { - return 0, 0, ErrSnappyCorrupt - } - - const wordSize = 32 << (^uint(0) >> 32 & 1) - if wordSize == 32 && v > 0x7fffffff { - return 0, 0, ErrSnappyTooLarge - } - return int(v), n, nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/zip.go b/vendor/github.com/klauspost/compress/zstd/zip.go deleted file mode 100644 index 29c15c8c4..000000000 --- a/vendor/github.com/klauspost/compress/zstd/zip.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. - -package zstd - -import ( - "errors" - "io" - "sync" -) - -// ZipMethodWinZip is the method for Zstandard compressed data inside Zip files for WinZip. -// See https://www.winzip.com/win/en/comp_info.html -const ZipMethodWinZip = 93 - -// ZipMethodPKWare is the original method number used by PKWARE to indicate Zstandard compression. -// Deprecated: This has been deprecated by PKWARE, use ZipMethodWinZip instead for compression. -// See https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.3.9.TXT -const ZipMethodPKWare = 20 - -// zipReaderPool is the default reader pool. -var zipReaderPool = sync.Pool{New: func() interface{} { - z, err := NewReader(nil, WithDecoderLowmem(true), WithDecoderMaxWindow(128<<20), WithDecoderConcurrency(1)) - if err != nil { - panic(err) - } - return z -}} - -// newZipReader creates a pooled zip decompressor. -func newZipReader(opts ...DOption) func(r io.Reader) io.ReadCloser { - pool := &zipReaderPool - if len(opts) > 0 { - opts = append([]DOption{WithDecoderLowmem(true), WithDecoderMaxWindow(128 << 20)}, opts...) - // Force concurrency 1 - opts = append(opts, WithDecoderConcurrency(1)) - // Create our own pool - pool = &sync.Pool{} - } - return func(r io.Reader) io.ReadCloser { - dec, ok := pool.Get().(*Decoder) - if ok { - dec.Reset(r) - } else { - d, err := NewReader(r, opts...) - if err != nil { - panic(err) - } - dec = d - } - return &pooledZipReader{dec: dec, pool: pool} - } -} - -type pooledZipReader struct { - mu sync.Mutex // guards Close and Read - pool *sync.Pool - dec *Decoder -} - -func (r *pooledZipReader) Read(p []byte) (n int, err error) { - r.mu.Lock() - defer r.mu.Unlock() - if r.dec == nil { - return 0, errors.New("read after close or EOF") - } - dec, err := r.dec.Read(p) - if err == io.EOF { - r.dec.Reset(nil) - r.pool.Put(r.dec) - r.dec = nil - } - return dec, err -} - -func (r *pooledZipReader) Close() error { - r.mu.Lock() - defer r.mu.Unlock() - var err error - if r.dec != nil { - err = r.dec.Reset(nil) - r.pool.Put(r.dec) - r.dec = nil - } - return err -} - -type pooledZipWriter struct { - mu sync.Mutex // guards Close and Read - enc *Encoder - pool *sync.Pool -} - -func (w *pooledZipWriter) Write(p []byte) (n int, err error) { - w.mu.Lock() - defer w.mu.Unlock() - if w.enc == nil { - return 0, errors.New("Write after Close") - } - return w.enc.Write(p) -} - -func (w *pooledZipWriter) Close() error { - w.mu.Lock() - defer w.mu.Unlock() - var err error - if w.enc != nil { - err = w.enc.Close() - w.pool.Put(w.enc) - w.enc = nil - } - return err -} - -// ZipCompressor returns a compressor that can be registered with zip libraries. -// The provided encoder options will be used on all encodes. -func ZipCompressor(opts ...EOption) func(w io.Writer) (io.WriteCloser, error) { - var pool sync.Pool - return func(w io.Writer) (io.WriteCloser, error) { - enc, ok := pool.Get().(*Encoder) - if ok { - enc.Reset(w) - } else { - var err error - enc, err = NewWriter(w, opts...) - if err != nil { - return nil, err - } - } - return &pooledZipWriter{enc: enc, pool: &pool}, nil - } -} - -// ZipDecompressor returns a decompressor that can be registered with zip libraries. -// See ZipCompressor for example. -// Options can be specified. WithDecoderConcurrency(1) is forced, -// and by default a 128MB maximum decompression window is specified. -// The window size can be overridden if required. -func ZipDecompressor(opts ...DOption) func(r io.Reader) io.ReadCloser { - return newZipReader(opts...) -} diff --git a/vendor/github.com/klauspost/compress/zstd/zstd.go b/vendor/github.com/klauspost/compress/zstd/zstd.go deleted file mode 100644 index 4be7cc736..000000000 --- a/vendor/github.com/klauspost/compress/zstd/zstd.go +++ /dev/null @@ -1,121 +0,0 @@ -// Package zstd provides decompression of zstandard files. -// -// For advanced usage and examples, go to the README: https://github.com/klauspost/compress/tree/master/zstd#zstd -package zstd - -import ( - "bytes" - "encoding/binary" - "errors" - "log" - "math" -) - -// enable debug printing -const debug = false - -// enable encoding debug printing -const debugEncoder = debug - -// enable decoding debug printing -const debugDecoder = debug - -// Enable extra assertions. -const debugAsserts = debug || false - -// print sequence details -const debugSequences = false - -// print detailed matching information -const debugMatches = false - -// force encoder to use predefined tables. -const forcePreDef = false - -// zstdMinMatch is the minimum zstd match length. -const zstdMinMatch = 3 - -// fcsUnknown is used for unknown frame content size. -const fcsUnknown = math.MaxUint64 - -var ( - // ErrReservedBlockType is returned when a reserved block type is found. - // Typically this indicates wrong or corrupted input. - ErrReservedBlockType = errors.New("invalid input: reserved block type encountered") - - // ErrCompressedSizeTooBig is returned when a block is bigger than allowed. - // Typically this indicates wrong or corrupted input. - ErrCompressedSizeTooBig = errors.New("invalid input: compressed size too big") - - // ErrBlockTooSmall is returned when a block is too small to be decoded. - // Typically returned on invalid input. - ErrBlockTooSmall = errors.New("block too small") - - // ErrUnexpectedBlockSize is returned when a block has unexpected size. - // Typically returned on invalid input. - ErrUnexpectedBlockSize = errors.New("unexpected block size") - - // ErrMagicMismatch is returned when a "magic" number isn't what is expected. - // Typically this indicates wrong or corrupted input. - ErrMagicMismatch = errors.New("invalid input: magic number mismatch") - - // ErrWindowSizeExceeded is returned when a reference exceeds the valid window size. - // Typically this indicates wrong or corrupted input. - ErrWindowSizeExceeded = errors.New("window size exceeded") - - // ErrWindowSizeTooSmall is returned when no window size is specified. - // Typically this indicates wrong or corrupted input. - ErrWindowSizeTooSmall = errors.New("invalid input: window size was too small") - - // ErrDecoderSizeExceeded is returned if decompressed size exceeds the configured limit. - ErrDecoderSizeExceeded = errors.New("decompressed size exceeds configured limit") - - // ErrUnknownDictionary is returned if the dictionary ID is unknown. - ErrUnknownDictionary = errors.New("unknown dictionary") - - // ErrFrameSizeExceeded is returned if the stated frame size is exceeded. - // This is only returned if SingleSegment is specified on the frame. - ErrFrameSizeExceeded = errors.New("frame size exceeded") - - // ErrFrameSizeMismatch is returned if the stated frame size does not match the expected size. - // This is only returned if SingleSegment is specified on the frame. - ErrFrameSizeMismatch = errors.New("frame size does not match size on stream") - - // ErrCRCMismatch is returned if CRC mismatches. - ErrCRCMismatch = errors.New("CRC check failed") - - // ErrDecoderClosed will be returned if the Decoder was used after - // Close has been called. - ErrDecoderClosed = errors.New("decoder used after Close") - - // ErrDecoderNilInput is returned when a nil Reader was provided - // and an operation other than Reset/DecodeAll/Close was attempted. - ErrDecoderNilInput = errors.New("nil input provided as reader") -) - -func println(a ...interface{}) { - if debug || debugDecoder || debugEncoder { - log.Println(a...) - } -} - -func printf(format string, a ...interface{}) { - if debug || debugDecoder || debugEncoder { - log.Printf(format, a...) - } -} - -func load3232(b []byte, i int32) uint32 { - return binary.LittleEndian.Uint32(b[:len(b):len(b)][i:]) -} - -func load6432(b []byte, i int32) uint64 { - return binary.LittleEndian.Uint64(b[:len(b):len(b)][i:]) -} - -type byter interface { - Bytes() []byte - Len() int -} - -var _ byter = &bytes.Buffer{} diff --git a/vendor/github.com/labstack/echo/v4/.editorconfig b/vendor/github.com/labstack/echo/v4/.editorconfig deleted file mode 100644 index 17ae50dd0..000000000 --- a/vendor/github.com/labstack/echo/v4/.editorconfig +++ /dev/null @@ -1,25 +0,0 @@ -# EditorConfig coding styles definitions. For more information about the -# properties used in this file, please see the EditorConfig documentation: -# http://editorconfig.org/ - -# indicate this is the root of the project -root = true - -[*] -charset = utf-8 - -end_of_line = LF -insert_final_newline = true -trim_trailing_whitespace = true - -indent_style = space -indent_size = 2 - -[Makefile] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -[*.go] -indent_style = tab diff --git a/vendor/github.com/labstack/echo/v4/.gitattributes b/vendor/github.com/labstack/echo/v4/.gitattributes deleted file mode 100644 index 49b63e526..000000000 --- a/vendor/github.com/labstack/echo/v4/.gitattributes +++ /dev/null @@ -1,20 +0,0 @@ -# Automatically normalize line endings for all text-based files -# http://git-scm.com/docs/gitattributes#_end_of_line_conversion -* text=auto - -# For the following file types, normalize line endings to LF on checking and -# prevent conversion to CRLF when they are checked out (this is required in -# order to prevent newline related issues) -.* text eol=lf -*.go text eol=lf -*.yml text eol=lf -*.html text eol=lf -*.css text eol=lf -*.js text eol=lf -*.json text eol=lf -LICENSE text eol=lf - -# Exclude `website` and `cookbook` from GitHub's language statistics -# https://github.com/github/linguist#using-gitattributes -cookbook/* linguist-documentation -website/* linguist-documentation diff --git a/vendor/github.com/labstack/echo/v4/.gitignore b/vendor/github.com/labstack/echo/v4/.gitignore deleted file mode 100644 index dbadf3bd0..000000000 --- a/vendor/github.com/labstack/echo/v4/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -.DS_Store -coverage.txt -_test -vendor -.idea -*.iml -*.out -.vscode diff --git a/vendor/github.com/labstack/echo/v4/CHANGELOG.md b/vendor/github.com/labstack/echo/v4/CHANGELOG.md deleted file mode 100644 index 4e88f8abb..000000000 --- a/vendor/github.com/labstack/echo/v4/CHANGELOG.md +++ /dev/null @@ -1,538 +0,0 @@ -# Changelog - -## v4.13.3 - 2024-12-19 - -**Security** - -* Update golang.org/x/net dependency [GO-2024-3333](https://pkg.go.dev/vuln/GO-2024-3333) in https://github.com/labstack/echo/pull/2722 - - -## v4.13.2 - 2024-12-12 - -**Security** - -* Update dependencies (dependabot reports [GO-2024-3321](https://pkg.go.dev/vuln/GO-2024-3321)) in https://github.com/labstack/echo/pull/2721 - - -## v4.13.1 - 2024-12-11 - -**Fixes** - -* Fix BindBody ignoring `Transfer-Encoding: chunked` requests by @178inaba in https://github.com/labstack/echo/pull/2717 - - - -## v4.13.0 - 2024-12-04 - -**BREAKING CHANGE** JWT Middleware Removed from Core use [labstack/echo-jwt](https://github.com/labstack/echo-jwt) instead - -The JWT middleware has been **removed from Echo core** due to another security vulnerability, [CVE-2024-51744](https://nvd.nist.gov/vuln/detail/CVE-2024-51744). For more details, refer to issue [#2699](https://github.com/labstack/echo/issues/2699). A drop-in replacement is available in the [labstack/echo-jwt](https://github.com/labstack/echo-jwt) repository. - -**Important**: Direct assignments like `token := c.Get("user").(*jwt.Token)` will now cause a panic due to an invalid cast. Update your code accordingly. Replace the current imports from `"github.com/golang-jwt/jwt"` in your handlers to the new middleware version using `"github.com/golang-jwt/jwt/v5"`. - - -Background: - -The version of `golang-jwt/jwt` (v3.2.2) previously used in Echo core has been in an unmaintained state for some time. This is not the first vulnerability affecting this library; earlier issues were addressed in [PR #1946](https://github.com/labstack/echo/pull/1946). -JWT middleware was marked as deprecated in Echo core as of [v4.10.0](https://github.com/labstack/echo/releases/tag/v4.10.0) on 2022-12-27. If you did not notice that, consider leveraging tools like [Staticcheck](https://staticcheck.dev/) to catch such deprecations earlier in you dev/CI flow. For bonus points - check out [gosec](https://github.com/securego/gosec). - -We sincerely apologize for any inconvenience caused by this change. While we strive to maintain backward compatibility within Echo core, recurring security issues with third-party dependencies have forced this decision. - -**Enhancements** - -* remove jwt middleware by @stevenwhitehead in https://github.com/labstack/echo/pull/2701 -* optimization: struct alignment by @behnambm in https://github.com/labstack/echo/pull/2636 -* bind: Maintain backwards compatibility for map[string]interface{} binding by @thesaltree in https://github.com/labstack/echo/pull/2656 -* Add Go 1.23 to CI by @aldas in https://github.com/labstack/echo/pull/2675 -* improve `MultipartForm` test by @martinyonatann in https://github.com/labstack/echo/pull/2682 -* `bind` : add support of multipart multi files by @martinyonatann in https://github.com/labstack/echo/pull/2684 -* Add TemplateRenderer struct to ease creating renderers for `html/template` and `text/template` packages. by @aldas in https://github.com/labstack/echo/pull/2690 -* Refactor TestBasicAuth to utilize table-driven test format by @ErikOlson in https://github.com/labstack/echo/pull/2688 -* Remove broken header by @aldas in https://github.com/labstack/echo/pull/2705 -* fix(bind body): content-length can be -1 by @phamvinhdat in https://github.com/labstack/echo/pull/2710 -* CORS middleware should compile allowOrigin regexp at creation by @aldas in https://github.com/labstack/echo/pull/2709 -* Shorten Github issue template and add test example by @aldas in https://github.com/labstack/echo/pull/2711 - - -## v4.12.0 - 2024-04-15 - -**Security** - -* Update golang.org/x/net dep because of [GO-2024-2687](https://pkg.go.dev/vuln/GO-2024-2687) by @aldas in https://github.com/labstack/echo/pull/2625 - - -**Enhancements** - -* binder: make binding to Map work better with string destinations by @aldas in https://github.com/labstack/echo/pull/2554 -* README.md: add Encore as sponsor by @marcuskohlberg in https://github.com/labstack/echo/pull/2579 -* Reorder paragraphs in README.md by @aldas in https://github.com/labstack/echo/pull/2581 -* CI: upgrade actions/checkout to v4 by @aldas in https://github.com/labstack/echo/pull/2584 -* Remove default charset from 'application/json' Content-Type header by @doortts in https://github.com/labstack/echo/pull/2568 -* CI: Use Go 1.22 by @aldas in https://github.com/labstack/echo/pull/2588 -* binder: allow binding to a nil map by @georgmu in https://github.com/labstack/echo/pull/2574 -* Add Skipper Unit Test In BasicBasicAuthConfig and Add More Detail Explanation regarding BasicAuthValidator by @RyoKusnadi in https://github.com/labstack/echo/pull/2461 -* fix some typos by @teslaedison in https://github.com/labstack/echo/pull/2603 -* fix: some typos by @pomadev in https://github.com/labstack/echo/pull/2596 -* Allow ResponseWriters to unwrap writers when flushing/hijacking by @aldas in https://github.com/labstack/echo/pull/2595 -* Add SPDX licence comments to files. by @aldas in https://github.com/labstack/echo/pull/2604 -* Upgrade deps by @aldas in https://github.com/labstack/echo/pull/2605 -* Change type definition blocks to single declarations. This helps copy… by @aldas in https://github.com/labstack/echo/pull/2606 -* Fix Real IP logic by @cl-bvl in https://github.com/labstack/echo/pull/2550 -* Default binder can use `UnmarshalParams(params []string) error` inter… by @aldas in https://github.com/labstack/echo/pull/2607 -* Default binder can bind pointer to slice as struct field. For example `*[]string` by @aldas in https://github.com/labstack/echo/pull/2608 -* Remove maxparam dependence from Context by @aldas in https://github.com/labstack/echo/pull/2611 -* When route is registered with empty path it is normalized to `/`. by @aldas in https://github.com/labstack/echo/pull/2616 -* proxy middleware should use httputil.ReverseProxy for SSE requests by @aldas in https://github.com/labstack/echo/pull/2624 - - -## v4.11.4 - 2023-12-20 - -**Security** - -* Upgrade golang.org/x/crypto to v0.17.0 to fix vulnerability [issue](https://pkg.go.dev/vuln/GO-2023-2402) [#2562](https://github.com/labstack/echo/pull/2562) - -**Enhancements** - -* Update deps and mark Go version to 1.18 as this is what golang.org/x/* use [#2563](https://github.com/labstack/echo/pull/2563) -* Request logger: add example for Slog https://pkg.go.dev/log/slog [#2543](https://github.com/labstack/echo/pull/2543) - - -## v4.11.3 - 2023-11-07 - -**Security** - -* 'c.Attachment' and 'c.Inline' should escape filename in 'Content-Disposition' header to avoid 'Reflect File Download' vulnerability. [#2541](https://github.com/labstack/echo/pull/2541) - -**Enhancements** - -* Tests: refactor context tests to be separate functions [#2540](https://github.com/labstack/echo/pull/2540) -* Proxy middleware: reuse echo request context [#2537](https://github.com/labstack/echo/pull/2537) -* Mark unmarshallable yaml struct tags as ignored [#2536](https://github.com/labstack/echo/pull/2536) - - -## v4.11.2 - 2023-10-11 - -**Security** - -* Bump golang.org/x/net to prevent CVE-2023-39325 / CVE-2023-44487 HTTP/2 Rapid Reset Attack [#2527](https://github.com/labstack/echo/pull/2527) -* fix(sec): randomString bias introduced by #2490 [#2492](https://github.com/labstack/echo/pull/2492) -* CSRF/RequestID mw: switch math/random usage to crypto/random [#2490](https://github.com/labstack/echo/pull/2490) - -**Enhancements** - -* Delete unused context in body_limit.go [#2483](https://github.com/labstack/echo/pull/2483) -* Use Go 1.21 in CI [#2505](https://github.com/labstack/echo/pull/2505) -* Fix some typos [#2511](https://github.com/labstack/echo/pull/2511) -* Allow CORS middleware to send Access-Control-Max-Age: 0 [#2518](https://github.com/labstack/echo/pull/2518) -* Bump dependancies [#2522](https://github.com/labstack/echo/pull/2522) - -## v4.11.1 - 2023-07-16 - -**Fixes** - -* Fix `Gzip` middleware not sending response code for no content responses (404, 301/302 redirects etc) [#2481](https://github.com/labstack/echo/pull/2481) - - -## v4.11.0 - 2023-07-14 - - -**Fixes** - -* Fixes the proxy middleware concurrency issue of calling the Next() proxy target on Round Robin Balancer [#2409](https://github.com/labstack/echo/pull/2409) -* Fix `group.RouteNotFound` not working when group has attached middlewares [#2411](https://github.com/labstack/echo/pull/2411) -* Fix global error handler return error message when message is an error [#2456](https://github.com/labstack/echo/pull/2456) -* Do not use global timeNow variables [#2477](https://github.com/labstack/echo/pull/2477) - - -**Enhancements** - -* Added a optional config variable to disable centralized error handler in recovery middleware [#2410](https://github.com/labstack/echo/pull/2410) -* refactor: use `strings.ReplaceAll` directly [#2424](https://github.com/labstack/echo/pull/2424) -* Add support for Go1.20 `http.rwUnwrapper` to Response struct [#2425](https://github.com/labstack/echo/pull/2425) -* Check whether is nil before invoking centralized error handling [#2429](https://github.com/labstack/echo/pull/2429) -* Proper colon support in `echo.Reverse` method [#2416](https://github.com/labstack/echo/pull/2416) -* Fix misuses of a vs an in documentation comments [#2436](https://github.com/labstack/echo/pull/2436) -* Add link to slog.Handler library for Echo logging into README.md [#2444](https://github.com/labstack/echo/pull/2444) -* In proxy middleware Support retries of failed proxy requests [#2414](https://github.com/labstack/echo/pull/2414) -* gofmt fixes to comments [#2452](https://github.com/labstack/echo/pull/2452) -* gzip response only if it exceeds a minimal length [#2267](https://github.com/labstack/echo/pull/2267) -* Upgrade packages [#2475](https://github.com/labstack/echo/pull/2475) - - -## v4.10.2 - 2023-02-22 - -**Security** - -* `filepath.Clean` behaviour has changed in Go 1.20 - adapt to it [#2406](https://github.com/labstack/echo/pull/2406) -* Add `middleware.CORSConfig.UnsafeWildcardOriginWithAllowCredentials` to make UNSAFE usages of wildcard origin + allow cretentials less likely [#2405](https://github.com/labstack/echo/pull/2405) - -**Enhancements** - -* Add more HTTP error values [#2277](https://github.com/labstack/echo/pull/2277) - - -## v4.10.1 - 2023-02-19 - -**Security** - -* Upgrade deps due to the latest golang.org/x/net vulnerability [#2402](https://github.com/labstack/echo/pull/2402) - - -**Enhancements** - -* Add new JWT repository to the README [#2377](https://github.com/labstack/echo/pull/2377) -* Return an empty string for ctx.path if there is no registered path [#2385](https://github.com/labstack/echo/pull/2385) -* Add context timeout middleware [#2380](https://github.com/labstack/echo/pull/2380) -* Update link to jaegertracing [#2394](https://github.com/labstack/echo/pull/2394) - - -## v4.10.0 - 2022-12-27 - -**Security** - -* We are deprecating JWT middleware in this repository. Please use https://github.com/labstack/echo-jwt instead. - - JWT middleware is moved to separate repository to allow us to bump/upgrade version of JWT implementation (`github.com/golang-jwt/jwt`) we are using -which we can not do in Echo core because this would break backwards compatibility guarantees we try to maintain. - -* This minor version bumps minimum Go version to 1.17 (from 1.16) due `golang.org/x/` packages we depend on. There are - several vulnerabilities fixed in these libraries. - - Echo still tries to support last 4 Go versions but there are occasions we can not guarantee this promise. - - -**Enhancements** - -* Bump x/text to 0.3.8 [#2305](https://github.com/labstack/echo/pull/2305) -* Bump dependencies and add notes about Go releases we support [#2336](https://github.com/labstack/echo/pull/2336) -* Add helper interface for ProxyBalancer interface [#2316](https://github.com/labstack/echo/pull/2316) -* Expose `middleware.CreateExtractors` function so we can use it from echo-contrib repository [#2338](https://github.com/labstack/echo/pull/2338) -* Refactor func(Context) error to HandlerFunc [#2315](https://github.com/labstack/echo/pull/2315) -* Improve function comments [#2329](https://github.com/labstack/echo/pull/2329) -* Add new method HTTPError.WithInternal [#2340](https://github.com/labstack/echo/pull/2340) -* Replace io/ioutil package usages [#2342](https://github.com/labstack/echo/pull/2342) -* Add staticcheck to CI flow [#2343](https://github.com/labstack/echo/pull/2343) -* Replace relative path determination from proprietary to std [#2345](https://github.com/labstack/echo/pull/2345) -* Remove square brackets from ipv6 addresses in XFF (X-Forwarded-For header) [#2182](https://github.com/labstack/echo/pull/2182) -* Add testcases for some BodyLimit middleware configuration options [#2350](https://github.com/labstack/echo/pull/2350) -* Additional configuration options for RequestLogger and Logger middleware [#2341](https://github.com/labstack/echo/pull/2341) -* Add route to request log [#2162](https://github.com/labstack/echo/pull/2162) -* GitHub Workflows security hardening [#2358](https://github.com/labstack/echo/pull/2358) -* Add govulncheck to CI and bump dependencies [#2362](https://github.com/labstack/echo/pull/2362) -* Fix rate limiter docs [#2366](https://github.com/labstack/echo/pull/2366) -* Refactor how `e.Routes()` work and introduce `e.OnAddRouteHandler` callback [#2337](https://github.com/labstack/echo/pull/2337) - - -## v4.9.1 - 2022-10-12 - -**Fixes** - -* Fix logger panicing (when template is set to empty) by bumping dependency version [#2295](https://github.com/labstack/echo/issues/2295) - -**Enhancements** - -* Improve CORS documentation [#2272](https://github.com/labstack/echo/pull/2272) -* Update readme about supported Go versions [#2291](https://github.com/labstack/echo/pull/2291) -* Tests: improve error handling on closing body [#2254](https://github.com/labstack/echo/pull/2254) -* Tests: refactor some of the assertions in tests [#2275](https://github.com/labstack/echo/pull/2275) -* Tests: refactor assertions [#2301](https://github.com/labstack/echo/pull/2301) - -## v4.9.0 - 2022-09-04 - -**Security** - -* Fix open redirect vulnerability in handlers serving static directories (e.Static, e.StaticFs, echo.StaticDirectoryHandler) [#2260](https://github.com/labstack/echo/pull/2260) - -**Enhancements** - -* Allow configuring ErrorHandler in CSRF middleware [#2257](https://github.com/labstack/echo/pull/2257) -* Replace HTTP method constants in tests with stdlib constants [#2247](https://github.com/labstack/echo/pull/2247) - - -## v4.8.0 - 2022-08-10 - -**Most notable things** - -You can now add any arbitrary HTTP method type as a route [#2237](https://github.com/labstack/echo/pull/2237) -```go -e.Add("COPY", "/*", func(c echo.Context) error - return c.String(http.StatusOK, "OK COPY") -}) -``` - -You can add custom 404 handler for specific paths [#2217](https://github.com/labstack/echo/pull/2217) -```go -e.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) }) - -g := e.Group("/images") -g.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) }) -``` - -**Enhancements** - -* Add new value binding methods (UnixTimeMilli,TextUnmarshaler,JSONUnmarshaler) to Valuebinder [#2127](https://github.com/labstack/echo/pull/2127) -* Refactor: body_limit middleware unit test [#2145](https://github.com/labstack/echo/pull/2145) -* Refactor: Timeout mw: rework how test waits for timeout. [#2187](https://github.com/labstack/echo/pull/2187) -* BasicAuth middleware returns 500 InternalServerError on invalid base64 strings but should return 400 [#2191](https://github.com/labstack/echo/pull/2191) -* Refactor: duplicated findStaticChild process at findChildWithLabel [#2176](https://github.com/labstack/echo/pull/2176) -* Allow different param names in different methods with same path scheme [#2209](https://github.com/labstack/echo/pull/2209) -* Add support for registering handlers for different 404 routes [#2217](https://github.com/labstack/echo/pull/2217) -* Middlewares should use errors.As() instead of type assertion on HTTPError [#2227](https://github.com/labstack/echo/pull/2227) -* Allow arbitrary HTTP method types to be added as routes [#2237](https://github.com/labstack/echo/pull/2237) - -## v4.7.2 - 2022-03-16 - -**Fixes** - -* Fix nil pointer exception when calling Start again after address binding error [#2131](https://github.com/labstack/echo/pull/2131) -* Fix CSRF middleware not being able to extract token from multipart/form-data form [#2136](https://github.com/labstack/echo/pull/2136) -* Fix Timeout middleware write race [#2126](https://github.com/labstack/echo/pull/2126) - -**Enhancements** - -* Recover middleware should not log panic for aborted handler [#2134](https://github.com/labstack/echo/pull/2134) - - -## v4.7.1 - 2022-03-13 - -**Fixes** - -* Fix `e.Static`, `.File()`, `c.Attachment()` being picky with paths starting with `./`, `../` and `/` after 4.7.0 introduced echo.Filesystem support (Go1.16+) [#2123](https://github.com/labstack/echo/pull/2123) - -**Enhancements** - -* Remove some unused code [#2116](https://github.com/labstack/echo/pull/2116) - - -## v4.7.0 - 2022-03-01 - -**Enhancements** - -* Add JWT, KeyAuth, CSRF multivalue extractors [#2060](https://github.com/labstack/echo/pull/2060) -* Add LogErrorFunc to recover middleware [#2072](https://github.com/labstack/echo/pull/2072) -* Add support for HEAD method query params binding [#2027](https://github.com/labstack/echo/pull/2027) -* Improve filesystem support with echo.FileFS, echo.StaticFS, group.FileFS, group.StaticFS [#2064](https://github.com/labstack/echo/pull/2064) - -**Fixes** - -* Fix X-Real-IP bug, improve tests [#2007](https://github.com/labstack/echo/pull/2007) -* Minor syntax fixes [#1994](https://github.com/labstack/echo/pull/1994), [#2102](https://github.com/labstack/echo/pull/2102), [#2102](https://github.com/labstack/echo/pull/2102) - -**General** - -* Add cache-control and connection headers [#2103](https://github.com/labstack/echo/pull/2103) -* Add Retry-After header constant [#2078](https://github.com/labstack/echo/pull/2078) -* Upgrade `go` directive in `go.mod` to 1.17 [#2049](https://github.com/labstack/echo/pull/2049) -* Add Pagoda [#2077](https://github.com/labstack/echo/pull/2077) and Souin [#2069](https://github.com/labstack/echo/pull/2069) to 3rd-party middlewares in README - -## v4.6.3 - 2022-01-10 - -**Fixes** - -* Fixed Echo version number in greeting message which was not incremented to `4.6.2` [#2066](https://github.com/labstack/echo/issues/2066) - - -## v4.6.2 - 2022-01-08 - -**Fixes** - -* Fixed route containing escaped colon should be matchable but is not matched to request path [#2047](https://github.com/labstack/echo/pull/2047) -* Fixed a problem that returned wrong content-encoding when the gzip compressed content was empty. [#1921](https://github.com/labstack/echo/pull/1921) -* Update (test) dependencies [#2021](https://github.com/labstack/echo/pull/2021) - - -**Enhancements** - -* Add support for configurable target header for the request_id middleware [#2040](https://github.com/labstack/echo/pull/2040) -* Change decompress middleware to use stream decompression instead of buffering [#2018](https://github.com/labstack/echo/pull/2018) -* Documentation updates - - -## v4.6.1 - 2021-09-26 - -**Enhancements** - -* Add start time to request logger middleware values [#1991](https://github.com/labstack/echo/pull/1991) - -## v4.6.0 - 2021-09-20 - -Introduced a new [request logger](https://github.com/labstack/echo/blob/master/middleware/request_logger.go) middleware -to help with cases when you want to use some other logging library in your application. - -**Fixes** - -* fix timeout middleware warning: superfluous response.WriteHeader [#1905](https://github.com/labstack/echo/issues/1905) - -**Enhancements** - -* Add Cookie to KeyAuth middleware's KeyLookup [#1929](https://github.com/labstack/echo/pull/1929) -* JWT middleware should ignore case of auth scheme in request header [#1951](https://github.com/labstack/echo/pull/1951) -* Refactor default error handler to return first if response is already committed [#1956](https://github.com/labstack/echo/pull/1956) -* Added request logger middleware which helps to use custom logger library for logging requests. [#1980](https://github.com/labstack/echo/pull/1980) -* Allow escaping of colon in route path so Google Cloud API "custom methods" could be implemented [#1988](https://github.com/labstack/echo/pull/1988) - -## v4.5.0 - 2021-08-01 - -**Important notes** - -A **BREAKING CHANGE** is introduced for JWT middleware users. -The JWT library used for the JWT middleware had to be changed from [github.com/dgrijalva/jwt-go](https://github.com/dgrijalva/jwt-go) to -[github.com/golang-jwt/jwt](https://github.com/golang-jwt/jwt) due former library being unmaintained and affected by security -issues. -The [github.com/golang-jwt/jwt](https://github.com/golang-jwt/jwt) project is a drop-in replacement, but supports only the latest 2 Go versions. -So for JWT middleware users Go 1.15+ is required. For detailed information please read [#1940](https://github.com/labstack/echo/discussions/) - -To change the library imports in all .go files in your project replace all occurrences of `dgrijalva/jwt-go` with `golang-jwt/jwt`. - -For Linux CLI you can use: -```bash -find -type f -name "*.go" -exec sed -i "s/dgrijalva\/jwt-go/golang-jwt\/jwt/g" {} \; -go mod tidy -``` - -**Fixes** - -* Change JWT library to `github.com/golang-jwt/jwt` [#1946](https://github.com/labstack/echo/pull/1946) - -## v4.4.0 - 2021-07-12 - -**Fixes** - -* Split HeaderXForwardedFor header only by comma [#1878](https://github.com/labstack/echo/pull/1878) -* Fix Timeout middleware Context propagation [#1910](https://github.com/labstack/echo/pull/1910) - -**Enhancements** - -* Bind data using headers as source [#1866](https://github.com/labstack/echo/pull/1866) -* Adds JWTConfig.ParseTokenFunc to JWT middleware to allow different libraries implementing JWT parsing. [#1887](https://github.com/labstack/echo/pull/1887) -* Adding tests for Echo#Host [#1895](https://github.com/labstack/echo/pull/1895) -* Adds RequestIDHandler function to RequestID middleware [#1898](https://github.com/labstack/echo/pull/1898) -* Allow for custom JSON encoding implementations [#1880](https://github.com/labstack/echo/pull/1880) - -## v4.3.0 - 2021-05-08 - -**Important notes** - -* Route matching has improvements for following cases: - 1. Correctly match routes with parameter part as last part of route (with trailing backslash) - 2. Considering handlers when resolving routes and search for matching http method handler -* Echo minimal Go version is now 1.13. - -**Fixes** - -* When url ends with slash first param route is the match [#1804](https://github.com/labstack/echo/pull/1812) -* Router should check if node is suitable as matching route by path+method and if not then continue search in tree [#1808](https://github.com/labstack/echo/issues/1808) -* Fix timeout middleware not writing response correctly when handler panics [#1864](https://github.com/labstack/echo/pull/1864) -* Fix binder not working with embedded pointer structs [#1861](https://github.com/labstack/echo/pull/1861) -* Add Go 1.16 to CI and drop 1.12 specific code [#1850](https://github.com/labstack/echo/pull/1850) - -**Enhancements** - -* Make KeyFunc public in JWT middleware [#1756](https://github.com/labstack/echo/pull/1756) -* Add support for optional filesystem to the static middleware [#1797](https://github.com/labstack/echo/pull/1797) -* Add a custom error handler to key-auth middleware [#1847](https://github.com/labstack/echo/pull/1847) -* Allow JWT token to be looked up from multiple sources [#1845](https://github.com/labstack/echo/pull/1845) - -## v4.2.2 - 2021-04-07 - -**Fixes** - -* Allow proxy middleware to use query part in rewrite (#1802) -* Fix timeout middleware not sending status code when handler returns an error (#1805) -* Fix Bind() when target is array/slice and path/query params complains bind target not being struct (#1835) -* Fix panic in redirect middleware on short host name (#1813) -* Fix timeout middleware docs (#1836) - -## v4.2.1 - 2021-03-08 - -**Important notes** - -Due to a datarace the config parameters for the newly added timeout middleware required a change. -See the [docs](https://echo.labstack.com/middleware/timeout). -A performance regression has been fixed, even bringing better performance than before for some routing scenarios. - -**Fixes** - -* Fix performance regression caused by path escaping (#1777, #1798, #1799, aldas) -* Avoid context canceled errors (#1789, clwluvw) -* Improve router to use on stack backtracking (#1791, aldas, stffabi) -* Fix panic in timeout middleware not being not recovered and cause application crash (#1794, aldas) -* Fix Echo.Serve() not serving on HTTP port correctly when TLSListener is used (#1785, #1793, aldas) -* Apply go fmt (#1788, Le0tk0k) -* Uses strings.Equalfold (#1790, rkilingr) -* Improve code quality (#1792, withshubh) - -This release was made possible by our **contributors**: -aldas, clwluvw, lammel, Le0tk0k, maciej-jezierski, rkilingr, stffabi, withshubh - -## v4.2.0 - 2021-02-11 - -**Important notes** - -The behaviour for binding data has been reworked for compatibility with echo before v4.1.11 by -enforcing `explicit tagging` for processing parameters. This **may break** your code if you -expect combined handling of query/path/form params. -Please see the updated documentation for [request](https://echo.labstack.com/guide/request) and [binding](https://echo.labstack.com/guide/request) - -The handling for rewrite rules has been slightly adjusted to expand `*` to a non-greedy `(.*?)` capture group. This is only relevant if multiple asterisks are used in your rules. -Please see [rewrite](https://echo.labstack.com/middleware/rewrite) and [proxy](https://echo.labstack.com/middleware/proxy) for details. - -**Security** - -* Fix directory traversal vulnerability for Windows (#1718, little-cui) -* Fix open redirect vulnerability with trailing slash (#1771,#1775 aldas,GeoffreyFrogeye) - -**Enhancements** - -* Add Echo#ListenerNetwork as configuration (#1667, pafuent) -* Add ability to change the status code using response beforeFuncs (#1706, RashadAnsari) -* Echo server startup to allow data race free access to listener address -* Binder: Restore pre v4.1.11 behaviour for c.Bind() to use query params only for GET or DELETE methods (#1727, aldas) -* Binder: Add separate methods to bind only query params, path params or request body (#1681, aldas) -* Binder: New fluent binder for query/path/form parameter binding (#1717, #1736, aldas) -* Router: Performance improvements for missed routes (#1689, pafuent) -* Router: Improve performance for Real-IP detection using IndexByte instead of Split (#1640, imxyb) -* Middleware: Support real regex rules for rewrite and proxy middleware (#1767) -* Middleware: New rate limiting middleware (#1724, iambenkay) -* Middleware: New timeout middleware implementation for go1.13+ (#1743, ) -* Middleware: Allow regex pattern for CORS middleware (#1623, KlotzAndrew) -* Middleware: Add IgnoreBase parameter to static middleware (#1701, lnenad, iambenkay) -* Middleware: Add an optional custom function to CORS middleware to validate origin (#1651, curvegrid) -* Middleware: Support form fields in JWT middleware (#1704, rkfg) -* Middleware: Use sync.Pool for (de)compress middleware to improve performance (#1699, #1672, pafuent) -* Middleware: Add decompress middleware to support gzip compressed requests (#1687, arun0009) -* Middleware: Add ErrJWTInvalid for JWT middleware (#1627, juanbelieni) -* Middleware: Add SameSite mode for CSRF cookies to support iframes (#1524, pr0head) - -**Fixes** - -* Fix handling of special trailing slash case for partial prefix (#1741, stffabi) -* Fix handling of static routes with trailing slash (#1747) -* Fix Static files route not working (#1671, pwli0755, lammel) -* Fix use of caret(^) in regex for rewrite middleware (#1588, chotow) -* Fix Echo#Reverse for Any type routes (#1695, pafuent) -* Fix Router#Find panic with infinite loop (#1661, pafuent) -* Fix Router#Find panic fails on Param paths (#1659, pafuent) -* Fix DefaultHTTPErrorHandler with Debug=true (#1477, lammel) -* Fix incorrect CORS headers (#1669, ulasakdeniz) -* Fix proxy middleware rewritePath to use url with updated tests (#1630, arun0009) -* Fix rewritePath for proxy middleware to use escaped path in (#1628, arun0009) -* Remove unless defer (#1656, imxyb) - -**General** - -* New maintainers for Echo: Roland Lammel (@lammel) and Pablo Andres Fuente (@pafuent) -* Add GitHub action to compare benchmarks (#1702, pafuent) -* Binding query/path params and form fields to struct only works for explicit tags (#1729,#1734, aldas) -* Add support for Go 1.15 in CI (#1683, asahasrabuddhe) -* Add test for request id to remain unchanged if provided (#1719, iambenkay) -* Refactor echo instance listener access and startup to speed up testing (#1735, aldas) -* Refactor and improve various tests for binding and routing -* Run test workflow only for relevant changes (#1637, #1636, pofl) -* Update .travis.yml (#1662, santosh653) -* Update README.md with an recents framework benchmark (#1679, pafuent) - -This release was made possible by **over 100 commits** from more than **20 contributors**: -asahasrabuddhe, aldas, AndrewKlotz, arun0009, chotow, curvegrid, iambenkay, imxyb, -juanbelieni, lammel, little-cui, lnenad, pafuent, pofl, pr0head, pwli, RashadAnsari, -rkfg, santosh653, segfiner, stffabi, ulasakdeniz diff --git a/vendor/github.com/labstack/echo/v4/LICENSE b/vendor/github.com/labstack/echo/v4/LICENSE deleted file mode 100644 index c46d0105f..000000000 --- a/vendor/github.com/labstack/echo/v4/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2021 LabStack - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/labstack/echo/v4/Makefile b/vendor/github.com/labstack/echo/v4/Makefile deleted file mode 100644 index c07d8bb45..000000000 --- a/vendor/github.com/labstack/echo/v4/Makefile +++ /dev/null @@ -1,36 +0,0 @@ -PKG := "github.com/labstack/echo" -PKG_LIST := $(shell go list ${PKG}/...) - -tag: - @git tag `grep -P '^\tversion = ' echo.go|cut -f2 -d'"'` - @git tag|grep -v ^v - -.DEFAULT_GOAL := check -check: lint vet race ## Check project - -init: - @go install golang.org/x/lint/golint@latest - @go install honnef.co/go/tools/cmd/staticcheck@latest - -lint: ## Lint the files - @staticcheck ${PKG_LIST} - @golint -set_exit_status ${PKG_LIST} - -vet: ## Vet the files - @go vet ${PKG_LIST} - -test: ## Run tests - @go test -short ${PKG_LIST} - -race: ## Run tests with data race detector - @go test -race ${PKG_LIST} - -benchmark: ## Run benchmarks - @go test -run="-" -bench=".*" ${PKG_LIST} - -help: ## Display this help screen - @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' - -goversion ?= "1.20" -test_version: ## Run tests inside Docker with given version (defaults to 1.20 oldest supported). Example: make test_version goversion=1.20 - @docker run --rm -it -v $(shell pwd):/project golang:$(goversion) /bin/sh -c "cd /project && make init check" diff --git a/vendor/github.com/labstack/echo/v4/README.md b/vendor/github.com/labstack/echo/v4/README.md deleted file mode 100644 index 5381898d9..000000000 --- a/vendor/github.com/labstack/echo/v4/README.md +++ /dev/null @@ -1,158 +0,0 @@ -[![Sourcegraph](https://sourcegraph.com/github.com/labstack/echo/-/badge.svg?style=flat-square)](https://sourcegraph.com/github.com/labstack/echo?badge) -[![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://pkg.go.dev/github.com/labstack/echo/v4) -[![Go Report Card](https://goreportcard.com/badge/github.com/labstack/echo?style=flat-square)](https://goreportcard.com/report/github.com/labstack/echo) -[![GitHub Workflow Status (with event)](https://img.shields.io/github/actions/workflow/status/labstack/echo/echo.yml?style=flat-square)](https://github.com/labstack/echo/actions) -[![Codecov](https://img.shields.io/codecov/c/github/labstack/echo.svg?style=flat-square)](https://codecov.io/gh/labstack/echo) -[![Forum](https://img.shields.io/badge/community-forum-00afd1.svg?style=flat-square)](https://github.com/labstack/echo/discussions) -[![Twitter](https://img.shields.io/badge/twitter-@labstack-55acee.svg?style=flat-square)](https://twitter.com/labstack) -[![License](http://img.shields.io/badge/license-mit-blue.svg?style=flat-square)](https://raw.githubusercontent.com/labstack/echo/master/LICENSE) - -## Echo - -High performance, extensible, minimalist Go web framework. - -* [Official website](https://echo.labstack.com) -* [Quick start](https://echo.labstack.com/docs/quick-start) -* [Middlewares](https://echo.labstack.com/docs/category/middleware) - -Help and questions: [Github Discussions](https://github.com/labstack/echo/discussions) - - -### Feature Overview - -- Optimized HTTP router which smartly prioritize routes -- Build robust and scalable RESTful APIs -- Group APIs -- Extensible middleware framework -- Define middleware at root, group or route level -- Data binding for JSON, XML and form payload -- Handy functions to send variety of HTTP responses -- Centralized HTTP error handling -- Template rendering with any template engine -- Define your format for the logger -- Highly customizable -- Automatic TLS via Let’s Encrypt -- HTTP/2 support - -## Sponsors - - -
- -Click [here](https://github.com/sponsors/labstack) for more information on sponsorship. - -## Benchmarks - -Date: 2020/11/11
-Source: https://github.com/vishr/web-framework-benchmark
-Lower is better! - - - - -The benchmarks above were run on an Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz - -## [Guide](https://echo.labstack.com/guide) - -### Installation - -```sh -// go get github.com/labstack/echo/{version} -go get github.com/labstack/echo/v4 -``` -Latest version of Echo supports last four Go major [releases](https://go.dev/doc/devel/release) and might work with older versions. - -### Example - -```go -package main - -import ( - "github.com/labstack/echo/v4" - "github.com/labstack/echo/v4/middleware" - "log/slog" - "net/http" -) - -func main() { - // Echo instance - e := echo.New() - - // Middleware - e.Use(middleware.Logger()) - e.Use(middleware.Recover()) - - // Routes - e.GET("/", hello) - - // Start server - if err := e.Start(":8080"); err != nil && !errors.Is(err, http.ErrServerClosed) { - slog.Error("failed to start server", "error", err) - } -} - -// Handler -func hello(c echo.Context) error { - return c.String(http.StatusOK, "Hello, World!") -} -``` - -# Official middleware repositories - -Following list of middleware is maintained by Echo team. - -| Repository | Description | -|------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| [github.com/labstack/echo-jwt](https://github.com/labstack/echo-jwt) | [JWT](https://github.com/golang-jwt/jwt) middleware | -| [github.com/labstack/echo-contrib](https://github.com/labstack/echo-contrib) | [casbin](https://github.com/casbin/casbin), [gorilla/sessions](https://github.com/gorilla/sessions), [jaegertracing](https://github.com/uber/jaeger-client-go), [prometheus](https://github.com/prometheus/client_golang/), [pprof](https://pkg.go.dev/net/http/pprof), [zipkin](https://github.com/openzipkin/zipkin-go) middlewares | - -# Third-party middleware repositories - -Be careful when adding 3rd party middleware. Echo teams does not have time or manpower to guarantee safety and quality -of middlewares in this list. - -| Repository | Description | -|------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| [deepmap/oapi-codegen](https://github.com/deepmap/oapi-codegen) | Automatically generate RESTful API documentation with [OpenAPI](https://swagger.io/specification/) Client and Server Code Generator | -| [github.com/swaggo/echo-swagger](https://github.com/swaggo/echo-swagger) | Automatically generate RESTful API documentation with [Swagger](https://swagger.io/) 2.0. | -| [github.com/ziflex/lecho](https://github.com/ziflex/lecho) | [Zerolog](https://github.com/rs/zerolog) logging library wrapper for Echo logger interface. | -| [github.com/brpaz/echozap](https://github.com/brpaz/echozap) | Uber´s [Zap](https://github.com/uber-go/zap) logging library wrapper for Echo logger interface. | -| [github.com/samber/slog-echo](https://github.com/samber/slog-echo) | Go [slog](https://pkg.go.dev/golang.org/x/exp/slog) logging library wrapper for Echo logger interface. | -| [github.com/darkweak/souin/plugins/echo](https://github.com/darkweak/souin/tree/master/plugins/echo) | HTTP cache system based on [Souin](https://github.com/darkweak/souin) to automatically get your endpoints cached. It supports some distributed and non-distributed storage systems depending your needs. | -| [github.com/mikestefanello/pagoda](https://github.com/mikestefanello/pagoda) | Rapid, easy full-stack web development starter kit built with Echo. | -| [github.com/go-woo/protoc-gen-echo](https://github.com/go-woo/protoc-gen-echo) | ProtoBuf generate Echo server side code | - -Please send a PR to add your own library here. - -## Contribute - -**Use issues for everything** - -- For a small change, just send a PR. -- For bigger changes open an issue for discussion before sending a PR. -- PR should have: - - Test case - - Documentation - - Example (If it makes sense) -- You can also contribute by: - - Reporting issues - - Suggesting new features or enhancements - - Improve/fix documentation - -## Credits - -- [Vishal Rana](https://github.com/vishr) (Author) -- [Nitin Rana](https://github.com/nr17) (Consultant) -- [Roland Lammel](https://github.com/lammel) (Maintainer) -- [Martti T.](https://github.com/aldas) (Maintainer) -- [Pablo Andres Fuente](https://github.com/pafuent) (Maintainer) -- [Contributors](https://github.com/labstack/echo/graphs/contributors) - -## License - -[MIT](https://github.com/labstack/echo/blob/master/LICENSE) diff --git a/vendor/github.com/labstack/echo/v4/bind.go b/vendor/github.com/labstack/echo/v4/bind.go deleted file mode 100644 index ed7ca3249..000000000 --- a/vendor/github.com/labstack/echo/v4/bind.go +++ /dev/null @@ -1,466 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "encoding" - "encoding/xml" - "errors" - "fmt" - "mime/multipart" - "net/http" - "reflect" - "strconv" - "strings" -) - -// Binder is the interface that wraps the Bind method. -type Binder interface { - Bind(i interface{}, c Context) error -} - -// DefaultBinder is the default implementation of the Binder interface. -type DefaultBinder struct{} - -// BindUnmarshaler is the interface used to wrap the UnmarshalParam method. -// Types that don't implement this, but do implement encoding.TextUnmarshaler -// will use that interface instead. -type BindUnmarshaler interface { - // UnmarshalParam decodes and assigns a value from an form or query param. - UnmarshalParam(param string) error -} - -// bindMultipleUnmarshaler is used by binder to unmarshal multiple values from request at once to -// type implementing this interface. For example request could have multiple query fields `?a=1&a=2&b=test` in that case -// for `a` following slice `["1", "2"] will be passed to unmarshaller. -type bindMultipleUnmarshaler interface { - UnmarshalParams(params []string) error -} - -// BindPathParams binds path params to bindable object -func (b *DefaultBinder) BindPathParams(c Context, i interface{}) error { - names := c.ParamNames() - values := c.ParamValues() - params := map[string][]string{} - for i, name := range names { - params[name] = []string{values[i]} - } - if err := b.bindData(i, params, "param", nil); err != nil { - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - return nil -} - -// BindQueryParams binds query params to bindable object -func (b *DefaultBinder) BindQueryParams(c Context, i interface{}) error { - if err := b.bindData(i, c.QueryParams(), "query", nil); err != nil { - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - return nil -} - -// BindBody binds request body contents to bindable object -// NB: then binding forms take note that this implementation uses standard library form parsing -// which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm -// See non-MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseForm -// See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm -func (b *DefaultBinder) BindBody(c Context, i interface{}) (err error) { - req := c.Request() - if req.ContentLength == 0 { - return - } - - // mediatype is found like `mime.ParseMediaType()` does it - base, _, _ := strings.Cut(req.Header.Get(HeaderContentType), ";") - mediatype := strings.TrimSpace(base) - - switch mediatype { - case MIMEApplicationJSON: - if err = c.Echo().JSONSerializer.Deserialize(c, i); err != nil { - switch err.(type) { - case *HTTPError: - return err - default: - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - } - case MIMEApplicationXML, MIMETextXML: - if err = xml.NewDecoder(req.Body).Decode(i); err != nil { - if ute, ok := err.(*xml.UnsupportedTypeError); ok { - return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unsupported type error: type=%v, error=%v", ute.Type, ute.Error())).SetInternal(err) - } else if se, ok := err.(*xml.SyntaxError); ok { - return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: line=%v, error=%v", se.Line, se.Error())).SetInternal(err) - } - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - case MIMEApplicationForm: - params, err := c.FormParams() - if err != nil { - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - if err = b.bindData(i, params, "form", nil); err != nil { - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - case MIMEMultipartForm: - params, err := c.MultipartForm() - if err != nil { - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - if err = b.bindData(i, params.Value, "form", params.File); err != nil { - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - default: - return ErrUnsupportedMediaType - } - return nil -} - -// BindHeaders binds HTTP headers to a bindable object -func (b *DefaultBinder) BindHeaders(c Context, i interface{}) error { - if err := b.bindData(i, c.Request().Header, "header", nil); err != nil { - return NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err) - } - return nil -} - -// Bind implements the `Binder#Bind` function. -// Binding is done in following order: 1) path params; 2) query params; 3) request body. Each step COULD override previous -// step binded values. For single source binding use their own methods BindBody, BindQueryParams, BindPathParams. -func (b *DefaultBinder) Bind(i interface{}, c Context) (err error) { - if err := b.BindPathParams(c, i); err != nil { - return err - } - // Only bind query parameters for GET/DELETE/HEAD to avoid unexpected behavior with destination struct binding from body. - // For example a request URL `&id=1&lang=en` with body `{"id":100,"lang":"de"}` would lead to precedence issues. - // The HTTP method check restores pre-v4.1.11 behavior to avoid these problems (see issue #1670) - method := c.Request().Method - if method == http.MethodGet || method == http.MethodDelete || method == http.MethodHead { - if err = b.BindQueryParams(c, i); err != nil { - return err - } - } - return b.BindBody(c, i) -} - -// bindData will bind data ONLY fields in destination struct that have EXPLICIT tag -func (b *DefaultBinder) bindData(destination interface{}, data map[string][]string, tag string, dataFiles map[string][]*multipart.FileHeader) error { - if destination == nil || (len(data) == 0 && len(dataFiles) == 0) { - return nil - } - hasFiles := len(dataFiles) > 0 - typ := reflect.TypeOf(destination).Elem() - val := reflect.ValueOf(destination).Elem() - - // Support binding to limited Map destinations: - // - map[string][]string, - // - map[string]string <-- (binds first value from data slice) - // - map[string]interface{} - // You are better off binding to struct but there are user who want this map feature. Source of data for these cases are: - // params,query,header,form as these sources produce string values, most of the time slice of strings, actually. - if typ.Kind() == reflect.Map && typ.Key().Kind() == reflect.String { - k := typ.Elem().Kind() - isElemInterface := k == reflect.Interface - isElemString := k == reflect.String - isElemSliceOfStrings := k == reflect.Slice && typ.Elem().Elem().Kind() == reflect.String - if !(isElemSliceOfStrings || isElemString || isElemInterface) { - return nil - } - if val.IsNil() { - val.Set(reflect.MakeMap(typ)) - } - for k, v := range data { - if isElemString { - val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v[0])) - } else if isElemInterface { - // To maintain backward compatibility, we always bind to the first string value - // and not the slice of strings when dealing with map[string]interface{}{} - val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v[0])) - } else { - val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v)) - } - } - return nil - } - - // !struct - if typ.Kind() != reflect.Struct { - if tag == "param" || tag == "query" || tag == "header" { - // incompatible type, data is probably to be found in the body - return nil - } - return errors.New("binding element must be a struct") - } - - for i := 0; i < typ.NumField(); i++ { // iterate over all destination fields - typeField := typ.Field(i) - structField := val.Field(i) - if typeField.Anonymous { - if structField.Kind() == reflect.Ptr { - structField = structField.Elem() - } - } - if !structField.CanSet() { - continue - } - structFieldKind := structField.Kind() - inputFieldName := typeField.Tag.Get(tag) - if typeField.Anonymous && structFieldKind == reflect.Struct && inputFieldName != "" { - // if anonymous struct with query/param/form tags, report an error - return errors.New("query/param/form tags are not allowed with anonymous struct field") - } - - if inputFieldName == "" { - // If tag is nil, we inspect if the field is a not BindUnmarshaler struct and try to bind data into it (might contain fields with tags). - // structs that implement BindUnmarshaler are bound only when they have explicit tag - if _, ok := structField.Addr().Interface().(BindUnmarshaler); !ok && structFieldKind == reflect.Struct { - if err := b.bindData(structField.Addr().Interface(), data, tag, dataFiles); err != nil { - return err - } - } - // does not have explicit tag and is not an ordinary struct - so move to next field - continue - } - - if hasFiles { - if ok, err := isFieldMultipartFile(structField.Type()); err != nil { - return err - } else if ok { - if ok := setMultipartFileHeaderTypes(structField, inputFieldName, dataFiles); ok { - continue - } - } - } - - inputValue, exists := data[inputFieldName] - if !exists { - // Go json.Unmarshal supports case-insensitive binding. However the - // url params are bound case-sensitive which is inconsistent. To - // fix this we must check all of the map values in a - // case-insensitive search. - for k, v := range data { - if strings.EqualFold(k, inputFieldName) { - inputValue = v - exists = true - break - } - } - } - - if !exists { - continue - } - - // NOTE: algorithm here is not particularly sophisticated. It probably does not work with absurd types like `**[]*int` - // but it is smart enough to handle niche cases like `*int`,`*[]string`,`[]*int` . - - // try unmarshalling first, in case we're dealing with an alias to an array type - if ok, err := unmarshalInputsToField(typeField.Type.Kind(), inputValue, structField); ok { - if err != nil { - return err - } - continue - } - - if ok, err := unmarshalInputToField(typeField.Type.Kind(), inputValue[0], structField); ok { - if err != nil { - return err - } - continue - } - - // we could be dealing with pointer to slice `*[]string` so dereference it. There are wierd OpenAPI generators - // that could create struct fields like that. - if structFieldKind == reflect.Pointer { - structFieldKind = structField.Elem().Kind() - structField = structField.Elem() - } - - if structFieldKind == reflect.Slice { - sliceOf := structField.Type().Elem().Kind() - numElems := len(inputValue) - slice := reflect.MakeSlice(structField.Type(), numElems, numElems) - for j := 0; j < numElems; j++ { - if err := setWithProperType(sliceOf, inputValue[j], slice.Index(j)); err != nil { - return err - } - } - structField.Set(slice) - continue - } - - if err := setWithProperType(structFieldKind, inputValue[0], structField); err != nil { - return err - } - } - return nil -} - -func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error { - // But also call it here, in case we're dealing with an array of BindUnmarshalers - if ok, err := unmarshalInputToField(valueKind, val, structField); ok { - return err - } - - switch valueKind { - case reflect.Ptr: - return setWithProperType(structField.Elem().Kind(), val, structField.Elem()) - case reflect.Int: - return setIntField(val, 0, structField) - case reflect.Int8: - return setIntField(val, 8, structField) - case reflect.Int16: - return setIntField(val, 16, structField) - case reflect.Int32: - return setIntField(val, 32, structField) - case reflect.Int64: - return setIntField(val, 64, structField) - case reflect.Uint: - return setUintField(val, 0, structField) - case reflect.Uint8: - return setUintField(val, 8, structField) - case reflect.Uint16: - return setUintField(val, 16, structField) - case reflect.Uint32: - return setUintField(val, 32, structField) - case reflect.Uint64: - return setUintField(val, 64, structField) - case reflect.Bool: - return setBoolField(val, structField) - case reflect.Float32: - return setFloatField(val, 32, structField) - case reflect.Float64: - return setFloatField(val, 64, structField) - case reflect.String: - structField.SetString(val) - default: - return errors.New("unknown type") - } - return nil -} - -func unmarshalInputsToField(valueKind reflect.Kind, values []string, field reflect.Value) (bool, error) { - if valueKind == reflect.Ptr { - if field.IsNil() { - field.Set(reflect.New(field.Type().Elem())) - } - field = field.Elem() - } - - fieldIValue := field.Addr().Interface() - unmarshaler, ok := fieldIValue.(bindMultipleUnmarshaler) - if !ok { - return false, nil - } - return true, unmarshaler.UnmarshalParams(values) -} - -func unmarshalInputToField(valueKind reflect.Kind, val string, field reflect.Value) (bool, error) { - if valueKind == reflect.Ptr { - if field.IsNil() { - field.Set(reflect.New(field.Type().Elem())) - } - field = field.Elem() - } - - fieldIValue := field.Addr().Interface() - switch unmarshaler := fieldIValue.(type) { - case BindUnmarshaler: - return true, unmarshaler.UnmarshalParam(val) - case encoding.TextUnmarshaler: - return true, unmarshaler.UnmarshalText([]byte(val)) - } - - return false, nil -} - -func setIntField(value string, bitSize int, field reflect.Value) error { - if value == "" { - value = "0" - } - intVal, err := strconv.ParseInt(value, 10, bitSize) - if err == nil { - field.SetInt(intVal) - } - return err -} - -func setUintField(value string, bitSize int, field reflect.Value) error { - if value == "" { - value = "0" - } - uintVal, err := strconv.ParseUint(value, 10, bitSize) - if err == nil { - field.SetUint(uintVal) - } - return err -} - -func setBoolField(value string, field reflect.Value) error { - if value == "" { - value = "false" - } - boolVal, err := strconv.ParseBool(value) - if err == nil { - field.SetBool(boolVal) - } - return err -} - -func setFloatField(value string, bitSize int, field reflect.Value) error { - if value == "" { - value = "0.0" - } - floatVal, err := strconv.ParseFloat(value, bitSize) - if err == nil { - field.SetFloat(floatVal) - } - return err -} - -var ( - // NOT supported by bind as you can NOT check easily empty struct being actual file or not - multipartFileHeaderType = reflect.TypeOf(multipart.FileHeader{}) - // supported by bind as you can check by nil value if file existed or not - multipartFileHeaderPointerType = reflect.TypeOf(&multipart.FileHeader{}) - multipartFileHeaderSliceType = reflect.TypeOf([]multipart.FileHeader(nil)) - multipartFileHeaderPointerSliceType = reflect.TypeOf([]*multipart.FileHeader(nil)) -) - -func isFieldMultipartFile(field reflect.Type) (bool, error) { - switch field { - case multipartFileHeaderPointerType, - multipartFileHeaderSliceType, - multipartFileHeaderPointerSliceType: - return true, nil - case multipartFileHeaderType: - return true, errors.New("binding to multipart.FileHeader struct is not supported, use pointer to struct") - default: - return false, nil - } -} - -func setMultipartFileHeaderTypes(structField reflect.Value, inputFieldName string, files map[string][]*multipart.FileHeader) bool { - fileHeaders := files[inputFieldName] - if len(fileHeaders) == 0 { - return false - } - - result := true - switch structField.Type() { - case multipartFileHeaderPointerSliceType: - structField.Set(reflect.ValueOf(fileHeaders)) - case multipartFileHeaderSliceType: - headers := make([]multipart.FileHeader, len(fileHeaders)) - for i, fileHeader := range fileHeaders { - headers[i] = *fileHeader - } - structField.Set(reflect.ValueOf(headers)) - case multipartFileHeaderPointerType: - structField.Set(reflect.ValueOf(fileHeaders[0])) - default: - result = false - } - - return result -} diff --git a/vendor/github.com/labstack/echo/v4/binder.go b/vendor/github.com/labstack/echo/v4/binder.go deleted file mode 100644 index da15ae82a..000000000 --- a/vendor/github.com/labstack/echo/v4/binder.go +++ /dev/null @@ -1,1333 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "encoding" - "encoding/json" - "fmt" - "net/http" - "strconv" - "strings" - "time" -) - -/** - Following functions provide handful of methods for binding to Go native types from request query or path parameters. - * QueryParamsBinder(c) - binds query parameters (source URL) - * PathParamsBinder(c) - binds path parameters (source URL) - * FormFieldBinder(c) - binds form fields (source URL + body) - - Example: - ```go - var length int64 - err := echo.QueryParamsBinder(c).Int64("length", &length).BindError() - ``` - - For every supported type there are following methods: - * ("param", &destination) - if parameter value exists then binds it to given destination of that type i.e Int64(...). - * Must("param", &destination) - parameter value is required to exist, binds it to given destination of that type i.e MustInt64(...). - * s("param", &destination) - (for slices) if parameter values exists then binds it to given destination of that type i.e Int64s(...). - * Musts("param", &destination) - (for slices) parameter value is required to exist, binds it to given destination of that type i.e MustInt64s(...). - - for some slice types `BindWithDelimiter("param", &dest, ",")` supports splitting parameter values before type conversion is done - i.e. URL `/api/search?id=1,2,3&id=1` can be bind to `[]int64{1,2,3,1}` - - `FailFast` flags binder to stop binding after first bind error during binder call chain. Enabled by default. - `BindError()` returns first bind error from binder and resets errors in binder. Useful along with `FailFast()` method - to do binding and returns on first problem - `BindErrors()` returns all bind errors from binder and resets errors in binder. - - Types that are supported: - * bool - * float32 - * float64 - * int - * int8 - * int16 - * int32 - * int64 - * uint - * uint8/byte (does not support `bytes()`. Use BindUnmarshaler/CustomFunc to convert value from base64 etc to []byte{}) - * uint16 - * uint32 - * uint64 - * string - * time - * duration - * BindUnmarshaler() interface - * TextUnmarshaler() interface - * JSONUnmarshaler() interface - * UnixTime() - converts unix time (integer) to time.Time - * UnixTimeMilli() - converts unix time with millisecond precision (integer) to time.Time - * UnixTimeNano() - converts unix time with nanosecond precision (integer) to time.Time - * CustomFunc() - callback function for your custom conversion logic. Signature `func(values []string) []error` -*/ - -// BindingError represents an error that occurred while binding request data. -type BindingError struct { - // Field is the field name where value binding failed - Field string `json:"field"` - *HTTPError - // Values of parameter that failed to bind. - Values []string `json:"-"` -} - -// NewBindingError creates new instance of binding error -func NewBindingError(sourceParam string, values []string, message interface{}, internalError error) error { - return &BindingError{ - Field: sourceParam, - Values: values, - HTTPError: &HTTPError{ - Code: http.StatusBadRequest, - Message: message, - Internal: internalError, - }, - } -} - -// Error returns error message -func (be *BindingError) Error() string { - return fmt.Sprintf("%s, field=%s", be.HTTPError.Error(), be.Field) -} - -// ValueBinder provides utility methods for binding query or path parameter to various Go built-in types -type ValueBinder struct { - // ValueFunc is used to get single parameter (first) value from request - ValueFunc func(sourceParam string) string - // ValuesFunc is used to get all values for parameter from request. i.e. `/api/search?ids=1&ids=2` - ValuesFunc func(sourceParam string) []string - // ErrorFunc is used to create errors. Allows you to use your own error type, that for example marshals to your specific json response - ErrorFunc func(sourceParam string, values []string, message interface{}, internalError error) error - errors []error - // failFast is flag for binding methods to return without attempting to bind when previous binding already failed - failFast bool -} - -// QueryParamsBinder creates query parameter value binder -func QueryParamsBinder(c Context) *ValueBinder { - return &ValueBinder{ - failFast: true, - ValueFunc: c.QueryParam, - ValuesFunc: func(sourceParam string) []string { - values, ok := c.QueryParams()[sourceParam] - if !ok { - return nil - } - return values - }, - ErrorFunc: NewBindingError, - } -} - -// PathParamsBinder creates path parameter value binder -func PathParamsBinder(c Context) *ValueBinder { - return &ValueBinder{ - failFast: true, - ValueFunc: c.Param, - ValuesFunc: func(sourceParam string) []string { - // path parameter should not have multiple values so getting values does not make sense but lets not error out here - value := c.Param(sourceParam) - if value == "" { - return nil - } - return []string{value} - }, - ErrorFunc: NewBindingError, - } -} - -// FormFieldBinder creates form field value binder -// For all requests, FormFieldBinder parses the raw query from the URL and uses query params as form fields -// -// For POST, PUT, and PATCH requests, it also reads the request body, parses it -// as a form and uses query params as form fields. Request body parameters take precedence over URL query -// string values in r.Form. -// -// NB: when binding forms take note that this implementation uses standard library form parsing -// which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm -// See https://golang.org/pkg/net/http/#Request.ParseForm -func FormFieldBinder(c Context) *ValueBinder { - vb := &ValueBinder{ - failFast: true, - ValueFunc: func(sourceParam string) string { - return c.Request().FormValue(sourceParam) - }, - ErrorFunc: NewBindingError, - } - vb.ValuesFunc = func(sourceParam string) []string { - if c.Request().Form == nil { - // this is same as `Request().FormValue()` does internally - _ = c.Request().ParseMultipartForm(32 << 20) - } - values, ok := c.Request().Form[sourceParam] - if !ok { - return nil - } - return values - } - - return vb -} - -// FailFast set internal flag to indicate if binding methods will return early (without binding) when previous bind failed -// NB: call this method before any other binding methods as it modifies binding methods behaviour -func (b *ValueBinder) FailFast(value bool) *ValueBinder { - b.failFast = value - return b -} - -func (b *ValueBinder) setError(err error) { - if b.errors == nil { - b.errors = []error{err} - return - } - b.errors = append(b.errors, err) -} - -// BindError returns first seen bind error and resets/empties binder errors for further calls -func (b *ValueBinder) BindError() error { - if b.errors == nil { - return nil - } - err := b.errors[0] - b.errors = nil // reset errors so next chain will start from zero - return err -} - -// BindErrors returns all bind errors and resets/empties binder errors for further calls -func (b *ValueBinder) BindErrors() []error { - if b.errors == nil { - return nil - } - errors := b.errors - b.errors = nil // reset errors so next chain will start from zero - return errors -} - -// CustomFunc binds parameter values with Func. Func is called only when parameter values exist. -func (b *ValueBinder) CustomFunc(sourceParam string, customFunc func(values []string) []error) *ValueBinder { - return b.customFunc(sourceParam, customFunc, false) -} - -// MustCustomFunc requires parameter values to exist to bind with Func. Returns error when value does not exist. -func (b *ValueBinder) MustCustomFunc(sourceParam string, customFunc func(values []string) []error) *ValueBinder { - return b.customFunc(sourceParam, customFunc, true) -} - -func (b *ValueBinder) customFunc(sourceParam string, customFunc func(values []string) []error, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - values := b.ValuesFunc(sourceParam) - if len(values) == 0 { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - if errs := customFunc(values); errs != nil { - b.errors = append(b.errors, errs...) - } - return b -} - -// String binds parameter to string variable -func (b *ValueBinder) String(sourceParam string, dest *string) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - return b - } - *dest = value - return b -} - -// MustString requires parameter value to exist to bind to string variable. Returns error when value does not exist -func (b *ValueBinder) MustString(sourceParam string, dest *string) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "required field value is empty", nil)) - return b - } - *dest = value - return b -} - -// Strings binds parameter values to slice of string -func (b *ValueBinder) Strings(sourceParam string, dest *[]string) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValuesFunc(sourceParam) - if value == nil { - return b - } - *dest = value - return b -} - -// MustStrings requires parameter values to exist to bind to slice of string variables. Returns error when value does not exist -func (b *ValueBinder) MustStrings(sourceParam string, dest *[]string) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValuesFunc(sourceParam) - if value == nil { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - return b - } - *dest = value - return b -} - -// BindUnmarshaler binds parameter to destination implementing BindUnmarshaler interface -func (b *ValueBinder) BindUnmarshaler(sourceParam string, dest BindUnmarshaler) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - tmp := b.ValueFunc(sourceParam) - if tmp == "" { - return b - } - - if err := dest.UnmarshalParam(tmp); err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{tmp}, "failed to bind field value to BindUnmarshaler interface", err)) - } - return b -} - -// MustBindUnmarshaler requires parameter value to exist to bind to destination implementing BindUnmarshaler interface. -// Returns error when value does not exist -func (b *ValueBinder) MustBindUnmarshaler(sourceParam string, dest BindUnmarshaler) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "required field value is empty", nil)) - return b - } - - if err := dest.UnmarshalParam(value); err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "failed to bind field value to BindUnmarshaler interface", err)) - } - return b -} - -// JSONUnmarshaler binds parameter to destination implementing json.Unmarshaler interface -func (b *ValueBinder) JSONUnmarshaler(sourceParam string, dest json.Unmarshaler) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - tmp := b.ValueFunc(sourceParam) - if tmp == "" { - return b - } - - if err := dest.UnmarshalJSON([]byte(tmp)); err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{tmp}, "failed to bind field value to json.Unmarshaler interface", err)) - } - return b -} - -// MustJSONUnmarshaler requires parameter value to exist to bind to destination implementing json.Unmarshaler interface. -// Returns error when value does not exist -func (b *ValueBinder) MustJSONUnmarshaler(sourceParam string, dest json.Unmarshaler) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - tmp := b.ValueFunc(sourceParam) - if tmp == "" { - b.setError(b.ErrorFunc(sourceParam, []string{tmp}, "required field value is empty", nil)) - return b - } - - if err := dest.UnmarshalJSON([]byte(tmp)); err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{tmp}, "failed to bind field value to json.Unmarshaler interface", err)) - } - return b -} - -// TextUnmarshaler binds parameter to destination implementing encoding.TextUnmarshaler interface -func (b *ValueBinder) TextUnmarshaler(sourceParam string, dest encoding.TextUnmarshaler) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - tmp := b.ValueFunc(sourceParam) - if tmp == "" { - return b - } - - if err := dest.UnmarshalText([]byte(tmp)); err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{tmp}, "failed to bind field value to encoding.TextUnmarshaler interface", err)) - } - return b -} - -// MustTextUnmarshaler requires parameter value to exist to bind to destination implementing encoding.TextUnmarshaler interface. -// Returns error when value does not exist -func (b *ValueBinder) MustTextUnmarshaler(sourceParam string, dest encoding.TextUnmarshaler) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - tmp := b.ValueFunc(sourceParam) - if tmp == "" { - b.setError(b.ErrorFunc(sourceParam, []string{tmp}, "required field value is empty", nil)) - return b - } - - if err := dest.UnmarshalText([]byte(tmp)); err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{tmp}, "failed to bind field value to encoding.TextUnmarshaler interface", err)) - } - return b -} - -// BindWithDelimiter binds parameter to destination by suitable conversion function. -// Delimiter is used before conversion to split parameter value to separate values -func (b *ValueBinder) BindWithDelimiter(sourceParam string, dest interface{}, delimiter string) *ValueBinder { - return b.bindWithDelimiter(sourceParam, dest, delimiter, false) -} - -// MustBindWithDelimiter requires parameter value to exist to bind destination by suitable conversion function. -// Delimiter is used before conversion to split parameter value to separate values -func (b *ValueBinder) MustBindWithDelimiter(sourceParam string, dest interface{}, delimiter string) *ValueBinder { - return b.bindWithDelimiter(sourceParam, dest, delimiter, true) -} - -func (b *ValueBinder) bindWithDelimiter(sourceParam string, dest interface{}, delimiter string, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - values := b.ValuesFunc(sourceParam) - if len(values) == 0 { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - tmpValues := make([]string, 0, len(values)) - for _, v := range values { - tmpValues = append(tmpValues, strings.Split(v, delimiter)...) - } - - switch d := dest.(type) { - case *[]string: - *d = tmpValues - return b - case *[]bool: - return b.bools(sourceParam, tmpValues, d) - case *[]int64, *[]int32, *[]int16, *[]int8, *[]int: - return b.ints(sourceParam, tmpValues, d) - case *[]uint64, *[]uint32, *[]uint16, *[]uint8, *[]uint: // *[]byte is same as *[]uint8 - return b.uints(sourceParam, tmpValues, d) - case *[]float64, *[]float32: - return b.floats(sourceParam, tmpValues, d) - case *[]time.Duration: - return b.durations(sourceParam, tmpValues, d) - default: - // support only cases when destination is slice - // does not support time.Time as it needs argument (layout) for parsing or BindUnmarshaler - b.setError(b.ErrorFunc(sourceParam, []string{}, "unsupported bind type", nil)) - return b - } -} - -// Int64 binds parameter to int64 variable -func (b *ValueBinder) Int64(sourceParam string, dest *int64) *ValueBinder { - return b.intValue(sourceParam, dest, 64, false) -} - -// MustInt64 requires parameter value to exist to bind to int64 variable. Returns error when value does not exist -func (b *ValueBinder) MustInt64(sourceParam string, dest *int64) *ValueBinder { - return b.intValue(sourceParam, dest, 64, true) -} - -// Int32 binds parameter to int32 variable -func (b *ValueBinder) Int32(sourceParam string, dest *int32) *ValueBinder { - return b.intValue(sourceParam, dest, 32, false) -} - -// MustInt32 requires parameter value to exist to bind to int32 variable. Returns error when value does not exist -func (b *ValueBinder) MustInt32(sourceParam string, dest *int32) *ValueBinder { - return b.intValue(sourceParam, dest, 32, true) -} - -// Int16 binds parameter to int16 variable -func (b *ValueBinder) Int16(sourceParam string, dest *int16) *ValueBinder { - return b.intValue(sourceParam, dest, 16, false) -} - -// MustInt16 requires parameter value to exist to bind to int16 variable. Returns error when value does not exist -func (b *ValueBinder) MustInt16(sourceParam string, dest *int16) *ValueBinder { - return b.intValue(sourceParam, dest, 16, true) -} - -// Int8 binds parameter to int8 variable -func (b *ValueBinder) Int8(sourceParam string, dest *int8) *ValueBinder { - return b.intValue(sourceParam, dest, 8, false) -} - -// MustInt8 requires parameter value to exist to bind to int8 variable. Returns error when value does not exist -func (b *ValueBinder) MustInt8(sourceParam string, dest *int8) *ValueBinder { - return b.intValue(sourceParam, dest, 8, true) -} - -// Int binds parameter to int variable -func (b *ValueBinder) Int(sourceParam string, dest *int) *ValueBinder { - return b.intValue(sourceParam, dest, 0, false) -} - -// MustInt requires parameter value to exist to bind to int variable. Returns error when value does not exist -func (b *ValueBinder) MustInt(sourceParam string, dest *int) *ValueBinder { - return b.intValue(sourceParam, dest, 0, true) -} - -func (b *ValueBinder) intValue(sourceParam string, dest interface{}, bitSize int, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - - return b.int(sourceParam, value, dest, bitSize) -} - -func (b *ValueBinder) int(sourceParam string, value string, dest interface{}, bitSize int) *ValueBinder { - n, err := strconv.ParseInt(value, 10, bitSize) - if err != nil { - if bitSize == 0 { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "failed to bind field value to int", err)) - } else { - b.setError(b.ErrorFunc(sourceParam, []string{value}, fmt.Sprintf("failed to bind field value to int%v", bitSize), err)) - } - return b - } - - switch d := dest.(type) { - case *int64: - *d = n - case *int32: - *d = int32(n) - case *int16: - *d = int16(n) - case *int8: - *d = int8(n) - case *int: - *d = int(n) - } - return b -} - -func (b *ValueBinder) intsValue(sourceParam string, dest interface{}, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - values := b.ValuesFunc(sourceParam) - if len(values) == 0 { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, values, "required field value is empty", nil)) - } - return b - } - return b.ints(sourceParam, values, dest) -} - -func (b *ValueBinder) ints(sourceParam string, values []string, dest interface{}) *ValueBinder { - switch d := dest.(type) { - case *[]int64: - tmp := make([]int64, len(values)) - for i, v := range values { - b.int(sourceParam, v, &tmp[i], 64) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]int32: - tmp := make([]int32, len(values)) - for i, v := range values { - b.int(sourceParam, v, &tmp[i], 32) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]int16: - tmp := make([]int16, len(values)) - for i, v := range values { - b.int(sourceParam, v, &tmp[i], 16) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]int8: - tmp := make([]int8, len(values)) - for i, v := range values { - b.int(sourceParam, v, &tmp[i], 8) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]int: - tmp := make([]int, len(values)) - for i, v := range values { - b.int(sourceParam, v, &tmp[i], 0) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - } - return b -} - -// Int64s binds parameter to slice of int64 -func (b *ValueBinder) Int64s(sourceParam string, dest *[]int64) *ValueBinder { - return b.intsValue(sourceParam, dest, false) -} - -// MustInt64s requires parameter value to exist to bind to int64 slice variable. Returns error when value does not exist -func (b *ValueBinder) MustInt64s(sourceParam string, dest *[]int64) *ValueBinder { - return b.intsValue(sourceParam, dest, true) -} - -// Int32s binds parameter to slice of int32 -func (b *ValueBinder) Int32s(sourceParam string, dest *[]int32) *ValueBinder { - return b.intsValue(sourceParam, dest, false) -} - -// MustInt32s requires parameter value to exist to bind to int32 slice variable. Returns error when value does not exist -func (b *ValueBinder) MustInt32s(sourceParam string, dest *[]int32) *ValueBinder { - return b.intsValue(sourceParam, dest, true) -} - -// Int16s binds parameter to slice of int16 -func (b *ValueBinder) Int16s(sourceParam string, dest *[]int16) *ValueBinder { - return b.intsValue(sourceParam, dest, false) -} - -// MustInt16s requires parameter value to exist to bind to int16 slice variable. Returns error when value does not exist -func (b *ValueBinder) MustInt16s(sourceParam string, dest *[]int16) *ValueBinder { - return b.intsValue(sourceParam, dest, true) -} - -// Int8s binds parameter to slice of int8 -func (b *ValueBinder) Int8s(sourceParam string, dest *[]int8) *ValueBinder { - return b.intsValue(sourceParam, dest, false) -} - -// MustInt8s requires parameter value to exist to bind to int8 slice variable. Returns error when value does not exist -func (b *ValueBinder) MustInt8s(sourceParam string, dest *[]int8) *ValueBinder { - return b.intsValue(sourceParam, dest, true) -} - -// Ints binds parameter to slice of int -func (b *ValueBinder) Ints(sourceParam string, dest *[]int) *ValueBinder { - return b.intsValue(sourceParam, dest, false) -} - -// MustInts requires parameter value to exist to bind to int slice variable. Returns error when value does not exist -func (b *ValueBinder) MustInts(sourceParam string, dest *[]int) *ValueBinder { - return b.intsValue(sourceParam, dest, true) -} - -// Uint64 binds parameter to uint64 variable -func (b *ValueBinder) Uint64(sourceParam string, dest *uint64) *ValueBinder { - return b.uintValue(sourceParam, dest, 64, false) -} - -// MustUint64 requires parameter value to exist to bind to uint64 variable. Returns error when value does not exist -func (b *ValueBinder) MustUint64(sourceParam string, dest *uint64) *ValueBinder { - return b.uintValue(sourceParam, dest, 64, true) -} - -// Uint32 binds parameter to uint32 variable -func (b *ValueBinder) Uint32(sourceParam string, dest *uint32) *ValueBinder { - return b.uintValue(sourceParam, dest, 32, false) -} - -// MustUint32 requires parameter value to exist to bind to uint32 variable. Returns error when value does not exist -func (b *ValueBinder) MustUint32(sourceParam string, dest *uint32) *ValueBinder { - return b.uintValue(sourceParam, dest, 32, true) -} - -// Uint16 binds parameter to uint16 variable -func (b *ValueBinder) Uint16(sourceParam string, dest *uint16) *ValueBinder { - return b.uintValue(sourceParam, dest, 16, false) -} - -// MustUint16 requires parameter value to exist to bind to uint16 variable. Returns error when value does not exist -func (b *ValueBinder) MustUint16(sourceParam string, dest *uint16) *ValueBinder { - return b.uintValue(sourceParam, dest, 16, true) -} - -// Uint8 binds parameter to uint8 variable -func (b *ValueBinder) Uint8(sourceParam string, dest *uint8) *ValueBinder { - return b.uintValue(sourceParam, dest, 8, false) -} - -// MustUint8 requires parameter value to exist to bind to uint8 variable. Returns error when value does not exist -func (b *ValueBinder) MustUint8(sourceParam string, dest *uint8) *ValueBinder { - return b.uintValue(sourceParam, dest, 8, true) -} - -// Byte binds parameter to byte variable -func (b *ValueBinder) Byte(sourceParam string, dest *byte) *ValueBinder { - return b.uintValue(sourceParam, dest, 8, false) -} - -// MustByte requires parameter value to exist to bind to byte variable. Returns error when value does not exist -func (b *ValueBinder) MustByte(sourceParam string, dest *byte) *ValueBinder { - return b.uintValue(sourceParam, dest, 8, true) -} - -// Uint binds parameter to uint variable -func (b *ValueBinder) Uint(sourceParam string, dest *uint) *ValueBinder { - return b.uintValue(sourceParam, dest, 0, false) -} - -// MustUint requires parameter value to exist to bind to uint variable. Returns error when value does not exist -func (b *ValueBinder) MustUint(sourceParam string, dest *uint) *ValueBinder { - return b.uintValue(sourceParam, dest, 0, true) -} - -func (b *ValueBinder) uintValue(sourceParam string, dest interface{}, bitSize int, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - - return b.uint(sourceParam, value, dest, bitSize) -} - -func (b *ValueBinder) uint(sourceParam string, value string, dest interface{}, bitSize int) *ValueBinder { - n, err := strconv.ParseUint(value, 10, bitSize) - if err != nil { - if bitSize == 0 { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "failed to bind field value to uint", err)) - } else { - b.setError(b.ErrorFunc(sourceParam, []string{value}, fmt.Sprintf("failed to bind field value to uint%v", bitSize), err)) - } - return b - } - - switch d := dest.(type) { - case *uint64: - *d = n - case *uint32: - *d = uint32(n) - case *uint16: - *d = uint16(n) - case *uint8: // byte is alias to uint8 - *d = uint8(n) - case *uint: - *d = uint(n) - } - return b -} - -func (b *ValueBinder) uintsValue(sourceParam string, dest interface{}, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - values := b.ValuesFunc(sourceParam) - if len(values) == 0 { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, values, "required field value is empty", nil)) - } - return b - } - return b.uints(sourceParam, values, dest) -} - -func (b *ValueBinder) uints(sourceParam string, values []string, dest interface{}) *ValueBinder { - switch d := dest.(type) { - case *[]uint64: - tmp := make([]uint64, len(values)) - for i, v := range values { - b.uint(sourceParam, v, &tmp[i], 64) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]uint32: - tmp := make([]uint32, len(values)) - for i, v := range values { - b.uint(sourceParam, v, &tmp[i], 32) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]uint16: - tmp := make([]uint16, len(values)) - for i, v := range values { - b.uint(sourceParam, v, &tmp[i], 16) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]uint8: // byte is alias to uint8 - tmp := make([]uint8, len(values)) - for i, v := range values { - b.uint(sourceParam, v, &tmp[i], 8) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]uint: - tmp := make([]uint, len(values)) - for i, v := range values { - b.uint(sourceParam, v, &tmp[i], 0) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - } - return b -} - -// Uint64s binds parameter to slice of uint64 -func (b *ValueBinder) Uint64s(sourceParam string, dest *[]uint64) *ValueBinder { - return b.uintsValue(sourceParam, dest, false) -} - -// MustUint64s requires parameter value to exist to bind to uint64 slice variable. Returns error when value does not exist -func (b *ValueBinder) MustUint64s(sourceParam string, dest *[]uint64) *ValueBinder { - return b.uintsValue(sourceParam, dest, true) -} - -// Uint32s binds parameter to slice of uint32 -func (b *ValueBinder) Uint32s(sourceParam string, dest *[]uint32) *ValueBinder { - return b.uintsValue(sourceParam, dest, false) -} - -// MustUint32s requires parameter value to exist to bind to uint32 slice variable. Returns error when value does not exist -func (b *ValueBinder) MustUint32s(sourceParam string, dest *[]uint32) *ValueBinder { - return b.uintsValue(sourceParam, dest, true) -} - -// Uint16s binds parameter to slice of uint16 -func (b *ValueBinder) Uint16s(sourceParam string, dest *[]uint16) *ValueBinder { - return b.uintsValue(sourceParam, dest, false) -} - -// MustUint16s requires parameter value to exist to bind to uint16 slice variable. Returns error when value does not exist -func (b *ValueBinder) MustUint16s(sourceParam string, dest *[]uint16) *ValueBinder { - return b.uintsValue(sourceParam, dest, true) -} - -// Uint8s binds parameter to slice of uint8 -func (b *ValueBinder) Uint8s(sourceParam string, dest *[]uint8) *ValueBinder { - return b.uintsValue(sourceParam, dest, false) -} - -// MustUint8s requires parameter value to exist to bind to uint8 slice variable. Returns error when value does not exist -func (b *ValueBinder) MustUint8s(sourceParam string, dest *[]uint8) *ValueBinder { - return b.uintsValue(sourceParam, dest, true) -} - -// Uints binds parameter to slice of uint -func (b *ValueBinder) Uints(sourceParam string, dest *[]uint) *ValueBinder { - return b.uintsValue(sourceParam, dest, false) -} - -// MustUints requires parameter value to exist to bind to uint slice variable. Returns error when value does not exist -func (b *ValueBinder) MustUints(sourceParam string, dest *[]uint) *ValueBinder { - return b.uintsValue(sourceParam, dest, true) -} - -// Bool binds parameter to bool variable -func (b *ValueBinder) Bool(sourceParam string, dest *bool) *ValueBinder { - return b.boolValue(sourceParam, dest, false) -} - -// MustBool requires parameter value to exist to bind to bool variable. Returns error when value does not exist -func (b *ValueBinder) MustBool(sourceParam string, dest *bool) *ValueBinder { - return b.boolValue(sourceParam, dest, true) -} - -func (b *ValueBinder) boolValue(sourceParam string, dest *bool, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - return b.bool(sourceParam, value, dest) -} - -func (b *ValueBinder) bool(sourceParam string, value string, dest *bool) *ValueBinder { - n, err := strconv.ParseBool(value) - if err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "failed to bind field value to bool", err)) - return b - } - - *dest = n - return b -} - -func (b *ValueBinder) boolsValue(sourceParam string, dest *[]bool, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - values := b.ValuesFunc(sourceParam) - if len(values) == 0 { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - return b.bools(sourceParam, values, dest) -} - -func (b *ValueBinder) bools(sourceParam string, values []string, dest *[]bool) *ValueBinder { - tmp := make([]bool, len(values)) - for i, v := range values { - b.bool(sourceParam, v, &tmp[i]) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *dest = tmp - } - return b -} - -// Bools binds parameter values to slice of bool variables -func (b *ValueBinder) Bools(sourceParam string, dest *[]bool) *ValueBinder { - return b.boolsValue(sourceParam, dest, false) -} - -// MustBools requires parameter values to exist to bind to slice of bool variables. Returns error when values does not exist -func (b *ValueBinder) MustBools(sourceParam string, dest *[]bool) *ValueBinder { - return b.boolsValue(sourceParam, dest, true) -} - -// Float64 binds parameter to float64 variable -func (b *ValueBinder) Float64(sourceParam string, dest *float64) *ValueBinder { - return b.floatValue(sourceParam, dest, 64, false) -} - -// MustFloat64 requires parameter value to exist to bind to float64 variable. Returns error when value does not exist -func (b *ValueBinder) MustFloat64(sourceParam string, dest *float64) *ValueBinder { - return b.floatValue(sourceParam, dest, 64, true) -} - -// Float32 binds parameter to float32 variable -func (b *ValueBinder) Float32(sourceParam string, dest *float32) *ValueBinder { - return b.floatValue(sourceParam, dest, 32, false) -} - -// MustFloat32 requires parameter value to exist to bind to float32 variable. Returns error when value does not exist -func (b *ValueBinder) MustFloat32(sourceParam string, dest *float32) *ValueBinder { - return b.floatValue(sourceParam, dest, 32, true) -} - -func (b *ValueBinder) floatValue(sourceParam string, dest interface{}, bitSize int, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - - return b.float(sourceParam, value, dest, bitSize) -} - -func (b *ValueBinder) float(sourceParam string, value string, dest interface{}, bitSize int) *ValueBinder { - n, err := strconv.ParseFloat(value, bitSize) - if err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{value}, fmt.Sprintf("failed to bind field value to float%v", bitSize), err)) - return b - } - - switch d := dest.(type) { - case *float64: - *d = n - case *float32: - *d = float32(n) - } - return b -} - -func (b *ValueBinder) floatsValue(sourceParam string, dest interface{}, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - values := b.ValuesFunc(sourceParam) - if len(values) == 0 { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - return b.floats(sourceParam, values, dest) -} - -func (b *ValueBinder) floats(sourceParam string, values []string, dest interface{}) *ValueBinder { - switch d := dest.(type) { - case *[]float64: - tmp := make([]float64, len(values)) - for i, v := range values { - b.float(sourceParam, v, &tmp[i], 64) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - case *[]float32: - tmp := make([]float32, len(values)) - for i, v := range values { - b.float(sourceParam, v, &tmp[i], 32) - if b.failFast && b.errors != nil { - return b - } - } - if b.errors == nil { - *d = tmp - } - } - return b -} - -// Float64s binds parameter values to slice of float64 variables -func (b *ValueBinder) Float64s(sourceParam string, dest *[]float64) *ValueBinder { - return b.floatsValue(sourceParam, dest, false) -} - -// MustFloat64s requires parameter values to exist to bind to slice of float64 variables. Returns error when values does not exist -func (b *ValueBinder) MustFloat64s(sourceParam string, dest *[]float64) *ValueBinder { - return b.floatsValue(sourceParam, dest, true) -} - -// Float32s binds parameter values to slice of float32 variables -func (b *ValueBinder) Float32s(sourceParam string, dest *[]float32) *ValueBinder { - return b.floatsValue(sourceParam, dest, false) -} - -// MustFloat32s requires parameter values to exist to bind to slice of float32 variables. Returns error when values does not exist -func (b *ValueBinder) MustFloat32s(sourceParam string, dest *[]float32) *ValueBinder { - return b.floatsValue(sourceParam, dest, true) -} - -// Time binds parameter to time.Time variable -func (b *ValueBinder) Time(sourceParam string, dest *time.Time, layout string) *ValueBinder { - return b.time(sourceParam, dest, layout, false) -} - -// MustTime requires parameter value to exist to bind to time.Time variable. Returns error when value does not exist -func (b *ValueBinder) MustTime(sourceParam string, dest *time.Time, layout string) *ValueBinder { - return b.time(sourceParam, dest, layout, true) -} - -func (b *ValueBinder) time(sourceParam string, dest *time.Time, layout string, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "required field value is empty", nil)) - } - return b - } - t, err := time.Parse(layout, value) - if err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "failed to bind field value to Time", err)) - return b - } - *dest = t - return b -} - -// Times binds parameter values to slice of time.Time variables -func (b *ValueBinder) Times(sourceParam string, dest *[]time.Time, layout string) *ValueBinder { - return b.times(sourceParam, dest, layout, false) -} - -// MustTimes requires parameter values to exist to bind to slice of time.Time variables. Returns error when values does not exist -func (b *ValueBinder) MustTimes(sourceParam string, dest *[]time.Time, layout string) *ValueBinder { - return b.times(sourceParam, dest, layout, true) -} - -func (b *ValueBinder) times(sourceParam string, dest *[]time.Time, layout string, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - values := b.ValuesFunc(sourceParam) - if len(values) == 0 { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - - tmp := make([]time.Time, len(values)) - for i, v := range values { - t, err := time.Parse(layout, v) - if err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{v}, "failed to bind field value to Time", err)) - if b.failFast { - return b - } - continue - } - tmp[i] = t - } - if b.errors == nil { - *dest = tmp - } - return b -} - -// Duration binds parameter to time.Duration variable -func (b *ValueBinder) Duration(sourceParam string, dest *time.Duration) *ValueBinder { - return b.duration(sourceParam, dest, false) -} - -// MustDuration requires parameter value to exist to bind to time.Duration variable. Returns error when value does not exist -func (b *ValueBinder) MustDuration(sourceParam string, dest *time.Duration) *ValueBinder { - return b.duration(sourceParam, dest, true) -} - -func (b *ValueBinder) duration(sourceParam string, dest *time.Duration, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "required field value is empty", nil)) - } - return b - } - t, err := time.ParseDuration(value) - if err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "failed to bind field value to Duration", err)) - return b - } - *dest = t - return b -} - -// Durations binds parameter values to slice of time.Duration variables -func (b *ValueBinder) Durations(sourceParam string, dest *[]time.Duration) *ValueBinder { - return b.durationsValue(sourceParam, dest, false) -} - -// MustDurations requires parameter values to exist to bind to slice of time.Duration variables. Returns error when values does not exist -func (b *ValueBinder) MustDurations(sourceParam string, dest *[]time.Duration) *ValueBinder { - return b.durationsValue(sourceParam, dest, true) -} - -func (b *ValueBinder) durationsValue(sourceParam string, dest *[]time.Duration, valueMustExist bool) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - values := b.ValuesFunc(sourceParam) - if len(values) == 0 { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{}, "required field value is empty", nil)) - } - return b - } - return b.durations(sourceParam, values, dest) -} - -func (b *ValueBinder) durations(sourceParam string, values []string, dest *[]time.Duration) *ValueBinder { - tmp := make([]time.Duration, len(values)) - for i, v := range values { - t, err := time.ParseDuration(v) - if err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{v}, "failed to bind field value to Duration", err)) - if b.failFast { - return b - } - continue - } - tmp[i] = t - } - if b.errors == nil { - *dest = tmp - } - return b -} - -// UnixTime binds parameter to time.Time variable (in local Time corresponding to the given Unix time). -// -// Example: 1609180603 bind to 2020-12-28T18:36:43.000000000+00:00 -// -// Note: -// - time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal -func (b *ValueBinder) UnixTime(sourceParam string, dest *time.Time) *ValueBinder { - return b.unixTime(sourceParam, dest, false, time.Second) -} - -// MustUnixTime requires parameter value to exist to bind to time.Duration variable (in local time corresponding -// to the given Unix time). Returns error when value does not exist. -// -// Example: 1609180603 bind to 2020-12-28T18:36:43.000000000+00:00 -// -// Note: -// - time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal -func (b *ValueBinder) MustUnixTime(sourceParam string, dest *time.Time) *ValueBinder { - return b.unixTime(sourceParam, dest, true, time.Second) -} - -// UnixTimeMilli binds parameter to time.Time variable (in local time corresponding to the given Unix time in millisecond precision). -// -// Example: 1647184410140 bind to 2022-03-13T15:13:30.140000000+00:00 -// -// Note: -// - time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal -func (b *ValueBinder) UnixTimeMilli(sourceParam string, dest *time.Time) *ValueBinder { - return b.unixTime(sourceParam, dest, false, time.Millisecond) -} - -// MustUnixTimeMilli requires parameter value to exist to bind to time.Duration variable (in local time corresponding -// to the given Unix time in millisecond precision). Returns error when value does not exist. -// -// Example: 1647184410140 bind to 2022-03-13T15:13:30.140000000+00:00 -// -// Note: -// - time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal -func (b *ValueBinder) MustUnixTimeMilli(sourceParam string, dest *time.Time) *ValueBinder { - return b.unixTime(sourceParam, dest, true, time.Millisecond) -} - -// UnixTimeNano binds parameter to time.Time variable (in local time corresponding to the given Unix time in nanosecond precision). -// -// Example: 1609180603123456789 binds to 2020-12-28T18:36:43.123456789+00:00 -// Example: 1000000000 binds to 1970-01-01T00:00:01.000000000+00:00 -// Example: 999999999 binds to 1970-01-01T00:00:00.999999999+00:00 -// -// Note: -// - time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal -// - Javascript's Number type only has about 53 bits of precision (Number.MAX_SAFE_INTEGER = 9007199254740991). Compare it to 1609180603123456789 in example. -func (b *ValueBinder) UnixTimeNano(sourceParam string, dest *time.Time) *ValueBinder { - return b.unixTime(sourceParam, dest, false, time.Nanosecond) -} - -// MustUnixTimeNano requires parameter value to exist to bind to time.Duration variable (in local Time corresponding -// to the given Unix time value in nano second precision). Returns error when value does not exist. -// -// Example: 1609180603123456789 binds to 2020-12-28T18:36:43.123456789+00:00 -// Example: 1000000000 binds to 1970-01-01T00:00:01.000000000+00:00 -// Example: 999999999 binds to 1970-01-01T00:00:00.999999999+00:00 -// -// Note: -// - time.Time{} (param is empty) and time.Unix(0,0) (param = "0") are not equal -// - Javascript's Number type only has about 53 bits of precision (Number.MAX_SAFE_INTEGER = 9007199254740991). Compare it to 1609180603123456789 in example. -func (b *ValueBinder) MustUnixTimeNano(sourceParam string, dest *time.Time) *ValueBinder { - return b.unixTime(sourceParam, dest, true, time.Nanosecond) -} - -func (b *ValueBinder) unixTime(sourceParam string, dest *time.Time, valueMustExist bool, precision time.Duration) *ValueBinder { - if b.failFast && b.errors != nil { - return b - } - - value := b.ValueFunc(sourceParam) - if value == "" { - if valueMustExist { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "required field value is empty", nil)) - } - return b - } - - n, err := strconv.ParseInt(value, 10, 64) - if err != nil { - b.setError(b.ErrorFunc(sourceParam, []string{value}, "failed to bind field value to Time", err)) - return b - } - - switch precision { - case time.Second: - *dest = time.Unix(n, 0) - case time.Millisecond: - *dest = time.UnixMilli(n) - case time.Nanosecond: - *dest = time.Unix(0, n) - } - return b -} diff --git a/vendor/github.com/labstack/echo/v4/codecov.yml b/vendor/github.com/labstack/echo/v4/codecov.yml deleted file mode 100644 index 0fa3a3f18..000000000 --- a/vendor/github.com/labstack/echo/v4/codecov.yml +++ /dev/null @@ -1,11 +0,0 @@ -coverage: - status: - project: - default: - threshold: 1% - patch: - default: - threshold: 1% - -comment: - require_changes: true \ No newline at end of file diff --git a/vendor/github.com/labstack/echo/v4/context.go b/vendor/github.com/labstack/echo/v4/context.go deleted file mode 100644 index f5dd5a69d..000000000 --- a/vendor/github.com/labstack/echo/v4/context.go +++ /dev/null @@ -1,660 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "bytes" - "encoding/xml" - "fmt" - "io" - "mime/multipart" - "net" - "net/http" - "net/url" - "strings" - "sync" -) - -// Context represents the context of the current HTTP request. It holds request and -// response objects, path, path parameters, data and registered handler. -type Context interface { - // Request returns `*http.Request`. - Request() *http.Request - - // SetRequest sets `*http.Request`. - SetRequest(r *http.Request) - - // SetResponse sets `*Response`. - SetResponse(r *Response) - - // Response returns `*Response`. - Response() *Response - - // IsTLS returns true if HTTP connection is TLS otherwise false. - IsTLS() bool - - // IsWebSocket returns true if HTTP connection is WebSocket otherwise false. - IsWebSocket() bool - - // Scheme returns the HTTP protocol scheme, `http` or `https`. - Scheme() string - - // RealIP returns the client's network address based on `X-Forwarded-For` - // or `X-Real-IP` request header. - // The behavior can be configured using `Echo#IPExtractor`. - RealIP() string - - // Path returns the registered path for the handler. - Path() string - - // SetPath sets the registered path for the handler. - SetPath(p string) - - // Param returns path parameter by name. - Param(name string) string - - // ParamNames returns path parameter names. - ParamNames() []string - - // SetParamNames sets path parameter names. - SetParamNames(names ...string) - - // ParamValues returns path parameter values. - ParamValues() []string - - // SetParamValues sets path parameter values. - SetParamValues(values ...string) - - // QueryParam returns the query param for the provided name. - QueryParam(name string) string - - // QueryParams returns the query parameters as `url.Values`. - QueryParams() url.Values - - // QueryString returns the URL query string. - QueryString() string - - // FormValue returns the form field value for the provided name. - FormValue(name string) string - - // FormParams returns the form parameters as `url.Values`. - FormParams() (url.Values, error) - - // FormFile returns the multipart form file for the provided name. - FormFile(name string) (*multipart.FileHeader, error) - - // MultipartForm returns the multipart form. - MultipartForm() (*multipart.Form, error) - - // Cookie returns the named cookie provided in the request. - Cookie(name string) (*http.Cookie, error) - - // SetCookie adds a `Set-Cookie` header in HTTP response. - SetCookie(cookie *http.Cookie) - - // Cookies returns the HTTP cookies sent with the request. - Cookies() []*http.Cookie - - // Get retrieves data from the context. - Get(key string) interface{} - - // Set saves data in the context. - Set(key string, val interface{}) - - // Bind binds path params, query params and the request body into provided type `i`. The default binder - // binds body based on Content-Type header. - Bind(i interface{}) error - - // Validate validates provided `i`. It is usually called after `Context#Bind()`. - // Validator must be registered using `Echo#Validator`. - Validate(i interface{}) error - - // Render renders a template with data and sends a text/html response with status - // code. Renderer must be registered using `Echo.Renderer`. - Render(code int, name string, data interface{}) error - - // HTML sends an HTTP response with status code. - HTML(code int, html string) error - - // HTMLBlob sends an HTTP blob response with status code. - HTMLBlob(code int, b []byte) error - - // String sends a string response with status code. - String(code int, s string) error - - // JSON sends a JSON response with status code. - JSON(code int, i interface{}) error - - // JSONPretty sends a pretty-print JSON with status code. - JSONPretty(code int, i interface{}, indent string) error - - // JSONBlob sends a JSON blob response with status code. - JSONBlob(code int, b []byte) error - - // JSONP sends a JSONP response with status code. It uses `callback` to construct - // the JSONP payload. - JSONP(code int, callback string, i interface{}) error - - // JSONPBlob sends a JSONP blob response with status code. It uses `callback` - // to construct the JSONP payload. - JSONPBlob(code int, callback string, b []byte) error - - // XML sends an XML response with status code. - XML(code int, i interface{}) error - - // XMLPretty sends a pretty-print XML with status code. - XMLPretty(code int, i interface{}, indent string) error - - // XMLBlob sends an XML blob response with status code. - XMLBlob(code int, b []byte) error - - // Blob sends a blob response with status code and content type. - Blob(code int, contentType string, b []byte) error - - // Stream sends a streaming response with status code and content type. - Stream(code int, contentType string, r io.Reader) error - - // File sends a response with the content of the file. - File(file string) error - - // Attachment sends a response as attachment, prompting client to save the - // file. - Attachment(file string, name string) error - - // Inline sends a response as inline, opening the file in the browser. - Inline(file string, name string) error - - // NoContent sends a response with no body and a status code. - NoContent(code int) error - - // Redirect redirects the request to a provided URL with status code. - Redirect(code int, url string) error - - // Error invokes the registered global HTTP error handler. Generally used by middleware. - // A side-effect of calling global error handler is that now Response has been committed (sent to the client) and - // middlewares up in chain can not change Response status code or Response body anymore. - // - // Avoid using this method in handlers as no middleware will be able to effectively handle errors after that. - Error(err error) - - // Handler returns the matched handler by router. - Handler() HandlerFunc - - // SetHandler sets the matched handler by router. - SetHandler(h HandlerFunc) - - // Logger returns the `Logger` instance. - Logger() Logger - - // SetLogger Set the logger - SetLogger(l Logger) - - // Echo returns the `Echo` instance. - Echo() *Echo - - // Reset resets the context after request completes. It must be called along - // with `Echo#AcquireContext()` and `Echo#ReleaseContext()`. - // See `Echo#ServeHTTP()` - Reset(r *http.Request, w http.ResponseWriter) -} - -type context struct { - logger Logger - request *http.Request - response *Response - query url.Values - echo *Echo - - store Map - lock sync.RWMutex - - // following fields are set by Router - handler HandlerFunc - - // path is route path that Router matched. It is empty string where there is no route match. - // Route registered with RouteNotFound is considered as a match and path therefore is not empty. - path string - - // Usually echo.Echo is sizing pvalues but there could be user created middlewares that decide to - // overwrite parameter by calling SetParamNames + SetParamValues. - // When echo.Echo allocated that slice it length/capacity is tied to echo.Echo.maxParam value. - // - // It is important that pvalues size is always equal or bigger to pnames length. - pvalues []string - - // pnames length is tied to param count for the matched route - pnames []string -} - -const ( - // ContextKeyHeaderAllow is set by Router for getting value for `Allow` header in later stages of handler call chain. - // Allow header is mandatory for status 405 (method not found) and useful for OPTIONS method requests. - // It is added to context only when Router does not find matching method handler for request. - ContextKeyHeaderAllow = "echo_header_allow" -) - -const ( - defaultMemory = 32 << 20 // 32 MB - indexPage = "index.html" - defaultIndent = " " -) - -func (c *context) writeContentType(value string) { - header := c.Response().Header() - if header.Get(HeaderContentType) == "" { - header.Set(HeaderContentType, value) - } -} - -func (c *context) Request() *http.Request { - return c.request -} - -func (c *context) SetRequest(r *http.Request) { - c.request = r -} - -func (c *context) Response() *Response { - return c.response -} - -func (c *context) SetResponse(r *Response) { - c.response = r -} - -func (c *context) IsTLS() bool { - return c.request.TLS != nil -} - -func (c *context) IsWebSocket() bool { - upgrade := c.request.Header.Get(HeaderUpgrade) - return strings.EqualFold(upgrade, "websocket") -} - -func (c *context) Scheme() string { - // Can't use `r.Request.URL.Scheme` - // See: https://groups.google.com/forum/#!topic/golang-nuts/pMUkBlQBDF0 - if c.IsTLS() { - return "https" - } - if scheme := c.request.Header.Get(HeaderXForwardedProto); scheme != "" { - return scheme - } - if scheme := c.request.Header.Get(HeaderXForwardedProtocol); scheme != "" { - return scheme - } - if ssl := c.request.Header.Get(HeaderXForwardedSsl); ssl == "on" { - return "https" - } - if scheme := c.request.Header.Get(HeaderXUrlScheme); scheme != "" { - return scheme - } - return "http" -} - -func (c *context) RealIP() string { - if c.echo != nil && c.echo.IPExtractor != nil { - return c.echo.IPExtractor(c.request) - } - // Fall back to legacy behavior - if ip := c.request.Header.Get(HeaderXForwardedFor); ip != "" { - i := strings.IndexAny(ip, ",") - if i > 0 { - xffip := strings.TrimSpace(ip[:i]) - xffip = strings.TrimPrefix(xffip, "[") - xffip = strings.TrimSuffix(xffip, "]") - return xffip - } - return ip - } - if ip := c.request.Header.Get(HeaderXRealIP); ip != "" { - ip = strings.TrimPrefix(ip, "[") - ip = strings.TrimSuffix(ip, "]") - return ip - } - ra, _, _ := net.SplitHostPort(c.request.RemoteAddr) - return ra -} - -func (c *context) Path() string { - return c.path -} - -func (c *context) SetPath(p string) { - c.path = p -} - -func (c *context) Param(name string) string { - for i, n := range c.pnames { - if i < len(c.pvalues) { - if n == name { - return c.pvalues[i] - } - } - } - return "" -} - -func (c *context) ParamNames() []string { - return c.pnames -} - -func (c *context) SetParamNames(names ...string) { - c.pnames = names - - l := len(names) - if len(c.pvalues) < l { - // Keeping the old pvalues just for backward compatibility, but it sounds that doesn't make sense to keep them, - // probably those values will be overridden in a Context#SetParamValues - newPvalues := make([]string, l) - copy(newPvalues, c.pvalues) - c.pvalues = newPvalues - } -} - -func (c *context) ParamValues() []string { - return c.pvalues[:len(c.pnames)] -} - -func (c *context) SetParamValues(values ...string) { - // NOTE: Don't just set c.pvalues = values, because it has to have length c.echo.maxParam (or bigger) at all times - // It will brake the Router#Find code - limit := len(values) - if limit > len(c.pvalues) { - c.pvalues = make([]string, limit) - } - for i := 0; i < limit; i++ { - c.pvalues[i] = values[i] - } -} - -func (c *context) QueryParam(name string) string { - if c.query == nil { - c.query = c.request.URL.Query() - } - return c.query.Get(name) -} - -func (c *context) QueryParams() url.Values { - if c.query == nil { - c.query = c.request.URL.Query() - } - return c.query -} - -func (c *context) QueryString() string { - return c.request.URL.RawQuery -} - -func (c *context) FormValue(name string) string { - return c.request.FormValue(name) -} - -func (c *context) FormParams() (url.Values, error) { - if strings.HasPrefix(c.request.Header.Get(HeaderContentType), MIMEMultipartForm) { - if err := c.request.ParseMultipartForm(defaultMemory); err != nil { - return nil, err - } - } else { - if err := c.request.ParseForm(); err != nil { - return nil, err - } - } - return c.request.Form, nil -} - -func (c *context) FormFile(name string) (*multipart.FileHeader, error) { - f, fh, err := c.request.FormFile(name) - if err != nil { - return nil, err - } - f.Close() - return fh, nil -} - -func (c *context) MultipartForm() (*multipart.Form, error) { - err := c.request.ParseMultipartForm(defaultMemory) - return c.request.MultipartForm, err -} - -func (c *context) Cookie(name string) (*http.Cookie, error) { - return c.request.Cookie(name) -} - -func (c *context) SetCookie(cookie *http.Cookie) { - http.SetCookie(c.Response(), cookie) -} - -func (c *context) Cookies() []*http.Cookie { - return c.request.Cookies() -} - -func (c *context) Get(key string) interface{} { - c.lock.RLock() - defer c.lock.RUnlock() - return c.store[key] -} - -func (c *context) Set(key string, val interface{}) { - c.lock.Lock() - defer c.lock.Unlock() - - if c.store == nil { - c.store = make(Map) - } - c.store[key] = val -} - -func (c *context) Bind(i interface{}) error { - return c.echo.Binder.Bind(i, c) -} - -func (c *context) Validate(i interface{}) error { - if c.echo.Validator == nil { - return ErrValidatorNotRegistered - } - return c.echo.Validator.Validate(i) -} - -func (c *context) Render(code int, name string, data interface{}) (err error) { - if c.echo.Renderer == nil { - return ErrRendererNotRegistered - } - buf := new(bytes.Buffer) - if err = c.echo.Renderer.Render(buf, name, data, c); err != nil { - return - } - return c.HTMLBlob(code, buf.Bytes()) -} - -func (c *context) HTML(code int, html string) (err error) { - return c.HTMLBlob(code, []byte(html)) -} - -func (c *context) HTMLBlob(code int, b []byte) (err error) { - return c.Blob(code, MIMETextHTMLCharsetUTF8, b) -} - -func (c *context) String(code int, s string) (err error) { - return c.Blob(code, MIMETextPlainCharsetUTF8, []byte(s)) -} - -func (c *context) jsonPBlob(code int, callback string, i interface{}) (err error) { - indent := "" - if _, pretty := c.QueryParams()["pretty"]; c.echo.Debug || pretty { - indent = defaultIndent - } - c.writeContentType(MIMEApplicationJavaScriptCharsetUTF8) - c.response.WriteHeader(code) - if _, err = c.response.Write([]byte(callback + "(")); err != nil { - return - } - if err = c.echo.JSONSerializer.Serialize(c, i, indent); err != nil { - return - } - if _, err = c.response.Write([]byte(");")); err != nil { - return - } - return -} - -func (c *context) json(code int, i interface{}, indent string) error { - c.writeContentType(MIMEApplicationJSON) - c.response.Status = code - return c.echo.JSONSerializer.Serialize(c, i, indent) -} - -func (c *context) JSON(code int, i interface{}) (err error) { - indent := "" - if _, pretty := c.QueryParams()["pretty"]; c.echo.Debug || pretty { - indent = defaultIndent - } - return c.json(code, i, indent) -} - -func (c *context) JSONPretty(code int, i interface{}, indent string) (err error) { - return c.json(code, i, indent) -} - -func (c *context) JSONBlob(code int, b []byte) (err error) { - return c.Blob(code, MIMEApplicationJSON, b) -} - -func (c *context) JSONP(code int, callback string, i interface{}) (err error) { - return c.jsonPBlob(code, callback, i) -} - -func (c *context) JSONPBlob(code int, callback string, b []byte) (err error) { - c.writeContentType(MIMEApplicationJavaScriptCharsetUTF8) - c.response.WriteHeader(code) - if _, err = c.response.Write([]byte(callback + "(")); err != nil { - return - } - if _, err = c.response.Write(b); err != nil { - return - } - _, err = c.response.Write([]byte(");")) - return -} - -func (c *context) xml(code int, i interface{}, indent string) (err error) { - c.writeContentType(MIMEApplicationXMLCharsetUTF8) - c.response.WriteHeader(code) - enc := xml.NewEncoder(c.response) - if indent != "" { - enc.Indent("", indent) - } - if _, err = c.response.Write([]byte(xml.Header)); err != nil { - return - } - return enc.Encode(i) -} - -func (c *context) XML(code int, i interface{}) (err error) { - indent := "" - if _, pretty := c.QueryParams()["pretty"]; c.echo.Debug || pretty { - indent = defaultIndent - } - return c.xml(code, i, indent) -} - -func (c *context) XMLPretty(code int, i interface{}, indent string) (err error) { - return c.xml(code, i, indent) -} - -func (c *context) XMLBlob(code int, b []byte) (err error) { - c.writeContentType(MIMEApplicationXMLCharsetUTF8) - c.response.WriteHeader(code) - if _, err = c.response.Write([]byte(xml.Header)); err != nil { - return - } - _, err = c.response.Write(b) - return -} - -func (c *context) Blob(code int, contentType string, b []byte) (err error) { - c.writeContentType(contentType) - c.response.WriteHeader(code) - _, err = c.response.Write(b) - return -} - -func (c *context) Stream(code int, contentType string, r io.Reader) (err error) { - c.writeContentType(contentType) - c.response.WriteHeader(code) - _, err = io.Copy(c.response, r) - return -} - -func (c *context) Attachment(file, name string) error { - return c.contentDisposition(file, name, "attachment") -} - -func (c *context) Inline(file, name string) error { - return c.contentDisposition(file, name, "inline") -} - -var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") - -func (c *context) contentDisposition(file, name, dispositionType string) error { - c.response.Header().Set(HeaderContentDisposition, fmt.Sprintf(`%s; filename="%s"`, dispositionType, quoteEscaper.Replace(name))) - return c.File(file) -} - -func (c *context) NoContent(code int) error { - c.response.WriteHeader(code) - return nil -} - -func (c *context) Redirect(code int, url string) error { - if code < 300 || code > 308 { - return ErrInvalidRedirectCode - } - c.response.Header().Set(HeaderLocation, url) - c.response.WriteHeader(code) - return nil -} - -func (c *context) Error(err error) { - c.echo.HTTPErrorHandler(err, c) -} - -func (c *context) Echo() *Echo { - return c.echo -} - -func (c *context) Handler() HandlerFunc { - return c.handler -} - -func (c *context) SetHandler(h HandlerFunc) { - c.handler = h -} - -func (c *context) Logger() Logger { - res := c.logger - if res != nil { - return res - } - return c.echo.Logger -} - -func (c *context) SetLogger(l Logger) { - c.logger = l -} - -func (c *context) Reset(r *http.Request, w http.ResponseWriter) { - c.request = r - c.response.reset(w) - c.query = nil - c.handler = NotFoundHandler - c.store = nil - c.path = "" - c.pnames = nil - c.logger = nil - // NOTE: Don't reset because it has to have length c.echo.maxParam (or bigger) at all times - for i := 0; i < len(c.pvalues); i++ { - c.pvalues[i] = "" - } -} diff --git a/vendor/github.com/labstack/echo/v4/context_fs.go b/vendor/github.com/labstack/echo/v4/context_fs.go deleted file mode 100644 index 1c25baf12..000000000 --- a/vendor/github.com/labstack/echo/v4/context_fs.go +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "errors" - "io" - "io/fs" - "net/http" - "path/filepath" -) - -func (c *context) File(file string) error { - return fsFile(c, file, c.echo.Filesystem) -} - -// FileFS serves file from given file system. -// -// When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary -// prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths -// including `assets/images` as their prefix. -func (c *context) FileFS(file string, filesystem fs.FS) error { - return fsFile(c, file, filesystem) -} - -func fsFile(c Context, file string, filesystem fs.FS) error { - f, err := filesystem.Open(file) - if err != nil { - return ErrNotFound - } - defer f.Close() - - fi, _ := f.Stat() - if fi.IsDir() { - file = filepath.ToSlash(filepath.Join(file, indexPage)) // ToSlash is necessary for Windows. fs.Open and os.Open are different in that aspect. - f, err = filesystem.Open(file) - if err != nil { - return ErrNotFound - } - defer f.Close() - if fi, err = f.Stat(); err != nil { - return err - } - } - ff, ok := f.(io.ReadSeeker) - if !ok { - return errors.New("file does not implement io.ReadSeeker") - } - http.ServeContent(c.Response(), c.Request(), fi.Name(), fi.ModTime(), ff) - return nil -} diff --git a/vendor/github.com/labstack/echo/v4/echo.go b/vendor/github.com/labstack/echo/v4/echo.go deleted file mode 100644 index 60f7061d8..000000000 --- a/vendor/github.com/labstack/echo/v4/echo.go +++ /dev/null @@ -1,1015 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -/* -Package echo implements high performance, minimalist Go web framework. - -Example: - - package main - - import ( - "net/http" - - "github.com/labstack/echo/v4" - "github.com/labstack/echo/v4/middleware" - ) - - // Handler - func hello(c echo.Context) error { - return c.String(http.StatusOK, "Hello, World!") - } - - func main() { - // Echo instance - e := echo.New() - - // Middleware - e.Use(middleware.Logger()) - e.Use(middleware.Recover()) - - // Routes - e.GET("/", hello) - - // Start server - e.Logger.Fatal(e.Start(":1323")) - } - -Learn more at https://echo.labstack.com -*/ -package echo - -import ( - stdContext "context" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - stdLog "log" - "net" - "net/http" - "os" - "reflect" - "runtime" - "sync" - "time" - - "github.com/labstack/gommon/color" - "github.com/labstack/gommon/log" - "golang.org/x/crypto/acme" - "golang.org/x/crypto/acme/autocert" - "golang.org/x/net/http2" - "golang.org/x/net/http2/h2c" -) - -// Echo is the top-level framework instance. -// -// Goroutine safety: Do not mutate Echo instance fields after server has started. Accessing these -// fields from handlers/middlewares and changing field values at the same time leads to data-races. -// Adding new routes after the server has been started is also not safe! -type Echo struct { - filesystem - common - // startupMutex is mutex to lock Echo instance access during server configuration and startup. Useful for to get - // listener address info (on which interface/port was listener bound) without having data races. - startupMutex sync.RWMutex - colorer *color.Color - - // premiddleware are middlewares that are run before routing is done. In case a pre-middleware returns - // an error the router is not executed and the request will end up in the global error handler. - premiddleware []MiddlewareFunc - middleware []MiddlewareFunc - maxParam *int - router *Router - routers map[string]*Router - pool sync.Pool - - StdLogger *stdLog.Logger - Server *http.Server - TLSServer *http.Server - Listener net.Listener - TLSListener net.Listener - AutoTLSManager autocert.Manager - HTTPErrorHandler HTTPErrorHandler - Binder Binder - JSONSerializer JSONSerializer - Validator Validator - Renderer Renderer - Logger Logger - IPExtractor IPExtractor - ListenerNetwork string - - // OnAddRouteHandler is called when Echo adds new route to specific host router. - OnAddRouteHandler func(host string, route Route, handler HandlerFunc, middleware []MiddlewareFunc) - DisableHTTP2 bool - Debug bool - HideBanner bool - HidePort bool -} - -// Route contains a handler and information for matching against requests. -type Route struct { - Method string `json:"method"` - Path string `json:"path"` - Name string `json:"name"` -} - -// HTTPError represents an error that occurred while handling a request. -type HTTPError struct { - Internal error `json:"-"` // Stores the error returned by an external dependency - Message interface{} `json:"message"` - Code int `json:"-"` -} - -// MiddlewareFunc defines a function to process middleware. -type MiddlewareFunc func(next HandlerFunc) HandlerFunc - -// HandlerFunc defines a function to serve HTTP requests. -type HandlerFunc func(c Context) error - -// HTTPErrorHandler is a centralized HTTP error handler. -type HTTPErrorHandler func(err error, c Context) - -// Validator is the interface that wraps the Validate function. -type Validator interface { - Validate(i interface{}) error -} - -// JSONSerializer is the interface that encodes and decodes JSON to and from interfaces. -type JSONSerializer interface { - Serialize(c Context, i interface{}, indent string) error - Deserialize(c Context, i interface{}) error -} - -// Map defines a generic map of type `map[string]interface{}`. -type Map map[string]interface{} - -// Common struct for Echo & Group. -type common struct{} - -// HTTP methods -// NOTE: Deprecated, please use the stdlib constants directly instead. -const ( - CONNECT = http.MethodConnect - DELETE = http.MethodDelete - GET = http.MethodGet - HEAD = http.MethodHead - OPTIONS = http.MethodOptions - PATCH = http.MethodPatch - POST = http.MethodPost - // PROPFIND = "PROPFIND" - PUT = http.MethodPut - TRACE = http.MethodTrace -) - -// MIME types -const ( - // MIMEApplicationJSON JavaScript Object Notation (JSON) https://www.rfc-editor.org/rfc/rfc8259 - MIMEApplicationJSON = "application/json" - // Deprecated: Please use MIMEApplicationJSON instead. JSON should be encoded using UTF-8 by default. - // No "charset" parameter is defined for this registration. - // Adding one really has no effect on compliant recipients. - // See RFC 8259, section 8.1. https://datatracker.ietf.org/doc/html/rfc8259#section-8.1 - MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 - MIMEApplicationJavaScript = "application/javascript" - MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 - MIMEApplicationXML = "application/xml" - MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 - MIMETextXML = "text/xml" - MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8 - MIMEApplicationForm = "application/x-www-form-urlencoded" - MIMEApplicationProtobuf = "application/protobuf" - MIMEApplicationMsgpack = "application/msgpack" - MIMETextHTML = "text/html" - MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8 - MIMETextPlain = "text/plain" - MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8 - MIMEMultipartForm = "multipart/form-data" - MIMEOctetStream = "application/octet-stream" -) - -const ( - charsetUTF8 = "charset=UTF-8" - // PROPFIND Method can be used on collection and property resources. - PROPFIND = "PROPFIND" - // REPORT Method can be used to get information about a resource, see rfc 3253 - REPORT = "REPORT" - // RouteNotFound is special method type for routes handling "route not found" (404) cases - RouteNotFound = "echo_route_not_found" -) - -// Headers -const ( - HeaderAccept = "Accept" - HeaderAcceptEncoding = "Accept-Encoding" - // HeaderAllow is the name of the "Allow" header field used to list the set of methods - // advertised as supported by the target resource. Returning an Allow header is mandatory - // for status 405 (method not found) and useful for the OPTIONS method in responses. - // See RFC 7231: https://datatracker.ietf.org/doc/html/rfc7231#section-7.4.1 - HeaderAllow = "Allow" - HeaderAuthorization = "Authorization" - HeaderContentDisposition = "Content-Disposition" - HeaderContentEncoding = "Content-Encoding" - HeaderContentLength = "Content-Length" - HeaderContentType = "Content-Type" - HeaderCookie = "Cookie" - HeaderSetCookie = "Set-Cookie" - HeaderIfModifiedSince = "If-Modified-Since" - HeaderLastModified = "Last-Modified" - HeaderLocation = "Location" - HeaderRetryAfter = "Retry-After" - HeaderUpgrade = "Upgrade" - HeaderVary = "Vary" - HeaderWWWAuthenticate = "WWW-Authenticate" - HeaderXForwardedFor = "X-Forwarded-For" - HeaderXForwardedProto = "X-Forwarded-Proto" - HeaderXForwardedProtocol = "X-Forwarded-Protocol" - HeaderXForwardedSsl = "X-Forwarded-Ssl" - HeaderXUrlScheme = "X-Url-Scheme" - HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" - HeaderXRealIP = "X-Real-Ip" - HeaderXRequestID = "X-Request-Id" - HeaderXCorrelationID = "X-Correlation-Id" - HeaderXRequestedWith = "X-Requested-With" - HeaderServer = "Server" - HeaderOrigin = "Origin" - HeaderCacheControl = "Cache-Control" - HeaderConnection = "Connection" - - // Access control - HeaderAccessControlRequestMethod = "Access-Control-Request-Method" - HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" - HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" - HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" - HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" - HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" - HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" - HeaderAccessControlMaxAge = "Access-Control-Max-Age" - - // Security - HeaderStrictTransportSecurity = "Strict-Transport-Security" - HeaderXContentTypeOptions = "X-Content-Type-Options" - HeaderXXSSProtection = "X-XSS-Protection" - HeaderXFrameOptions = "X-Frame-Options" - HeaderContentSecurityPolicy = "Content-Security-Policy" - HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" - HeaderXCSRFToken = "X-CSRF-Token" - HeaderReferrerPolicy = "Referrer-Policy" -) - -const ( - // Version of Echo - Version = "4.13.3" - website = "https://echo.labstack.com" - // http://patorjk.com/software/taag/#p=display&f=Small%20Slant&t=Echo - banner = ` - ____ __ - / __/___/ / ___ - / _// __/ _ \/ _ \ -/___/\__/_//_/\___/ %s -High performance, minimalist Go web framework -%s -____________________________________O/_______ - O\ -` -) - -var methods = [...]string{ - http.MethodConnect, - http.MethodDelete, - http.MethodGet, - http.MethodHead, - http.MethodOptions, - http.MethodPatch, - http.MethodPost, - PROPFIND, - http.MethodPut, - http.MethodTrace, - REPORT, -} - -// Errors -var ( - ErrBadRequest = NewHTTPError(http.StatusBadRequest) // HTTP 400 Bad Request - ErrUnauthorized = NewHTTPError(http.StatusUnauthorized) // HTTP 401 Unauthorized - ErrPaymentRequired = NewHTTPError(http.StatusPaymentRequired) // HTTP 402 Payment Required - ErrForbidden = NewHTTPError(http.StatusForbidden) // HTTP 403 Forbidden - ErrNotFound = NewHTTPError(http.StatusNotFound) // HTTP 404 Not Found - ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed) // HTTP 405 Method Not Allowed - ErrNotAcceptable = NewHTTPError(http.StatusNotAcceptable) // HTTP 406 Not Acceptable - ErrProxyAuthRequired = NewHTTPError(http.StatusProxyAuthRequired) // HTTP 407 Proxy AuthRequired - ErrRequestTimeout = NewHTTPError(http.StatusRequestTimeout) // HTTP 408 Request Timeout - ErrConflict = NewHTTPError(http.StatusConflict) // HTTP 409 Conflict - ErrGone = NewHTTPError(http.StatusGone) // HTTP 410 Gone - ErrLengthRequired = NewHTTPError(http.StatusLengthRequired) // HTTP 411 Length Required - ErrPreconditionFailed = NewHTTPError(http.StatusPreconditionFailed) // HTTP 412 Precondition Failed - ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge) // HTTP 413 Payload Too Large - ErrRequestURITooLong = NewHTTPError(http.StatusRequestURITooLong) // HTTP 414 URI Too Long - ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType) // HTTP 415 Unsupported Media Type - ErrRequestedRangeNotSatisfiable = NewHTTPError(http.StatusRequestedRangeNotSatisfiable) // HTTP 416 Range Not Satisfiable - ErrExpectationFailed = NewHTTPError(http.StatusExpectationFailed) // HTTP 417 Expectation Failed - ErrTeapot = NewHTTPError(http.StatusTeapot) // HTTP 418 I'm a teapot - ErrMisdirectedRequest = NewHTTPError(http.StatusMisdirectedRequest) // HTTP 421 Misdirected Request - ErrUnprocessableEntity = NewHTTPError(http.StatusUnprocessableEntity) // HTTP 422 Unprocessable Entity - ErrLocked = NewHTTPError(http.StatusLocked) // HTTP 423 Locked - ErrFailedDependency = NewHTTPError(http.StatusFailedDependency) // HTTP 424 Failed Dependency - ErrTooEarly = NewHTTPError(http.StatusTooEarly) // HTTP 425 Too Early - ErrUpgradeRequired = NewHTTPError(http.StatusUpgradeRequired) // HTTP 426 Upgrade Required - ErrPreconditionRequired = NewHTTPError(http.StatusPreconditionRequired) // HTTP 428 Precondition Required - ErrTooManyRequests = NewHTTPError(http.StatusTooManyRequests) // HTTP 429 Too Many Requests - ErrRequestHeaderFieldsTooLarge = NewHTTPError(http.StatusRequestHeaderFieldsTooLarge) // HTTP 431 Request Header Fields Too Large - ErrUnavailableForLegalReasons = NewHTTPError(http.StatusUnavailableForLegalReasons) // HTTP 451 Unavailable For Legal Reasons - ErrInternalServerError = NewHTTPError(http.StatusInternalServerError) // HTTP 500 Internal Server Error - ErrNotImplemented = NewHTTPError(http.StatusNotImplemented) // HTTP 501 Not Implemented - ErrBadGateway = NewHTTPError(http.StatusBadGateway) // HTTP 502 Bad Gateway - ErrServiceUnavailable = NewHTTPError(http.StatusServiceUnavailable) // HTTP 503 Service Unavailable - ErrGatewayTimeout = NewHTTPError(http.StatusGatewayTimeout) // HTTP 504 Gateway Timeout - ErrHTTPVersionNotSupported = NewHTTPError(http.StatusHTTPVersionNotSupported) // HTTP 505 HTTP Version Not Supported - ErrVariantAlsoNegotiates = NewHTTPError(http.StatusVariantAlsoNegotiates) // HTTP 506 Variant Also Negotiates - ErrInsufficientStorage = NewHTTPError(http.StatusInsufficientStorage) // HTTP 507 Insufficient Storage - ErrLoopDetected = NewHTTPError(http.StatusLoopDetected) // HTTP 508 Loop Detected - ErrNotExtended = NewHTTPError(http.StatusNotExtended) // HTTP 510 Not Extended - ErrNetworkAuthenticationRequired = NewHTTPError(http.StatusNetworkAuthenticationRequired) // HTTP 511 Network Authentication Required - - ErrValidatorNotRegistered = errors.New("validator not registered") - ErrRendererNotRegistered = errors.New("renderer not registered") - ErrInvalidRedirectCode = errors.New("invalid redirect status code") - ErrCookieNotFound = errors.New("cookie not found") - ErrInvalidCertOrKeyType = errors.New("invalid cert or key type, must be string or []byte") - ErrInvalidListenerNetwork = errors.New("invalid listener network") -) - -// NotFoundHandler is the handler that router uses in case there was no matching route found. Returns an error that results -// HTTP 404 status code. -var NotFoundHandler = func(c Context) error { - return ErrNotFound -} - -// MethodNotAllowedHandler is the handler thar router uses in case there was no matching route found but there was -// another matching routes for that requested URL. Returns an error that results HTTP 405 Method Not Allowed status code. -var MethodNotAllowedHandler = func(c Context) error { - // See RFC 7231 section 7.4.1: An origin server MUST generate an Allow field in a 405 (Method Not Allowed) - // response and MAY do so in any other response. For disabled resources an empty Allow header may be returned - routerAllowMethods, ok := c.Get(ContextKeyHeaderAllow).(string) - if ok && routerAllowMethods != "" { - c.Response().Header().Set(HeaderAllow, routerAllowMethods) - } - return ErrMethodNotAllowed -} - -// New creates an instance of Echo. -func New() (e *Echo) { - e = &Echo{ - filesystem: createFilesystem(), - Server: new(http.Server), - TLSServer: new(http.Server), - AutoTLSManager: autocert.Manager{ - Prompt: autocert.AcceptTOS, - }, - Logger: log.New("echo"), - colorer: color.New(), - maxParam: new(int), - ListenerNetwork: "tcp", - } - e.Server.Handler = e - e.TLSServer.Handler = e - e.HTTPErrorHandler = e.DefaultHTTPErrorHandler - e.Binder = &DefaultBinder{} - e.JSONSerializer = &DefaultJSONSerializer{} - e.Logger.SetLevel(log.ERROR) - e.StdLogger = stdLog.New(e.Logger.Output(), e.Logger.Prefix()+": ", 0) - e.pool.New = func() interface{} { - return e.NewContext(nil, nil) - } - e.router = NewRouter(e) - e.routers = map[string]*Router{} - return -} - -// NewContext returns a Context instance. -func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context { - return &context{ - request: r, - response: NewResponse(w, e), - store: make(Map), - echo: e, - pvalues: make([]string, *e.maxParam), - handler: NotFoundHandler, - } -} - -// Router returns the default router. -func (e *Echo) Router() *Router { - return e.router -} - -// Routers returns the map of host => router. -func (e *Echo) Routers() map[string]*Router { - return e.routers -} - -// DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response -// with status code. -// -// NOTE: In case errors happens in middleware call-chain that is returning from handler (which did not return an error). -// When handler has already sent response (ala c.JSON()) and there is error in middleware that is returning from -// handler. Then the error that global error handler received will be ignored because we have already "committed" the -// response and status code header has been sent to the client. -func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) { - - if c.Response().Committed { - return - } - - he, ok := err.(*HTTPError) - if ok { - if he.Internal != nil { - if herr, ok := he.Internal.(*HTTPError); ok { - he = herr - } - } - } else { - he = &HTTPError{ - Code: http.StatusInternalServerError, - Message: http.StatusText(http.StatusInternalServerError), - } - } - - // Issue #1426 - code := he.Code - message := he.Message - - switch m := he.Message.(type) { - case string: - if e.Debug { - message = Map{"message": m, "error": err.Error()} - } else { - message = Map{"message": m} - } - case json.Marshaler: - // do nothing - this type knows how to format itself to JSON - case error: - message = Map{"message": m.Error()} - } - - // Send response - if c.Request().Method == http.MethodHead { // Issue #608 - err = c.NoContent(he.Code) - } else { - err = c.JSON(code, message) - } - if err != nil { - e.Logger.Error(err) - } -} - -// Pre adds middleware to the chain which is run before router. -func (e *Echo) Pre(middleware ...MiddlewareFunc) { - e.premiddleware = append(e.premiddleware, middleware...) -} - -// Use adds middleware to the chain which is run after router. -func (e *Echo) Use(middleware ...MiddlewareFunc) { - e.middleware = append(e.middleware, middleware...) -} - -// CONNECT registers a new CONNECT route for a path with matching handler in the -// router with optional route-level middleware. -func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodConnect, path, h, m...) -} - -// DELETE registers a new DELETE route for a path with matching handler in the router -// with optional route-level middleware. -func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodDelete, path, h, m...) -} - -// GET registers a new GET route for a path with matching handler in the router -// with optional route-level middleware. -func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodGet, path, h, m...) -} - -// HEAD registers a new HEAD route for a path with matching handler in the -// router with optional route-level middleware. -func (e *Echo) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodHead, path, h, m...) -} - -// OPTIONS registers a new OPTIONS route for a path with matching handler in the -// router with optional route-level middleware. -func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodOptions, path, h, m...) -} - -// PATCH registers a new PATCH route for a path with matching handler in the -// router with optional route-level middleware. -func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodPatch, path, h, m...) -} - -// POST registers a new POST route for a path with matching handler in the -// router with optional route-level middleware. -func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodPost, path, h, m...) -} - -// PUT registers a new PUT route for a path with matching handler in the -// router with optional route-level middleware. -func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodPut, path, h, m...) -} - -// TRACE registers a new TRACE route for a path with matching handler in the -// router with optional route-level middleware. -func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(http.MethodTrace, path, h, m...) -} - -// RouteNotFound registers a special-case route which is executed when no other route is found (i.e. HTTP 404 cases) -// for current request URL. -// Path supports static and named/any parameters just like other http method is defined. Generally path is ended with -// wildcard/match-any character (`/*`, `/download/*` etc). -// -// Example: `e.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` -func (e *Echo) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return e.Add(RouteNotFound, path, h, m...) -} - -// Any registers a new route for all HTTP methods (supported by Echo) and path with matching handler -// in the router with optional route-level middleware. -// -// Note: this method only adds specific set of supported HTTP methods as handler and is not true -// "catch-any-arbitrary-method" way of matching requests. -func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route { - routes := make([]*Route, len(methods)) - for i, m := range methods { - routes[i] = e.Add(m, path, handler, middleware...) - } - return routes -} - -// Match registers a new route for multiple HTTP methods and path with matching -// handler in the router with optional route-level middleware. -func (e *Echo) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route { - routes := make([]*Route, len(methods)) - for i, m := range methods { - routes[i] = e.Add(m, path, handler, middleware...) - } - return routes -} - -func (common) file(path, file string, get func(string, HandlerFunc, ...MiddlewareFunc) *Route, - m ...MiddlewareFunc) *Route { - return get(path, func(c Context) error { - return c.File(file) - }, m...) -} - -// File registers a new route with path to serve a static file with optional route-level middleware. -func (e *Echo) File(path, file string, m ...MiddlewareFunc) *Route { - return e.file(path, file, e.GET, m...) -} - -func (e *Echo) add(host, method, path string, handler HandlerFunc, middlewares ...MiddlewareFunc) *Route { - router := e.findRouter(host) - //FIXME: when handler+middleware are both nil ... make it behave like handler removal - name := handlerName(handler) - route := router.add(method, path, name, func(c Context) error { - h := applyMiddleware(handler, middlewares...) - return h(c) - }) - - if e.OnAddRouteHandler != nil { - e.OnAddRouteHandler(host, *route, handler, middlewares) - } - - return route -} - -// Add registers a new route for an HTTP method and path with matching handler -// in the router with optional route-level middleware. -func (e *Echo) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route { - return e.add("", method, path, handler, middleware...) -} - -// Host creates a new router group for the provided host and optional host-level middleware. -func (e *Echo) Host(name string, m ...MiddlewareFunc) (g *Group) { - e.routers[name] = NewRouter(e) - g = &Group{host: name, echo: e} - g.Use(m...) - return -} - -// Group creates a new router group with prefix and optional group-level middleware. -func (e *Echo) Group(prefix string, m ...MiddlewareFunc) (g *Group) { - g = &Group{prefix: prefix, echo: e} - g.Use(m...) - return -} - -// URI generates an URI from handler. -func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string { - name := handlerName(handler) - return e.Reverse(name, params...) -} - -// URL is an alias for `URI` function. -func (e *Echo) URL(h HandlerFunc, params ...interface{}) string { - return e.URI(h, params...) -} - -// Reverse generates a URL from route name and provided parameters. -func (e *Echo) Reverse(name string, params ...interface{}) string { - return e.router.Reverse(name, params...) -} - -// Routes returns the registered routes for default router. -// In case when Echo serves multiple hosts/domains use `e.Routers()["domain2.site"].Routes()` to get specific host routes. -func (e *Echo) Routes() []*Route { - return e.router.Routes() -} - -// AcquireContext returns an empty `Context` instance from the pool. -// You must return the context by calling `ReleaseContext()`. -func (e *Echo) AcquireContext() Context { - return e.pool.Get().(Context) -} - -// ReleaseContext returns the `Context` instance back to the pool. -// You must call it after `AcquireContext()`. -func (e *Echo) ReleaseContext(c Context) { - e.pool.Put(c) -} - -// ServeHTTP implements `http.Handler` interface, which serves HTTP requests. -func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Acquire context - c := e.pool.Get().(*context) - c.Reset(r, w) - var h HandlerFunc - - if e.premiddleware == nil { - e.findRouter(r.Host).Find(r.Method, GetPath(r), c) - h = c.Handler() - h = applyMiddleware(h, e.middleware...) - } else { - h = func(c Context) error { - e.findRouter(r.Host).Find(r.Method, GetPath(r), c) - h := c.Handler() - h = applyMiddleware(h, e.middleware...) - return h(c) - } - h = applyMiddleware(h, e.premiddleware...) - } - - // Execute chain - if err := h(c); err != nil { - e.HTTPErrorHandler(err, c) - } - - // Release context - e.pool.Put(c) -} - -// Start starts an HTTP server. -func (e *Echo) Start(address string) error { - e.startupMutex.Lock() - e.Server.Addr = address - if err := e.configureServer(e.Server); err != nil { - e.startupMutex.Unlock() - return err - } - e.startupMutex.Unlock() - return e.Server.Serve(e.Listener) -} - -// StartTLS starts an HTTPS server. -// If `certFile` or `keyFile` is `string` the values are treated as file paths. -// If `certFile` or `keyFile` is `[]byte` the values are treated as the certificate or key as-is. -func (e *Echo) StartTLS(address string, certFile, keyFile interface{}) (err error) { - e.startupMutex.Lock() - var cert []byte - if cert, err = filepathOrContent(certFile); err != nil { - e.startupMutex.Unlock() - return - } - - var key []byte - if key, err = filepathOrContent(keyFile); err != nil { - e.startupMutex.Unlock() - return - } - - s := e.TLSServer - s.TLSConfig = new(tls.Config) - s.TLSConfig.Certificates = make([]tls.Certificate, 1) - if s.TLSConfig.Certificates[0], err = tls.X509KeyPair(cert, key); err != nil { - e.startupMutex.Unlock() - return - } - - e.configureTLS(address) - if err := e.configureServer(s); err != nil { - e.startupMutex.Unlock() - return err - } - e.startupMutex.Unlock() - return s.Serve(e.TLSListener) -} - -func filepathOrContent(fileOrContent interface{}) (content []byte, err error) { - switch v := fileOrContent.(type) { - case string: - return os.ReadFile(v) - case []byte: - return v, nil - default: - return nil, ErrInvalidCertOrKeyType - } -} - -// StartAutoTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org. -func (e *Echo) StartAutoTLS(address string) error { - e.startupMutex.Lock() - s := e.TLSServer - s.TLSConfig = new(tls.Config) - s.TLSConfig.GetCertificate = e.AutoTLSManager.GetCertificate - s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, acme.ALPNProto) - - e.configureTLS(address) - if err := e.configureServer(s); err != nil { - e.startupMutex.Unlock() - return err - } - e.startupMutex.Unlock() - return s.Serve(e.TLSListener) -} - -func (e *Echo) configureTLS(address string) { - s := e.TLSServer - s.Addr = address - if !e.DisableHTTP2 { - s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2") - } -} - -// StartServer starts a custom http server. -func (e *Echo) StartServer(s *http.Server) (err error) { - e.startupMutex.Lock() - if err := e.configureServer(s); err != nil { - e.startupMutex.Unlock() - return err - } - if s.TLSConfig != nil { - e.startupMutex.Unlock() - return s.Serve(e.TLSListener) - } - e.startupMutex.Unlock() - return s.Serve(e.Listener) -} - -func (e *Echo) configureServer(s *http.Server) error { - // Setup - e.colorer.SetOutput(e.Logger.Output()) - s.ErrorLog = e.StdLogger - s.Handler = e - if e.Debug { - e.Logger.SetLevel(log.DEBUG) - } - - if !e.HideBanner { - e.colorer.Printf(banner, e.colorer.Red("v"+Version), e.colorer.Blue(website)) - } - - if s.TLSConfig == nil { - if e.Listener == nil { - l, err := newListener(s.Addr, e.ListenerNetwork) - if err != nil { - return err - } - e.Listener = l - } - if !e.HidePort { - e.colorer.Printf("⇨ http server started on %s\n", e.colorer.Green(e.Listener.Addr())) - } - return nil - } - if e.TLSListener == nil { - l, err := newListener(s.Addr, e.ListenerNetwork) - if err != nil { - return err - } - e.TLSListener = tls.NewListener(l, s.TLSConfig) - } - if !e.HidePort { - e.colorer.Printf("⇨ https server started on %s\n", e.colorer.Green(e.TLSListener.Addr())) - } - return nil -} - -// ListenerAddr returns net.Addr for Listener -func (e *Echo) ListenerAddr() net.Addr { - e.startupMutex.RLock() - defer e.startupMutex.RUnlock() - if e.Listener == nil { - return nil - } - return e.Listener.Addr() -} - -// TLSListenerAddr returns net.Addr for TLSListener -func (e *Echo) TLSListenerAddr() net.Addr { - e.startupMutex.RLock() - defer e.startupMutex.RUnlock() - if e.TLSListener == nil { - return nil - } - return e.TLSListener.Addr() -} - -// StartH2CServer starts a custom http/2 server with h2c (HTTP/2 Cleartext). -func (e *Echo) StartH2CServer(address string, h2s *http2.Server) error { - e.startupMutex.Lock() - // Setup - s := e.Server - s.Addr = address - e.colorer.SetOutput(e.Logger.Output()) - s.ErrorLog = e.StdLogger - s.Handler = h2c.NewHandler(e, h2s) - if e.Debug { - e.Logger.SetLevel(log.DEBUG) - } - - if !e.HideBanner { - e.colorer.Printf(banner, e.colorer.Red("v"+Version), e.colorer.Blue(website)) - } - - if e.Listener == nil { - l, err := newListener(s.Addr, e.ListenerNetwork) - if err != nil { - e.startupMutex.Unlock() - return err - } - e.Listener = l - } - if !e.HidePort { - e.colorer.Printf("⇨ http server started on %s\n", e.colorer.Green(e.Listener.Addr())) - } - e.startupMutex.Unlock() - return s.Serve(e.Listener) -} - -// Close immediately stops the server. -// It internally calls `http.Server#Close()`. -func (e *Echo) Close() error { - e.startupMutex.Lock() - defer e.startupMutex.Unlock() - if err := e.TLSServer.Close(); err != nil { - return err - } - return e.Server.Close() -} - -// Shutdown stops the server gracefully. -// It internally calls `http.Server#Shutdown()`. -func (e *Echo) Shutdown(ctx stdContext.Context) error { - e.startupMutex.Lock() - defer e.startupMutex.Unlock() - if err := e.TLSServer.Shutdown(ctx); err != nil { - return err - } - return e.Server.Shutdown(ctx) -} - -// NewHTTPError creates a new HTTPError instance. -func NewHTTPError(code int, message ...interface{}) *HTTPError { - he := &HTTPError{Code: code, Message: http.StatusText(code)} - if len(message) > 0 { - he.Message = message[0] - } - return he -} - -// Error makes it compatible with `error` interface. -func (he *HTTPError) Error() string { - if he.Internal == nil { - return fmt.Sprintf("code=%d, message=%v", he.Code, he.Message) - } - return fmt.Sprintf("code=%d, message=%v, internal=%v", he.Code, he.Message, he.Internal) -} - -// SetInternal sets error to HTTPError.Internal -func (he *HTTPError) SetInternal(err error) *HTTPError { - he.Internal = err - return he -} - -// WithInternal returns clone of HTTPError with err set to HTTPError.Internal field -func (he *HTTPError) WithInternal(err error) *HTTPError { - return &HTTPError{ - Code: he.Code, - Message: he.Message, - Internal: err, - } -} - -// Unwrap satisfies the Go 1.13 error wrapper interface. -func (he *HTTPError) Unwrap() error { - return he.Internal -} - -// WrapHandler wraps `http.Handler` into `echo.HandlerFunc`. -func WrapHandler(h http.Handler) HandlerFunc { - return func(c Context) error { - h.ServeHTTP(c.Response(), c.Request()) - return nil - } -} - -// WrapMiddleware wraps `func(http.Handler) http.Handler` into `echo.MiddlewareFunc` -func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc { - return func(next HandlerFunc) HandlerFunc { - return func(c Context) (err error) { - m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - c.SetRequest(r) - c.SetResponse(NewResponse(w, c.Echo())) - err = next(c) - })).ServeHTTP(c.Response(), c.Request()) - return - } - } -} - -// GetPath returns RawPath, if it's empty returns Path from URL -// Difference between RawPath and Path is: -// - Path is where request path is stored. Value is stored in decoded form: /%47%6f%2f becomes /Go/. -// - RawPath is an optional field which only gets set if the default encoding is different from Path. -func GetPath(r *http.Request) string { - path := r.URL.RawPath - if path == "" { - path = r.URL.Path - } - return path -} - -func (e *Echo) findRouter(host string) *Router { - if len(e.routers) > 0 { - if r, ok := e.routers[host]; ok { - return r - } - } - return e.router -} - -func handlerName(h HandlerFunc) string { - t := reflect.ValueOf(h).Type() - if t.Kind() == reflect.Func { - return runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name() - } - return t.String() -} - -// // PathUnescape is wraps `url.PathUnescape` -// func PathUnescape(s string) (string, error) { -// return url.PathUnescape(s) -// } - -// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted -// connections. It's used by ListenAndServe and ListenAndServeTLS so -// dead TCP connections (e.g. closing laptop mid-download) eventually -// go away. -type tcpKeepAliveListener struct { - *net.TCPListener -} - -func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) { - if c, err = ln.AcceptTCP(); err != nil { - return - } else if err = c.(*net.TCPConn).SetKeepAlive(true); err != nil { - return - } - // Ignore error from setting the KeepAlivePeriod as some systems, such as - // OpenBSD, do not support setting TCP_USER_TIMEOUT on IPPROTO_TCP - _ = c.(*net.TCPConn).SetKeepAlivePeriod(3 * time.Minute) - return -} - -func newListener(address, network string) (*tcpKeepAliveListener, error) { - if network != "tcp" && network != "tcp4" && network != "tcp6" { - return nil, ErrInvalidListenerNetwork - } - l, err := net.Listen(network, address) - if err != nil { - return nil, err - } - return &tcpKeepAliveListener{l.(*net.TCPListener)}, nil -} - -func applyMiddleware(h HandlerFunc, middleware ...MiddlewareFunc) HandlerFunc { - for i := len(middleware) - 1; i >= 0; i-- { - h = middleware[i](h) - } - return h -} diff --git a/vendor/github.com/labstack/echo/v4/echo_fs.go b/vendor/github.com/labstack/echo/v4/echo_fs.go deleted file mode 100644 index 0ffc4b0bf..000000000 --- a/vendor/github.com/labstack/echo/v4/echo_fs.go +++ /dev/null @@ -1,162 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "fmt" - "io/fs" - "net/http" - "net/url" - "os" - "path/filepath" - "strings" -) - -type filesystem struct { - // Filesystem is file system used by Static and File handlers to access files. - // Defaults to os.DirFS(".") - // - // When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary - // prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths - // including `assets/images` as their prefix. - Filesystem fs.FS -} - -func createFilesystem() filesystem { - return filesystem{ - Filesystem: newDefaultFS(), - } -} - -// Static registers a new route with path prefix to serve static files from the provided root directory. -func (e *Echo) Static(pathPrefix, fsRoot string) *Route { - subFs := MustSubFS(e.Filesystem, fsRoot) - return e.Add( - http.MethodGet, - pathPrefix+"*", - StaticDirectoryHandler(subFs, false), - ) -} - -// StaticFS registers a new route with path prefix to serve static files from the provided file system. -// -// When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary -// prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths -// including `assets/images` as their prefix. -func (e *Echo) StaticFS(pathPrefix string, filesystem fs.FS) *Route { - return e.Add( - http.MethodGet, - pathPrefix+"*", - StaticDirectoryHandler(filesystem, false), - ) -} - -// StaticDirectoryHandler creates handler function to serve files from provided file system -// When disablePathUnescaping is set then file name from path is not unescaped and is served as is. -func StaticDirectoryHandler(fileSystem fs.FS, disablePathUnescaping bool) HandlerFunc { - return func(c Context) error { - p := c.Param("*") - if !disablePathUnescaping { // when router is already unescaping we do not want to do is twice - tmpPath, err := url.PathUnescape(p) - if err != nil { - return fmt.Errorf("failed to unescape path variable: %w", err) - } - p = tmpPath - } - - // fs.FS.Open() already assumes that file names are relative to FS root path and considers name with prefix `/` as invalid - name := filepath.ToSlash(filepath.Clean(strings.TrimPrefix(p, "/"))) - fi, err := fs.Stat(fileSystem, name) - if err != nil { - return ErrNotFound - } - - // If the request is for a directory and does not end with "/" - p = c.Request().URL.Path // path must not be empty. - if fi.IsDir() && len(p) > 0 && p[len(p)-1] != '/' { - // Redirect to ends with "/" - return c.Redirect(http.StatusMovedPermanently, sanitizeURI(p+"/")) - } - return fsFile(c, name, fileSystem) - } -} - -// FileFS registers a new route with path to serve file from the provided file system. -func (e *Echo) FileFS(path, file string, filesystem fs.FS, m ...MiddlewareFunc) *Route { - return e.GET(path, StaticFileHandler(file, filesystem), m...) -} - -// StaticFileHandler creates handler function to serve file from provided file system -func StaticFileHandler(file string, filesystem fs.FS) HandlerFunc { - return func(c Context) error { - return fsFile(c, file, filesystem) - } -} - -// defaultFS exists to preserve pre v4.7.0 behaviour where files were open by `os.Open`. -// v4.7 introduced `echo.Filesystem` field which is Go1.16+ `fs.Fs` interface. -// Difference between `os.Open` and `fs.Open` is that FS does not allow opening path that start with `.`, `..` or `/` -// etc. For example previously you could have `../images` in your application but `fs := os.DirFS("./")` would not -// allow you to use `fs.Open("../images")` and this would break all old applications that rely on being able to -// traverse up from current executable run path. -// NB: private because you really should use fs.FS implementation instances -type defaultFS struct { - fs fs.FS - prefix string -} - -func newDefaultFS() *defaultFS { - dir, _ := os.Getwd() - return &defaultFS{ - prefix: dir, - fs: nil, - } -} - -func (fs defaultFS) Open(name string) (fs.File, error) { - if fs.fs == nil { - return os.Open(name) - } - return fs.fs.Open(name) -} - -func subFS(currentFs fs.FS, root string) (fs.FS, error) { - root = filepath.ToSlash(filepath.Clean(root)) // note: fs.FS operates only with slashes. `ToSlash` is necessary for Windows - if dFS, ok := currentFs.(*defaultFS); ok { - // we need to make exception for `defaultFS` instances as it interprets root prefix differently from fs.FS. - // fs.Fs.Open does not like relative paths ("./", "../") and absolute paths at all but prior echo.Filesystem we - // were able to use paths like `./myfile.log`, `/etc/hosts` and these would work fine with `os.Open` but not with fs.Fs - if !filepath.IsAbs(root) { - root = filepath.Join(dFS.prefix, root) - } - return &defaultFS{ - prefix: root, - fs: os.DirFS(root), - }, nil - } - return fs.Sub(currentFs, root) -} - -// MustSubFS creates sub FS from current filesystem or panic on failure. -// Panic happens when `fsRoot` contains invalid path according to `fs.ValidPath` rules. -// -// MustSubFS is helpful when dealing with `embed.FS` because for example `//go:embed assets/images` embeds files with -// paths including `assets/images` as their prefix. In that case use `fs := echo.MustSubFS(fs, "rootDirectory") to -// create sub fs which uses necessary prefix for directory path. -func MustSubFS(currentFs fs.FS, fsRoot string) fs.FS { - subFs, err := subFS(currentFs, fsRoot) - if err != nil { - panic(fmt.Errorf("can not create sub FS, invalid root given, err: %w", err)) - } - return subFs -} - -func sanitizeURI(uri string) string { - // double slash `\\`, `//` or even `\/` is absolute uri for browsers and by redirecting request to that uri - // we are vulnerable to open redirect attack. so replace all slashes from the beginning with single slash - if len(uri) > 1 && (uri[0] == '\\' || uri[0] == '/') && (uri[1] == '\\' || uri[1] == '/') { - uri = "/" + strings.TrimLeft(uri, `/\`) - } - return uri -} diff --git a/vendor/github.com/labstack/echo/v4/group.go b/vendor/github.com/labstack/echo/v4/group.go deleted file mode 100644 index cb37b123f..000000000 --- a/vendor/github.com/labstack/echo/v4/group.go +++ /dev/null @@ -1,129 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "net/http" -) - -// Group is a set of sub-routes for a specified route. It can be used for inner -// routes that share a common middleware or functionality that should be separate -// from the parent echo instance while still inheriting from it. -type Group struct { - common - host string - prefix string - echo *Echo - middleware []MiddlewareFunc -} - -// Use implements `Echo#Use()` for sub-routes within the Group. -func (g *Group) Use(middleware ...MiddlewareFunc) { - g.middleware = append(g.middleware, middleware...) - if len(g.middleware) == 0 { - return - } - // group level middlewares are different from Echo `Pre` and `Use` middlewares (those are global). Group level middlewares - // are only executed if they are added to the Router with route. - // So we register catch all route (404 is a safe way to emulate route match) for this group and now during routing the - // Router would find route to match our request path and therefore guarantee the middleware(s) will get executed. - g.RouteNotFound("", NotFoundHandler) - g.RouteNotFound("/*", NotFoundHandler) -} - -// CONNECT implements `Echo#CONNECT()` for sub-routes within the Group. -func (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodConnect, path, h, m...) -} - -// DELETE implements `Echo#DELETE()` for sub-routes within the Group. -func (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodDelete, path, h, m...) -} - -// GET implements `Echo#GET()` for sub-routes within the Group. -func (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodGet, path, h, m...) -} - -// HEAD implements `Echo#HEAD()` for sub-routes within the Group. -func (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodHead, path, h, m...) -} - -// OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group. -func (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodOptions, path, h, m...) -} - -// PATCH implements `Echo#PATCH()` for sub-routes within the Group. -func (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodPatch, path, h, m...) -} - -// POST implements `Echo#POST()` for sub-routes within the Group. -func (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodPost, path, h, m...) -} - -// PUT implements `Echo#PUT()` for sub-routes within the Group. -func (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodPut, path, h, m...) -} - -// TRACE implements `Echo#TRACE()` for sub-routes within the Group. -func (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(http.MethodTrace, path, h, m...) -} - -// Any implements `Echo#Any()` for sub-routes within the Group. -func (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route { - routes := make([]*Route, len(methods)) - for i, m := range methods { - routes[i] = g.Add(m, path, handler, middleware...) - } - return routes -} - -// Match implements `Echo#Match()` for sub-routes within the Group. -func (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route { - routes := make([]*Route, len(methods)) - for i, m := range methods { - routes[i] = g.Add(m, path, handler, middleware...) - } - return routes -} - -// Group creates a new sub-group with prefix and optional sub-group-level middleware. -func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) (sg *Group) { - m := make([]MiddlewareFunc, 0, len(g.middleware)+len(middleware)) - m = append(m, g.middleware...) - m = append(m, middleware...) - sg = g.echo.Group(g.prefix+prefix, m...) - sg.host = g.host - return -} - -// File implements `Echo#File()` for sub-routes within the Group. -func (g *Group) File(path, file string) { - g.file(path, file, g.GET) -} - -// RouteNotFound implements `Echo#RouteNotFound()` for sub-routes within the Group. -// -// Example: `g.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` -func (g *Group) RouteNotFound(path string, h HandlerFunc, m ...MiddlewareFunc) *Route { - return g.Add(RouteNotFound, path, h, m...) -} - -// Add implements `Echo#Add()` for sub-routes within the Group. -func (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route { - // Combine into a new slice to avoid accidentally passing the same slice for - // multiple routes, which would lead to later add() calls overwriting the - // middleware from earlier calls. - m := make([]MiddlewareFunc, 0, len(g.middleware)+len(middleware)) - m = append(m, g.middleware...) - m = append(m, middleware...) - return g.echo.add(g.host, method, g.prefix+path, handler, m...) -} diff --git a/vendor/github.com/labstack/echo/v4/group_fs.go b/vendor/github.com/labstack/echo/v4/group_fs.go deleted file mode 100644 index c1b7ec2d3..000000000 --- a/vendor/github.com/labstack/echo/v4/group_fs.go +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "io/fs" - "net/http" -) - -// Static implements `Echo#Static()` for sub-routes within the Group. -func (g *Group) Static(pathPrefix, fsRoot string) { - subFs := MustSubFS(g.echo.Filesystem, fsRoot) - g.StaticFS(pathPrefix, subFs) -} - -// StaticFS implements `Echo#StaticFS()` for sub-routes within the Group. -// -// When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary -// prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths -// including `assets/images` as their prefix. -func (g *Group) StaticFS(pathPrefix string, filesystem fs.FS) { - g.Add( - http.MethodGet, - pathPrefix+"*", - StaticDirectoryHandler(filesystem, false), - ) -} - -// FileFS implements `Echo#FileFS()` for sub-routes within the Group. -func (g *Group) FileFS(path, file string, filesystem fs.FS, m ...MiddlewareFunc) *Route { - return g.GET(path, StaticFileHandler(file, filesystem), m...) -} diff --git a/vendor/github.com/labstack/echo/v4/ip.go b/vendor/github.com/labstack/echo/v4/ip.go deleted file mode 100644 index 393a6c2d3..000000000 --- a/vendor/github.com/labstack/echo/v4/ip.go +++ /dev/null @@ -1,277 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "net" - "net/http" - "strings" -) - -/** -By: https://github.com/tmshn (See: https://github.com/labstack/echo/pull/1478 , https://github.com/labstack/echox/pull/134 ) -Source: https://echo.labstack.com/guide/ip-address/ - -IP address plays fundamental role in HTTP; it's used for access control, auditing, geo-based access analysis and more. -Echo provides handy method [`Context#RealIP()`](https://godoc.org/github.com/labstack/echo#Context) for that. - -However, it is not trivial to retrieve the _real_ IP address from requests especially when you put L7 proxies before the application. -In such situation, _real_ IP needs to be relayed on HTTP layer from proxies to your app, but you must not trust HTTP headers unconditionally. -Otherwise, you might give someone a chance of deceiving you. **A security risk!** - -To retrieve IP address reliably/securely, you must let your application be aware of the entire architecture of your infrastructure. -In Echo, this can be done by configuring `Echo#IPExtractor` appropriately. -This guides show you why and how. - -> Note: if you dont' set `Echo#IPExtractor` explicitly, Echo fallback to legacy behavior, which is not a good choice. - -Let's start from two questions to know the right direction: - -1. Do you put any HTTP (L7) proxy in front of the application? - - It includes both cloud solutions (such as AWS ALB or GCP HTTP LB) and OSS ones (such as Nginx, Envoy or Istio ingress gateway). -2. If yes, what HTTP header do your proxies use to pass client IP to the application? - -## Case 1. With no proxy - -If you put no proxy (e.g.: directory facing to the internet), all you need to (and have to) see is IP address from network layer. -Any HTTP header is untrustable because the clients have full control what headers to be set. - -In this case, use `echo.ExtractIPDirect()`. - -```go -e.IPExtractor = echo.ExtractIPDirect() -``` - -## Case 2. With proxies using `X-Forwarded-For` header - -[`X-Forwared-For` (XFF)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For) is the popular header -to relay clients' IP addresses. -At each hop on the proxies, they append the request IP address at the end of the header. - -Following example diagram illustrates this behavior. - -```text -┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ -│ "Origin" │───────────>│ Proxy 1 │───────────>│ Proxy 2 │───────────>│ Your app │ -│ (IP: a) │ │ (IP: b) │ │ (IP: c) │ │ │ -└──────────┘ └──────────┘ └──────────┘ └──────────┘ - -Case 1. -XFF: "" "a" "a, b" - ~~~~~~ -Case 2. -XFF: "x" "x, a" "x, a, b" - ~~~~~~~~~ - ↑ What your app will see -``` - -In this case, use **first _untrustable_ IP reading from right**. Never use first one reading from left, as it is -configurable by client. Here "trustable" means "you are sure the IP address belongs to your infrastructure". -In above example, if `b` and `c` are trustable, the IP address of the client is `a` for both cases, never be `x`. - -In Echo, use `ExtractIPFromXFFHeader(...TrustOption)`. - -```go -e.IPExtractor = echo.ExtractIPFromXFFHeader() -``` - -By default, it trusts internal IP addresses (loopback, link-local unicast, private-use and unique local address -from [RFC6890](https://tools.ietf.org/html/rfc6890), [RFC4291](https://tools.ietf.org/html/rfc4291) and -[RFC4193](https://tools.ietf.org/html/rfc4193)). -To control this behavior, use [`TrustOption`](https://godoc.org/github.com/labstack/echo#TrustOption)s. - -E.g.: - -```go -e.IPExtractor = echo.ExtractIPFromXFFHeader( - TrustLinkLocal(false), - TrustIPRanges(lbIPRange), -) -``` - -- Ref: https://godoc.org/github.com/labstack/echo#TrustOption - -## Case 3. With proxies using `X-Real-IP` header - -`X-Real-IP` is another HTTP header to relay clients' IP addresses, but it carries only one address unlike XFF. - -If your proxies set this header, use `ExtractIPFromRealIPHeader(...TrustOption)`. - -```go -e.IPExtractor = echo.ExtractIPFromRealIPHeader() -``` - -Again, it trusts internal IP addresses by default (loopback, link-local unicast, private-use and unique local address -from [RFC6890](https://tools.ietf.org/html/rfc6890), [RFC4291](https://tools.ietf.org/html/rfc4291) and -[RFC4193](https://tools.ietf.org/html/rfc4193)). -To control this behavior, use [`TrustOption`](https://godoc.org/github.com/labstack/echo#TrustOption)s. - -- Ref: https://godoc.org/github.com/labstack/echo#TrustOption - -> **Never forget** to configure the outermost proxy (i.e.; at the edge of your infrastructure) **not to pass through incoming headers**. -> Otherwise there is a chance of fraud, as it is what clients can control. - -## About default behavior - -In default behavior, Echo sees all of first XFF header, X-Real-IP header and IP from network layer. - -As you might already notice, after reading this article, this is not good. -Sole reason this is default is just backward compatibility. - -## Private IP ranges - -See: https://en.wikipedia.org/wiki/Private_network - -Private IPv4 address ranges (RFC 1918): -* 10.0.0.0 – 10.255.255.255 (24-bit block) -* 172.16.0.0 – 172.31.255.255 (20-bit block) -* 192.168.0.0 – 192.168.255.255 (16-bit block) - -Private IPv6 address ranges: -* fc00::/7 address block = RFC 4193 Unique Local Addresses (ULA) - -*/ - -type ipChecker struct { - trustExtraRanges []*net.IPNet - trustLoopback bool - trustLinkLocal bool - trustPrivateNet bool -} - -// TrustOption is config for which IP address to trust -type TrustOption func(*ipChecker) - -// TrustLoopback configures if you trust loopback address (default: true). -func TrustLoopback(v bool) TrustOption { - return func(c *ipChecker) { - c.trustLoopback = v - } -} - -// TrustLinkLocal configures if you trust link-local address (default: true). -func TrustLinkLocal(v bool) TrustOption { - return func(c *ipChecker) { - c.trustLinkLocal = v - } -} - -// TrustPrivateNet configures if you trust private network address (default: true). -func TrustPrivateNet(v bool) TrustOption { - return func(c *ipChecker) { - c.trustPrivateNet = v - } -} - -// TrustIPRange add trustable IP ranges using CIDR notation. -func TrustIPRange(ipRange *net.IPNet) TrustOption { - return func(c *ipChecker) { - c.trustExtraRanges = append(c.trustExtraRanges, ipRange) - } -} - -func newIPChecker(configs []TrustOption) *ipChecker { - checker := &ipChecker{trustLoopback: true, trustLinkLocal: true, trustPrivateNet: true} - for _, configure := range configs { - configure(checker) - } - return checker -} - -// Go1.16+ added `ip.IsPrivate()` but until that use this implementation -func isPrivateIPRange(ip net.IP) bool { - if ip4 := ip.To4(); ip4 != nil { - return ip4[0] == 10 || - ip4[0] == 172 && ip4[1]&0xf0 == 16 || - ip4[0] == 192 && ip4[1] == 168 - } - return len(ip) == net.IPv6len && ip[0]&0xfe == 0xfc -} - -func (c *ipChecker) trust(ip net.IP) bool { - if c.trustLoopback && ip.IsLoopback() { - return true - } - if c.trustLinkLocal && ip.IsLinkLocalUnicast() { - return true - } - if c.trustPrivateNet && isPrivateIPRange(ip) { - return true - } - for _, trustedRange := range c.trustExtraRanges { - if trustedRange.Contains(ip) { - return true - } - } - return false -} - -// IPExtractor is a function to extract IP addr from http.Request. -// Set appropriate one to Echo#IPExtractor. -// See https://echo.labstack.com/guide/ip-address for more details. -type IPExtractor func(*http.Request) string - -// ExtractIPDirect extracts IP address using actual IP address. -// Use this if your server faces to internet directory (i.e.: uses no proxy). -func ExtractIPDirect() IPExtractor { - return extractIP -} - -func extractIP(req *http.Request) string { - ra, _, _ := net.SplitHostPort(req.RemoteAddr) - return ra -} - -// ExtractIPFromRealIPHeader extracts IP address using x-real-ip header. -// Use this if you put proxy which uses this header. -func ExtractIPFromRealIPHeader(options ...TrustOption) IPExtractor { - checker := newIPChecker(options) - return func(req *http.Request) string { - directIP := extractIP(req) - realIP := req.Header.Get(HeaderXRealIP) - if realIP == "" { - return directIP - } - - if checker.trust(net.ParseIP(directIP)) { - realIP = strings.TrimPrefix(realIP, "[") - realIP = strings.TrimSuffix(realIP, "]") - if rIP := net.ParseIP(realIP); rIP != nil { - return realIP - } - } - - return directIP - } -} - -// ExtractIPFromXFFHeader extracts IP address using x-forwarded-for header. -// Use this if you put proxy which uses this header. -// This returns nearest untrustable IP. If all IPs are trustable, returns furthest one (i.e.: XFF[0]). -func ExtractIPFromXFFHeader(options ...TrustOption) IPExtractor { - checker := newIPChecker(options) - return func(req *http.Request) string { - directIP := extractIP(req) - xffs := req.Header[HeaderXForwardedFor] - if len(xffs) == 0 { - return directIP - } - ips := append(strings.Split(strings.Join(xffs, ","), ","), directIP) - for i := len(ips) - 1; i >= 0; i-- { - ips[i] = strings.TrimSpace(ips[i]) - ips[i] = strings.TrimPrefix(ips[i], "[") - ips[i] = strings.TrimSuffix(ips[i], "]") - ip := net.ParseIP(ips[i]) - if ip == nil { - // Unable to parse IP; cannot trust entire records - return directIP - } - if !checker.trust(ip) { - return ip.String() - } - } - // All of the IPs are trusted; return first element because it is furthest from server (best effort strategy). - return strings.TrimSpace(ips[0]) - } -} diff --git a/vendor/github.com/labstack/echo/v4/json.go b/vendor/github.com/labstack/echo/v4/json.go deleted file mode 100644 index 6da0aaf97..000000000 --- a/vendor/github.com/labstack/echo/v4/json.go +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "encoding/json" - "fmt" - "net/http" -) - -// DefaultJSONSerializer implements JSON encoding using encoding/json. -type DefaultJSONSerializer struct{} - -// Serialize converts an interface into a json and writes it to the response. -// You can optionally use the indent parameter to produce pretty JSONs. -func (d DefaultJSONSerializer) Serialize(c Context, i interface{}, indent string) error { - enc := json.NewEncoder(c.Response()) - if indent != "" { - enc.SetIndent("", indent) - } - return enc.Encode(i) -} - -// Deserialize reads a JSON from a request body and converts it into an interface. -func (d DefaultJSONSerializer) Deserialize(c Context, i interface{}) error { - err := json.NewDecoder(c.Request().Body).Decode(i) - if ute, ok := err.(*json.UnmarshalTypeError); ok { - return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v", ute.Type, ute.Value, ute.Field, ute.Offset)).SetInternal(err) - } else if se, ok := err.(*json.SyntaxError); ok { - return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: offset=%v, error=%v", se.Offset, se.Error())).SetInternal(err) - } - return err -} diff --git a/vendor/github.com/labstack/echo/v4/log.go b/vendor/github.com/labstack/echo/v4/log.go deleted file mode 100644 index 0acd9ff03..000000000 --- a/vendor/github.com/labstack/echo/v4/log.go +++ /dev/null @@ -1,41 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package echo - -import ( - "github.com/labstack/gommon/log" - "io" -) - -// Logger defines the logging interface. -type Logger interface { - Output() io.Writer - SetOutput(w io.Writer) - Prefix() string - SetPrefix(p string) - Level() log.Lvl - SetLevel(v log.Lvl) - SetHeader(h string) - Print(i ...interface{}) - Printf(format string, args ...interface{}) - Printj(j log.JSON) - Debug(i ...interface{}) - Debugf(format string, args ...interface{}) - Debugj(j log.JSON) - Info(i ...interface{}) - Infof(format string, args ...interface{}) - Infoj(j log.JSON) - Warn(i ...interface{}) - Warnf(format string, args ...interface{}) - Warnj(j log.JSON) - Error(i ...interface{}) - Errorf(format string, args ...interface{}) - Errorj(j log.JSON) - Fatal(i ...interface{}) - Fatalj(j log.JSON) - Fatalf(format string, args ...interface{}) - Panic(i ...interface{}) - Panicj(j log.JSON) - Panicf(format string, args ...interface{}) -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/basic_auth.go b/vendor/github.com/labstack/echo/v4/middleware/basic_auth.go deleted file mode 100644 index 9285f29fd..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/basic_auth.go +++ /dev/null @@ -1,111 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "encoding/base64" - "net/http" - "strconv" - "strings" - - "github.com/labstack/echo/v4" -) - -// BasicAuthConfig defines the config for BasicAuth middleware. -type BasicAuthConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Validator is a function to validate BasicAuth credentials. - // Required. - Validator BasicAuthValidator - - // Realm is a string to define realm attribute of BasicAuth. - // Default value "Restricted". - Realm string -} - -// BasicAuthValidator defines a function to validate BasicAuth credentials. -// The function should return a boolean indicating whether the credentials are valid, -// and an error if any error occurs during the validation process. -type BasicAuthValidator func(string, string, echo.Context) (bool, error) - -const ( - basic = "basic" - defaultRealm = "Restricted" -) - -// DefaultBasicAuthConfig is the default BasicAuth middleware config. -var DefaultBasicAuthConfig = BasicAuthConfig{ - Skipper: DefaultSkipper, - Realm: defaultRealm, -} - -// BasicAuth returns an BasicAuth middleware. -// -// For valid credentials it calls the next handler. -// For missing or invalid credentials, it sends "401 - Unauthorized" response. -func BasicAuth(fn BasicAuthValidator) echo.MiddlewareFunc { - c := DefaultBasicAuthConfig - c.Validator = fn - return BasicAuthWithConfig(c) -} - -// BasicAuthWithConfig returns an BasicAuth middleware with config. -// See `BasicAuth()`. -func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc { - // Defaults - if config.Validator == nil { - panic("echo: basic-auth middleware requires a validator function") - } - if config.Skipper == nil { - config.Skipper = DefaultBasicAuthConfig.Skipper - } - if config.Realm == "" { - config.Realm = defaultRealm - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - auth := c.Request().Header.Get(echo.HeaderAuthorization) - l := len(basic) - - if len(auth) > l+1 && strings.EqualFold(auth[:l], basic) { - // Invalid base64 shouldn't be treated as error - // instead should be treated as invalid client input - b, err := base64.StdEncoding.DecodeString(auth[l+1:]) - if err != nil { - return echo.NewHTTPError(http.StatusBadRequest).SetInternal(err) - } - - cred := string(b) - for i := 0; i < len(cred); i++ { - if cred[i] == ':' { - // Verify credentials - valid, err := config.Validator(cred[:i], cred[i+1:], c) - if err != nil { - return err - } else if valid { - return next(c) - } - break - } - } - } - - realm := defaultRealm - if config.Realm != defaultRealm { - realm = strconv.Quote(config.Realm) - } - - // Need to return `401` for browsers to pop-up login box. - c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm="+realm) - return echo.ErrUnauthorized - } - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/body_dump.go b/vendor/github.com/labstack/echo/v4/middleware/body_dump.go deleted file mode 100644 index e4119ec1e..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/body_dump.go +++ /dev/null @@ -1,113 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "bufio" - "bytes" - "errors" - "io" - "net" - "net/http" - - "github.com/labstack/echo/v4" -) - -// BodyDumpConfig defines the config for BodyDump middleware. -type BodyDumpConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Handler receives request and response payload. - // Required. - Handler BodyDumpHandler -} - -// BodyDumpHandler receives the request and response payload. -type BodyDumpHandler func(echo.Context, []byte, []byte) - -type bodyDumpResponseWriter struct { - io.Writer - http.ResponseWriter -} - -// DefaultBodyDumpConfig is the default BodyDump middleware config. -var DefaultBodyDumpConfig = BodyDumpConfig{ - Skipper: DefaultSkipper, -} - -// BodyDump returns a BodyDump middleware. -// -// BodyDump middleware captures the request and response payload and calls the -// registered handler. -func BodyDump(handler BodyDumpHandler) echo.MiddlewareFunc { - c := DefaultBodyDumpConfig - c.Handler = handler - return BodyDumpWithConfig(c) -} - -// BodyDumpWithConfig returns a BodyDump middleware with config. -// See: `BodyDump()`. -func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc { - // Defaults - if config.Handler == nil { - panic("echo: body-dump middleware requires a handler function") - } - if config.Skipper == nil { - config.Skipper = DefaultBodyDumpConfig.Skipper - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) (err error) { - if config.Skipper(c) { - return next(c) - } - - // Request - reqBody := []byte{} - if c.Request().Body != nil { // Read - reqBody, _ = io.ReadAll(c.Request().Body) - } - c.Request().Body = io.NopCloser(bytes.NewBuffer(reqBody)) // Reset - - // Response - resBody := new(bytes.Buffer) - mw := io.MultiWriter(c.Response().Writer, resBody) - writer := &bodyDumpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer} - c.Response().Writer = writer - - if err = next(c); err != nil { - c.Error(err) - } - - // Callback - config.Handler(c, reqBody, resBody.Bytes()) - - return - } - } -} - -func (w *bodyDumpResponseWriter) WriteHeader(code int) { - w.ResponseWriter.WriteHeader(code) -} - -func (w *bodyDumpResponseWriter) Write(b []byte) (int, error) { - return w.Writer.Write(b) -} - -func (w *bodyDumpResponseWriter) Flush() { - err := http.NewResponseController(w.ResponseWriter).Flush() - if err != nil && errors.Is(err, http.ErrNotSupported) { - panic(errors.New("response writer flushing is not supported")) - } -} - -func (w *bodyDumpResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - return http.NewResponseController(w.ResponseWriter).Hijack() -} - -func (w *bodyDumpResponseWriter) Unwrap() http.ResponseWriter { - return w.ResponseWriter -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/body_limit.go b/vendor/github.com/labstack/echo/v4/middleware/body_limit.go deleted file mode 100644 index 7d3c665f2..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/body_limit.go +++ /dev/null @@ -1,114 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "fmt" - "io" - "sync" - - "github.com/labstack/echo/v4" - "github.com/labstack/gommon/bytes" -) - -// BodyLimitConfig defines the config for BodyLimit middleware. -type BodyLimitConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Maximum allowed size for a request body, it can be specified - // as `4x` or `4xB`, where x is one of the multiple from K, M, G, T or P. - Limit string `yaml:"limit"` - limit int64 -} - -type limitedReader struct { - BodyLimitConfig - reader io.ReadCloser - read int64 -} - -// DefaultBodyLimitConfig is the default BodyLimit middleware config. -var DefaultBodyLimitConfig = BodyLimitConfig{ - Skipper: DefaultSkipper, -} - -// BodyLimit returns a BodyLimit middleware. -// -// BodyLimit middleware sets the maximum allowed size for a request body, if the -// size exceeds the configured limit, it sends "413 - Request Entity Too Large" -// response. The BodyLimit is determined based on both `Content-Length` request -// header and actual content read, which makes it super secure. -// Limit can be specified as `4x` or `4xB`, where x is one of the multiple from K, M, -// G, T or P. -func BodyLimit(limit string) echo.MiddlewareFunc { - c := DefaultBodyLimitConfig - c.Limit = limit - return BodyLimitWithConfig(c) -} - -// BodyLimitWithConfig returns a BodyLimit middleware with config. -// See: `BodyLimit()`. -func BodyLimitWithConfig(config BodyLimitConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultBodyLimitConfig.Skipper - } - - limit, err := bytes.Parse(config.Limit) - if err != nil { - panic(fmt.Errorf("echo: invalid body-limit=%s", config.Limit)) - } - config.limit = limit - pool := limitedReaderPool(config) - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - req := c.Request() - - // Based on content length - if req.ContentLength > config.limit { - return echo.ErrStatusRequestEntityTooLarge - } - - // Based on content read - r := pool.Get().(*limitedReader) - r.Reset(req.Body) - defer pool.Put(r) - req.Body = r - - return next(c) - } - } -} - -func (r *limitedReader) Read(b []byte) (n int, err error) { - n, err = r.reader.Read(b) - r.read += int64(n) - if r.read > r.limit { - return n, echo.ErrStatusRequestEntityTooLarge - } - return -} - -func (r *limitedReader) Close() error { - return r.reader.Close() -} - -func (r *limitedReader) Reset(reader io.ReadCloser) { - r.reader = reader - r.read = 0 -} - -func limitedReaderPool(c BodyLimitConfig) sync.Pool { - return sync.Pool{ - New: func() interface{} { - return &limitedReader{BodyLimitConfig: c} - }, - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/compress.go b/vendor/github.com/labstack/echo/v4/middleware/compress.go deleted file mode 100644 index 012b76b01..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/compress.go +++ /dev/null @@ -1,230 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "bufio" - "bytes" - "compress/gzip" - "io" - "net" - "net/http" - "strings" - "sync" - - "github.com/labstack/echo/v4" -) - -// GzipConfig defines the config for Gzip middleware. -type GzipConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Gzip compression level. - // Optional. Default value -1. - Level int `yaml:"level"` - - // Length threshold before gzip compression is applied. - // Optional. Default value 0. - // - // Most of the time you will not need to change the default. Compressing - // a short response might increase the transmitted data because of the - // gzip format overhead. Compressing the response will also consume CPU - // and time on the server and the client (for decompressing). Depending on - // your use case such a threshold might be useful. - // - // See also: - // https://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits - MinLength int -} - -type gzipResponseWriter struct { - io.Writer - http.ResponseWriter - wroteHeader bool - wroteBody bool - minLength int - minLengthExceeded bool - buffer *bytes.Buffer - code int -} - -const ( - gzipScheme = "gzip" -) - -// DefaultGzipConfig is the default Gzip middleware config. -var DefaultGzipConfig = GzipConfig{ - Skipper: DefaultSkipper, - Level: -1, - MinLength: 0, -} - -// Gzip returns a middleware which compresses HTTP response using gzip compression -// scheme. -func Gzip() echo.MiddlewareFunc { - return GzipWithConfig(DefaultGzipConfig) -} - -// GzipWithConfig return Gzip middleware with config. -// See: `Gzip()`. -func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultGzipConfig.Skipper - } - if config.Level == 0 { - config.Level = DefaultGzipConfig.Level - } - if config.MinLength < 0 { - config.MinLength = DefaultGzipConfig.MinLength - } - - pool := gzipCompressPool(config) - bpool := bufferPool() - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - res := c.Response() - res.Header().Add(echo.HeaderVary, echo.HeaderAcceptEncoding) - if strings.Contains(c.Request().Header.Get(echo.HeaderAcceptEncoding), gzipScheme) { - i := pool.Get() - w, ok := i.(*gzip.Writer) - if !ok { - return echo.NewHTTPError(http.StatusInternalServerError, i.(error).Error()) - } - rw := res.Writer - w.Reset(rw) - - buf := bpool.Get().(*bytes.Buffer) - buf.Reset() - - grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw, minLength: config.MinLength, buffer: buf} - defer func() { - // There are different reasons for cases when we have not yet written response to the client and now need to do so. - // a) handler response had only response code and no response body (ala 404 or redirects etc). Response code need to be written now. - // b) body is shorter than our minimum length threshold and being buffered currently and needs to be written - if !grw.wroteBody { - if res.Header().Get(echo.HeaderContentEncoding) == gzipScheme { - res.Header().Del(echo.HeaderContentEncoding) - } - if grw.wroteHeader { - rw.WriteHeader(grw.code) - } - // We have to reset response to it's pristine state when - // nothing is written to body or error is returned. - // See issue #424, #407. - res.Writer = rw - w.Reset(io.Discard) - } else if !grw.minLengthExceeded { - // Write uncompressed response - res.Writer = rw - if grw.wroteHeader { - grw.ResponseWriter.WriteHeader(grw.code) - } - grw.buffer.WriteTo(rw) - w.Reset(io.Discard) - } - w.Close() - bpool.Put(buf) - pool.Put(w) - }() - res.Writer = grw - } - return next(c) - } - } -} - -func (w *gzipResponseWriter) WriteHeader(code int) { - w.Header().Del(echo.HeaderContentLength) // Issue #444 - - w.wroteHeader = true - - // Delay writing of the header until we know if we'll actually compress the response - w.code = code -} - -func (w *gzipResponseWriter) Write(b []byte) (int, error) { - if w.Header().Get(echo.HeaderContentType) == "" { - w.Header().Set(echo.HeaderContentType, http.DetectContentType(b)) - } - w.wroteBody = true - - if !w.minLengthExceeded { - n, err := w.buffer.Write(b) - - if w.buffer.Len() >= w.minLength { - w.minLengthExceeded = true - - // The minimum length is exceeded, add Content-Encoding header and write the header - w.Header().Set(echo.HeaderContentEncoding, gzipScheme) // Issue #806 - if w.wroteHeader { - w.ResponseWriter.WriteHeader(w.code) - } - - return w.Writer.Write(w.buffer.Bytes()) - } - - return n, err - } - - return w.Writer.Write(b) -} - -func (w *gzipResponseWriter) Flush() { - if !w.minLengthExceeded { - // Enforce compression because we will not know how much more data will come - w.minLengthExceeded = true - w.Header().Set(echo.HeaderContentEncoding, gzipScheme) // Issue #806 - if w.wroteHeader { - w.ResponseWriter.WriteHeader(w.code) - } - - w.Writer.Write(w.buffer.Bytes()) - } - - w.Writer.(*gzip.Writer).Flush() - _ = http.NewResponseController(w.ResponseWriter).Flush() -} - -func (w *gzipResponseWriter) Unwrap() http.ResponseWriter { - return w.ResponseWriter -} - -func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - return http.NewResponseController(w.ResponseWriter).Hijack() -} - -func (w *gzipResponseWriter) Push(target string, opts *http.PushOptions) error { - if p, ok := w.ResponseWriter.(http.Pusher); ok { - return p.Push(target, opts) - } - return http.ErrNotSupported -} - -func gzipCompressPool(config GzipConfig) sync.Pool { - return sync.Pool{ - New: func() interface{} { - w, err := gzip.NewWriterLevel(io.Discard, config.Level) - if err != nil { - return err - } - return w - }, - } -} - -func bufferPool() sync.Pool { - return sync.Pool{ - New: func() interface{} { - b := &bytes.Buffer{} - return b - }, - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/context_timeout.go b/vendor/github.com/labstack/echo/v4/middleware/context_timeout.go deleted file mode 100644 index e67173f21..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/context_timeout.go +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "context" - "errors" - "time" - - "github.com/labstack/echo/v4" -) - -// ContextTimeoutConfig defines the config for ContextTimeout middleware. -type ContextTimeoutConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // ErrorHandler is a function when error aries in middleware execution. - ErrorHandler func(err error, c echo.Context) error - - // Timeout configures a timeout for the middleware, defaults to 0 for no timeout - Timeout time.Duration -} - -// ContextTimeout returns a middleware which returns error (503 Service Unavailable error) to client -// when underlying method returns context.DeadlineExceeded error. -func ContextTimeout(timeout time.Duration) echo.MiddlewareFunc { - return ContextTimeoutWithConfig(ContextTimeoutConfig{Timeout: timeout}) -} - -// ContextTimeoutWithConfig returns a Timeout middleware with config. -func ContextTimeoutWithConfig(config ContextTimeoutConfig) echo.MiddlewareFunc { - mw, err := config.ToMiddleware() - if err != nil { - panic(err) - } - return mw -} - -// ToMiddleware converts Config to middleware. -func (config ContextTimeoutConfig) ToMiddleware() (echo.MiddlewareFunc, error) { - if config.Timeout == 0 { - return nil, errors.New("timeout must be set") - } - if config.Skipper == nil { - config.Skipper = DefaultSkipper - } - if config.ErrorHandler == nil { - config.ErrorHandler = func(err error, c echo.Context) error { - if err != nil && errors.Is(err, context.DeadlineExceeded) { - return echo.ErrServiceUnavailable.WithInternal(err) - } - return err - } - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - timeoutContext, cancel := context.WithTimeout(c.Request().Context(), config.Timeout) - defer cancel() - - c.SetRequest(c.Request().WithContext(timeoutContext)) - - if err := next(c); err != nil { - return config.ErrorHandler(err, c) - } - return nil - } - }, nil -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/cors.go b/vendor/github.com/labstack/echo/v4/middleware/cors.go deleted file mode 100644 index a1f445321..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/cors.go +++ /dev/null @@ -1,307 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/labstack/echo/v4" -) - -// CORSConfig defines the config for CORS middleware. -type CORSConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // AllowOrigins determines the value of the Access-Control-Allow-Origin - // response header. This header defines a list of origins that may access the - // resource. The wildcard characters '*' and '?' are supported and are - // converted to regex fragments '.*' and '.' accordingly. - // - // Security: use extreme caution when handling the origin, and carefully - // validate any logic. Remember that attackers may register hostile domain names. - // See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html - // - // Optional. Default value []string{"*"}. - // - // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin - AllowOrigins []string `yaml:"allow_origins"` - - // AllowOriginFunc is a custom function to validate the origin. It takes the - // origin as an argument and returns true if allowed or false otherwise. If - // an error is returned, it is returned by the handler. If this option is - // set, AllowOrigins is ignored. - // - // Security: use extreme caution when handling the origin, and carefully - // validate any logic. Remember that attackers may register hostile domain names. - // See https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html - // - // Optional. - AllowOriginFunc func(origin string) (bool, error) `yaml:"-"` - - // AllowMethods determines the value of the Access-Control-Allow-Methods - // response header. This header specified the list of methods allowed when - // accessing the resource. This is used in response to a preflight request. - // - // Optional. Default value DefaultCORSConfig.AllowMethods. - // If `allowMethods` is left empty, this middleware will fill for preflight - // request `Access-Control-Allow-Methods` header value - // from `Allow` header that echo.Router set into context. - // - // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods - AllowMethods []string `yaml:"allow_methods"` - - // AllowHeaders determines the value of the Access-Control-Allow-Headers - // response header. This header is used in response to a preflight request to - // indicate which HTTP headers can be used when making the actual request. - // - // Optional. Default value []string{}. - // - // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers - AllowHeaders []string `yaml:"allow_headers"` - - // AllowCredentials determines the value of the - // Access-Control-Allow-Credentials response header. This header indicates - // whether or not the response to the request can be exposed when the - // credentials mode (Request.credentials) is true. When used as part of a - // response to a preflight request, this indicates whether or not the actual - // request can be made using credentials. See also - // [MDN: Access-Control-Allow-Credentials]. - // - // Optional. Default value false, in which case the header is not set. - // - // Security: avoid using `AllowCredentials = true` with `AllowOrigins = *`. - // See "Exploiting CORS misconfigurations for Bitcoins and bounties", - // https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html - // - // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials - AllowCredentials bool `yaml:"allow_credentials"` - - // UnsafeWildcardOriginWithAllowCredentials UNSAFE/INSECURE: allows wildcard '*' origin to be used with AllowCredentials - // flag. In that case we consider any origin allowed and send it back to the client with `Access-Control-Allow-Origin` header. - // - // This is INSECURE and potentially leads to [cross-origin](https://portswigger.net/research/exploiting-cors-misconfigurations-for-bitcoins-and-bounties) - // attacks. See: https://github.com/labstack/echo/issues/2400 for discussion on the subject. - // - // Optional. Default value is false. - UnsafeWildcardOriginWithAllowCredentials bool `yaml:"unsafe_wildcard_origin_with_allow_credentials"` - - // ExposeHeaders determines the value of Access-Control-Expose-Headers, which - // defines a list of headers that clients are allowed to access. - // - // Optional. Default value []string{}, in which case the header is not set. - // - // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Header - ExposeHeaders []string `yaml:"expose_headers"` - - // MaxAge determines the value of the Access-Control-Max-Age response header. - // This header indicates how long (in seconds) the results of a preflight - // request can be cached. - // The header is set only if MaxAge != 0, negative value sends "0" which instructs browsers not to cache that response. - // - // Optional. Default value 0 - meaning header is not sent. - // - // See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age - MaxAge int `yaml:"max_age"` -} - -// DefaultCORSConfig is the default CORS middleware config. -var DefaultCORSConfig = CORSConfig{ - Skipper: DefaultSkipper, - AllowOrigins: []string{"*"}, - AllowMethods: []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete}, -} - -// CORS returns a Cross-Origin Resource Sharing (CORS) middleware. -// See also [MDN: Cross-Origin Resource Sharing (CORS)]. -// -// Security: Poorly configured CORS can compromise security because it allows -// relaxation of the browser's Same-Origin policy. See [Exploiting CORS -// misconfigurations for Bitcoins and bounties] and [Portswigger: Cross-origin -// resource sharing (CORS)] for more details. -// -// [MDN: Cross-Origin Resource Sharing (CORS)]: https://developer.mozilla.org/en/docs/Web/HTTP/Access_control_CORS -// [Exploiting CORS misconfigurations for Bitcoins and bounties]: https://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html -// [Portswigger: Cross-origin resource sharing (CORS)]: https://portswigger.net/web-security/cors -func CORS() echo.MiddlewareFunc { - return CORSWithConfig(DefaultCORSConfig) -} - -// CORSWithConfig returns a CORS middleware with config. -// See: [CORS]. -func CORSWithConfig(config CORSConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultCORSConfig.Skipper - } - if len(config.AllowOrigins) == 0 { - config.AllowOrigins = DefaultCORSConfig.AllowOrigins - } - hasCustomAllowMethods := true - if len(config.AllowMethods) == 0 { - hasCustomAllowMethods = false - config.AllowMethods = DefaultCORSConfig.AllowMethods - } - - allowOriginPatterns := make([]*regexp.Regexp, 0, len(config.AllowOrigins)) - for _, origin := range config.AllowOrigins { - if origin == "*" { - continue // "*" is handled differently and does not need regexp - } - pattern := regexp.QuoteMeta(origin) - pattern = strings.ReplaceAll(pattern, "\\*", ".*") - pattern = strings.ReplaceAll(pattern, "\\?", ".") - pattern = "^" + pattern + "$" - - re, err := regexp.Compile(pattern) - if err != nil { - // this is to preserve previous behaviour - invalid patterns were just ignored. - // If we would turn this to panic, users with invalid patterns - // would have applications crashing in production due unrecovered panic. - // TODO: this should be turned to error/panic in `v5` - continue - } - allowOriginPatterns = append(allowOriginPatterns, re) - } - - allowMethods := strings.Join(config.AllowMethods, ",") - allowHeaders := strings.Join(config.AllowHeaders, ",") - exposeHeaders := strings.Join(config.ExposeHeaders, ",") - - maxAge := "0" - if config.MaxAge > 0 { - maxAge = strconv.Itoa(config.MaxAge) - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - req := c.Request() - res := c.Response() - origin := req.Header.Get(echo.HeaderOrigin) - allowOrigin := "" - - res.Header().Add(echo.HeaderVary, echo.HeaderOrigin) - - // Preflight request is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, - // Access-Control-Request-Headers, and the Origin header. See: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request - // For simplicity we just consider method type and later `Origin` header. - preflight := req.Method == http.MethodOptions - - // Although router adds special handler in case of OPTIONS method we avoid calling next for OPTIONS in this middleware - // as CORS requests do not have cookies / authentication headers by default, so we could get stuck in auth - // middlewares by calling next(c). - // But we still want to send `Allow` header as response in case of Non-CORS OPTIONS request as router default - // handler does. - routerAllowMethods := "" - if preflight { - tmpAllowMethods, ok := c.Get(echo.ContextKeyHeaderAllow).(string) - if ok && tmpAllowMethods != "" { - routerAllowMethods = tmpAllowMethods - c.Response().Header().Set(echo.HeaderAllow, routerAllowMethods) - } - } - - // No Origin provided. This is (probably) not request from actual browser - proceed executing middleware chain - if origin == "" { - if !preflight { - return next(c) - } - return c.NoContent(http.StatusNoContent) - } - - if config.AllowOriginFunc != nil { - allowed, err := config.AllowOriginFunc(origin) - if err != nil { - return err - } - if allowed { - allowOrigin = origin - } - } else { - // Check allowed origins - for _, o := range config.AllowOrigins { - if o == "*" && config.AllowCredentials && config.UnsafeWildcardOriginWithAllowCredentials { - allowOrigin = origin - break - } - if o == "*" || o == origin { - allowOrigin = o - break - } - if matchSubdomain(origin, o) { - allowOrigin = origin - break - } - } - - checkPatterns := false - if allowOrigin == "" { - // to avoid regex cost by invalid (long) domains (253 is domain name max limit) - if len(origin) <= (253+3+5) && strings.Contains(origin, "://") { - checkPatterns = true - } - } - if checkPatterns { - for _, re := range allowOriginPatterns { - if match := re.MatchString(origin); match { - allowOrigin = origin - break - } - } - } - } - - // Origin not allowed - if allowOrigin == "" { - if !preflight { - return next(c) - } - return c.NoContent(http.StatusNoContent) - } - - res.Header().Set(echo.HeaderAccessControlAllowOrigin, allowOrigin) - if config.AllowCredentials { - res.Header().Set(echo.HeaderAccessControlAllowCredentials, "true") - } - - // Simple request - if !preflight { - if exposeHeaders != "" { - res.Header().Set(echo.HeaderAccessControlExposeHeaders, exposeHeaders) - } - return next(c) - } - - // Preflight request - res.Header().Add(echo.HeaderVary, echo.HeaderAccessControlRequestMethod) - res.Header().Add(echo.HeaderVary, echo.HeaderAccessControlRequestHeaders) - - if !hasCustomAllowMethods && routerAllowMethods != "" { - res.Header().Set(echo.HeaderAccessControlAllowMethods, routerAllowMethods) - } else { - res.Header().Set(echo.HeaderAccessControlAllowMethods, allowMethods) - } - - if allowHeaders != "" { - res.Header().Set(echo.HeaderAccessControlAllowHeaders, allowHeaders) - } else { - h := req.Header.Get(echo.HeaderAccessControlRequestHeaders) - if h != "" { - res.Header().Set(echo.HeaderAccessControlAllowHeaders, h) - } - } - if config.MaxAge != 0 { - res.Header().Set(echo.HeaderAccessControlMaxAge, maxAge) - } - return c.NoContent(http.StatusNoContent) - } - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/csrf.go b/vendor/github.com/labstack/echo/v4/middleware/csrf.go deleted file mode 100644 index 92f4019dc..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/csrf.go +++ /dev/null @@ -1,218 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "crypto/subtle" - "net/http" - "time" - - "github.com/labstack/echo/v4" -) - -// CSRFConfig defines the config for CSRF middleware. -type CSRFConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // TokenLength is the length of the generated token. - TokenLength uint8 `yaml:"token_length"` - // Optional. Default value 32. - - // TokenLookup is a string in the form of ":" or ":,:" that is used - // to extract token from the request. - // Optional. Default value "header:X-CSRF-Token". - // Possible values: - // - "header:" or "header::" - // - "query:" - // - "form:" - // Multiple sources example: - // - "header:X-CSRF-Token,query:csrf" - TokenLookup string `yaml:"token_lookup"` - - // Context key to store generated CSRF token into context. - // Optional. Default value "csrf". - ContextKey string `yaml:"context_key"` - - // Name of the CSRF cookie. This cookie will store CSRF token. - // Optional. Default value "csrf". - CookieName string `yaml:"cookie_name"` - - // Domain of the CSRF cookie. - // Optional. Default value none. - CookieDomain string `yaml:"cookie_domain"` - - // Path of the CSRF cookie. - // Optional. Default value none. - CookiePath string `yaml:"cookie_path"` - - // Max age (in seconds) of the CSRF cookie. - // Optional. Default value 86400 (24hr). - CookieMaxAge int `yaml:"cookie_max_age"` - - // Indicates if CSRF cookie is secure. - // Optional. Default value false. - CookieSecure bool `yaml:"cookie_secure"` - - // Indicates if CSRF cookie is HTTP only. - // Optional. Default value false. - CookieHTTPOnly bool `yaml:"cookie_http_only"` - - // Indicates SameSite mode of the CSRF cookie. - // Optional. Default value SameSiteDefaultMode. - CookieSameSite http.SameSite `yaml:"cookie_same_site"` - - // ErrorHandler defines a function which is executed for returning custom errors. - ErrorHandler CSRFErrorHandler -} - -// CSRFErrorHandler is a function which is executed for creating custom errors. -type CSRFErrorHandler func(err error, c echo.Context) error - -// ErrCSRFInvalid is returned when CSRF check fails -var ErrCSRFInvalid = echo.NewHTTPError(http.StatusForbidden, "invalid csrf token") - -// DefaultCSRFConfig is the default CSRF middleware config. -var DefaultCSRFConfig = CSRFConfig{ - Skipper: DefaultSkipper, - TokenLength: 32, - TokenLookup: "header:" + echo.HeaderXCSRFToken, - ContextKey: "csrf", - CookieName: "_csrf", - CookieMaxAge: 86400, - CookieSameSite: http.SameSiteDefaultMode, -} - -// CSRF returns a Cross-Site Request Forgery (CSRF) middleware. -// See: https://en.wikipedia.org/wiki/Cross-site_request_forgery -func CSRF() echo.MiddlewareFunc { - c := DefaultCSRFConfig - return CSRFWithConfig(c) -} - -// CSRFWithConfig returns a CSRF middleware with config. -// See `CSRF()`. -func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultCSRFConfig.Skipper - } - if config.TokenLength == 0 { - config.TokenLength = DefaultCSRFConfig.TokenLength - } - - if config.TokenLookup == "" { - config.TokenLookup = DefaultCSRFConfig.TokenLookup - } - if config.ContextKey == "" { - config.ContextKey = DefaultCSRFConfig.ContextKey - } - if config.CookieName == "" { - config.CookieName = DefaultCSRFConfig.CookieName - } - if config.CookieMaxAge == 0 { - config.CookieMaxAge = DefaultCSRFConfig.CookieMaxAge - } - if config.CookieSameSite == http.SameSiteNoneMode { - config.CookieSecure = true - } - - extractors, cErr := CreateExtractors(config.TokenLookup) - if cErr != nil { - panic(cErr) - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - token := "" - if k, err := c.Cookie(config.CookieName); err != nil { - token = randomString(config.TokenLength) - } else { - token = k.Value // Reuse token - } - - switch c.Request().Method { - case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace: - default: - // Validate token only for requests which are not defined as 'safe' by RFC7231 - var lastExtractorErr error - var lastTokenErr error - outer: - for _, extractor := range extractors { - clientTokens, err := extractor(c) - if err != nil { - lastExtractorErr = err - continue - } - - for _, clientToken := range clientTokens { - if validateCSRFToken(token, clientToken) { - lastTokenErr = nil - lastExtractorErr = nil - break outer - } - lastTokenErr = ErrCSRFInvalid - } - } - var finalErr error - if lastTokenErr != nil { - finalErr = lastTokenErr - } else if lastExtractorErr != nil { - // ugly part to preserve backwards compatible errors. someone could rely on them - if lastExtractorErr == errQueryExtractorValueMissing { - lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, "missing csrf token in the query string") - } else if lastExtractorErr == errFormExtractorValueMissing { - lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, "missing csrf token in the form parameter") - } else if lastExtractorErr == errHeaderExtractorValueMissing { - lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, "missing csrf token in request header") - } else { - lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, lastExtractorErr.Error()) - } - finalErr = lastExtractorErr - } - - if finalErr != nil { - if config.ErrorHandler != nil { - return config.ErrorHandler(finalErr, c) - } - return finalErr - } - } - - // Set CSRF cookie - cookie := new(http.Cookie) - cookie.Name = config.CookieName - cookie.Value = token - if config.CookiePath != "" { - cookie.Path = config.CookiePath - } - if config.CookieDomain != "" { - cookie.Domain = config.CookieDomain - } - if config.CookieSameSite != http.SameSiteDefaultMode { - cookie.SameSite = config.CookieSameSite - } - cookie.Expires = time.Now().Add(time.Duration(config.CookieMaxAge) * time.Second) - cookie.Secure = config.CookieSecure - cookie.HttpOnly = config.CookieHTTPOnly - c.SetCookie(cookie) - - // Store token in the context - c.Set(config.ContextKey, token) - - // Protect clients from caching the response - c.Response().Header().Add(echo.HeaderVary, echo.HeaderCookie) - - return next(c) - } - } -} - -func validateCSRFToken(token, clientToken string) bool { - return subtle.ConstantTimeCompare([]byte(token), []byte(clientToken)) == 1 -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/decompress.go b/vendor/github.com/labstack/echo/v4/middleware/decompress.go deleted file mode 100644 index 0c56176ee..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/decompress.go +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "compress/gzip" - "io" - "net/http" - "sync" - - "github.com/labstack/echo/v4" -) - -// DecompressConfig defines the config for Decompress middleware. -type DecompressConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // GzipDecompressPool defines an interface to provide the sync.Pool used to create/store Gzip readers - GzipDecompressPool Decompressor -} - -// GZIPEncoding content-encoding header if set to "gzip", decompress body contents. -const GZIPEncoding string = "gzip" - -// Decompressor is used to get the sync.Pool used by the middleware to get Gzip readers -type Decompressor interface { - gzipDecompressPool() sync.Pool -} - -// DefaultDecompressConfig defines the config for decompress middleware -var DefaultDecompressConfig = DecompressConfig{ - Skipper: DefaultSkipper, - GzipDecompressPool: &DefaultGzipDecompressPool{}, -} - -// DefaultGzipDecompressPool is the default implementation of Decompressor interface -type DefaultGzipDecompressPool struct { -} - -func (d *DefaultGzipDecompressPool) gzipDecompressPool() sync.Pool { - return sync.Pool{New: func() interface{} { return new(gzip.Reader) }} -} - -// Decompress decompresses request body based if content encoding type is set to "gzip" with default config -func Decompress() echo.MiddlewareFunc { - return DecompressWithConfig(DefaultDecompressConfig) -} - -// DecompressWithConfig decompresses request body based if content encoding type is set to "gzip" with config -func DecompressWithConfig(config DecompressConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultGzipConfig.Skipper - } - if config.GzipDecompressPool == nil { - config.GzipDecompressPool = DefaultDecompressConfig.GzipDecompressPool - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - pool := config.GzipDecompressPool.gzipDecompressPool() - - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - if c.Request().Header.Get(echo.HeaderContentEncoding) != GZIPEncoding { - return next(c) - } - - i := pool.Get() - gr, ok := i.(*gzip.Reader) - if !ok || gr == nil { - return echo.NewHTTPError(http.StatusInternalServerError, i.(error).Error()) - } - defer pool.Put(gr) - - b := c.Request().Body - defer b.Close() - - if err := gr.Reset(b); err != nil { - if err == io.EOF { //ignore if body is empty - return next(c) - } - return err - } - - // only Close gzip reader if it was set to a proper gzip source otherwise it will panic on close. - defer gr.Close() - - c.Request().Body = gr - - return next(c) - } - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/extractor.go b/vendor/github.com/labstack/echo/v4/middleware/extractor.go deleted file mode 100644 index 3f2741407..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/extractor.go +++ /dev/null @@ -1,207 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "errors" - "fmt" - "github.com/labstack/echo/v4" - "net/textproto" - "strings" -) - -const ( - // extractorLimit is arbitrary number to limit values extractor can return. this limits possible resource exhaustion - // attack vector - extractorLimit = 20 -) - -var errHeaderExtractorValueMissing = errors.New("missing value in request header") -var errHeaderExtractorValueInvalid = errors.New("invalid value in request header") -var errQueryExtractorValueMissing = errors.New("missing value in the query string") -var errParamExtractorValueMissing = errors.New("missing value in path params") -var errCookieExtractorValueMissing = errors.New("missing value in cookies") -var errFormExtractorValueMissing = errors.New("missing value in the form") - -// ValuesExtractor defines a function for extracting values (keys/tokens) from the given context. -type ValuesExtractor func(c echo.Context) ([]string, error) - -// CreateExtractors creates ValuesExtractors from given lookups. -// Lookups is a string in the form of ":" or ":,:" that is used -// to extract key from the request. -// Possible values: -// - "header:" or "header::" -// `` is argument value to cut/trim prefix of the extracted value. This is useful if header -// value has static prefix like `Authorization: ` where part that we -// want to cut is ` ` note the space at the end. -// In case of basic authentication `Authorization: Basic ` prefix we want to remove is `Basic `. -// - "query:" -// - "param:" -// - "form:" -// - "cookie:" -// -// Multiple sources example: -// - "header:Authorization,header:X-Api-Key" -func CreateExtractors(lookups string) ([]ValuesExtractor, error) { - return createExtractors(lookups, "") -} - -func createExtractors(lookups string, authScheme string) ([]ValuesExtractor, error) { - if lookups == "" { - return nil, nil - } - sources := strings.Split(lookups, ",") - var extractors = make([]ValuesExtractor, 0) - for _, source := range sources { - parts := strings.Split(source, ":") - if len(parts) < 2 { - return nil, fmt.Errorf("extractor source for lookup could not be split into needed parts: %v", source) - } - - switch parts[0] { - case "query": - extractors = append(extractors, valuesFromQuery(parts[1])) - case "param": - extractors = append(extractors, valuesFromParam(parts[1])) - case "cookie": - extractors = append(extractors, valuesFromCookie(parts[1])) - case "form": - extractors = append(extractors, valuesFromForm(parts[1])) - case "header": - prefix := "" - if len(parts) > 2 { - prefix = parts[2] - } else if authScheme != "" && parts[1] == echo.HeaderAuthorization { - // backwards compatibility for JWT and KeyAuth: - // * we only apply this fix to Authorization as header we use and uses prefixes like "Bearer " etc - // * previously header extractor assumed that auth-scheme/prefix had a space as suffix we need to retain that - // behaviour for default values and Authorization header. - prefix = authScheme - if !strings.HasSuffix(prefix, " ") { - prefix += " " - } - } - extractors = append(extractors, valuesFromHeader(parts[1], prefix)) - } - } - return extractors, nil -} - -// valuesFromHeader returns a functions that extracts values from the request header. -// valuePrefix is parameter to remove first part (prefix) of the extracted value. This is useful if header value has static -// prefix like `Authorization: ` where part that we want to remove is ` ` -// note the space at the end. In case of basic authentication `Authorization: Basic ` prefix we want to remove -// is `Basic `. In case of JWT tokens `Authorization: Bearer ` prefix is `Bearer `. -// If prefix is left empty the whole value is returned. -func valuesFromHeader(header string, valuePrefix string) ValuesExtractor { - prefixLen := len(valuePrefix) - // standard library parses http.Request header keys in canonical form but we may provide something else so fix this - header = textproto.CanonicalMIMEHeaderKey(header) - return func(c echo.Context) ([]string, error) { - values := c.Request().Header.Values(header) - if len(values) == 0 { - return nil, errHeaderExtractorValueMissing - } - - result := make([]string, 0) - for i, value := range values { - if prefixLen == 0 { - result = append(result, value) - if i >= extractorLimit-1 { - break - } - continue - } - if len(value) > prefixLen && strings.EqualFold(value[:prefixLen], valuePrefix) { - result = append(result, value[prefixLen:]) - if i >= extractorLimit-1 { - break - } - } - } - - if len(result) == 0 { - if prefixLen > 0 { - return nil, errHeaderExtractorValueInvalid - } - return nil, errHeaderExtractorValueMissing - } - return result, nil - } -} - -// valuesFromQuery returns a function that extracts values from the query string. -func valuesFromQuery(param string) ValuesExtractor { - return func(c echo.Context) ([]string, error) { - result := c.QueryParams()[param] - if len(result) == 0 { - return nil, errQueryExtractorValueMissing - } else if len(result) > extractorLimit-1 { - result = result[:extractorLimit] - } - return result, nil - } -} - -// valuesFromParam returns a function that extracts values from the url param string. -func valuesFromParam(param string) ValuesExtractor { - return func(c echo.Context) ([]string, error) { - result := make([]string, 0) - paramVales := c.ParamValues() - for i, p := range c.ParamNames() { - if param == p { - result = append(result, paramVales[i]) - if i >= extractorLimit-1 { - break - } - } - } - if len(result) == 0 { - return nil, errParamExtractorValueMissing - } - return result, nil - } -} - -// valuesFromCookie returns a function that extracts values from the named cookie. -func valuesFromCookie(name string) ValuesExtractor { - return func(c echo.Context) ([]string, error) { - cookies := c.Cookies() - if len(cookies) == 0 { - return nil, errCookieExtractorValueMissing - } - - result := make([]string, 0) - for i, cookie := range cookies { - if name == cookie.Name { - result = append(result, cookie.Value) - if i >= extractorLimit-1 { - break - } - } - } - if len(result) == 0 { - return nil, errCookieExtractorValueMissing - } - return result, nil - } -} - -// valuesFromForm returns a function that extracts values from the form field. -func valuesFromForm(name string) ValuesExtractor { - return func(c echo.Context) ([]string, error) { - if c.Request().Form == nil { - _ = c.Request().ParseMultipartForm(32 << 20) // same what `c.Request().FormValue(name)` does - } - values := c.Request().Form[name] - if len(values) == 0 { - return nil, errFormExtractorValueMissing - } - if len(values) > extractorLimit-1 { - values = values[:extractorLimit] - } - result := append([]string{}, values...) - return result, nil - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/key_auth.go b/vendor/github.com/labstack/echo/v4/middleware/key_auth.go deleted file mode 100644 index 79bee207c..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/key_auth.go +++ /dev/null @@ -1,179 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "errors" - "github.com/labstack/echo/v4" - "net/http" -) - -// KeyAuthConfig defines the config for KeyAuth middleware. -type KeyAuthConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // KeyLookup is a string in the form of ":" or ":,:" that is used - // to extract key from the request. - // Optional. Default value "header:Authorization". - // Possible values: - // - "header:" or "header::" - // `` is argument value to cut/trim prefix of the extracted value. This is useful if header - // value has static prefix like `Authorization: ` where part that we - // want to cut is ` ` note the space at the end. - // In case of basic authentication `Authorization: Basic ` prefix we want to remove is `Basic `. - // - "query:" - // - "form:" - // - "cookie:" - // Multiple sources example: - // - "header:Authorization,header:X-Api-Key" - KeyLookup string - - // AuthScheme to be used in the Authorization header. - // Optional. Default value "Bearer". - AuthScheme string - - // Validator is a function to validate key. - // Required. - Validator KeyAuthValidator - - // ErrorHandler defines a function which is executed for an invalid key. - // It may be used to define a custom error. - ErrorHandler KeyAuthErrorHandler - - // ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandler decides to - // ignore the error (by returning `nil`). - // This is useful when parts of your site/api allow public access and some authorized routes provide extra functionality. - // In that case you can use ErrorHandler to set a default public key auth value in the request context - // and continue. Some logic down the remaining execution chain needs to check that (public) key auth value then. - ContinueOnIgnoredError bool -} - -// KeyAuthValidator defines a function to validate KeyAuth credentials. -type KeyAuthValidator func(auth string, c echo.Context) (bool, error) - -// KeyAuthErrorHandler defines a function which is executed for an invalid key. -type KeyAuthErrorHandler func(err error, c echo.Context) error - -// ErrKeyAuthMissing is error type when KeyAuth middleware is unable to extract value from lookups -type ErrKeyAuthMissing struct { - Err error -} - -// DefaultKeyAuthConfig is the default KeyAuth middleware config. -var DefaultKeyAuthConfig = KeyAuthConfig{ - Skipper: DefaultSkipper, - KeyLookup: "header:" + echo.HeaderAuthorization, - AuthScheme: "Bearer", -} - -// Error returns errors text -func (e *ErrKeyAuthMissing) Error() string { - return e.Err.Error() -} - -// Unwrap unwraps error -func (e *ErrKeyAuthMissing) Unwrap() error { - return e.Err -} - -// KeyAuth returns an KeyAuth middleware. -// -// For valid key it calls the next handler. -// For invalid key, it sends "401 - Unauthorized" response. -// For missing key, it sends "400 - Bad Request" response. -func KeyAuth(fn KeyAuthValidator) echo.MiddlewareFunc { - c := DefaultKeyAuthConfig - c.Validator = fn - return KeyAuthWithConfig(c) -} - -// KeyAuthWithConfig returns an KeyAuth middleware with config. -// See `KeyAuth()`. -func KeyAuthWithConfig(config KeyAuthConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultKeyAuthConfig.Skipper - } - // Defaults - if config.AuthScheme == "" { - config.AuthScheme = DefaultKeyAuthConfig.AuthScheme - } - if config.KeyLookup == "" { - config.KeyLookup = DefaultKeyAuthConfig.KeyLookup - } - if config.Validator == nil { - panic("echo: key-auth middleware requires a validator function") - } - - extractors, cErr := createExtractors(config.KeyLookup, config.AuthScheme) - if cErr != nil { - panic(cErr) - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - var lastExtractorErr error - var lastValidatorErr error - for _, extractor := range extractors { - keys, err := extractor(c) - if err != nil { - lastExtractorErr = err - continue - } - for _, key := range keys { - valid, err := config.Validator(key, c) - if err != nil { - lastValidatorErr = err - continue - } - if valid { - return next(c) - } - lastValidatorErr = errors.New("invalid key") - } - } - - // we are here only when we did not successfully extract and validate any of keys - err := lastValidatorErr - if err == nil { // prioritize validator errors over extracting errors - // ugly part to preserve backwards compatible errors. someone could rely on them - if lastExtractorErr == errQueryExtractorValueMissing { - err = errors.New("missing key in the query string") - } else if lastExtractorErr == errCookieExtractorValueMissing { - err = errors.New("missing key in cookies") - } else if lastExtractorErr == errFormExtractorValueMissing { - err = errors.New("missing key in the form") - } else if lastExtractorErr == errHeaderExtractorValueMissing { - err = errors.New("missing key in request header") - } else if lastExtractorErr == errHeaderExtractorValueInvalid { - err = errors.New("invalid key in the request header") - } else { - err = lastExtractorErr - } - err = &ErrKeyAuthMissing{Err: err} - } - - if config.ErrorHandler != nil { - tmpErr := config.ErrorHandler(err, c) - if config.ContinueOnIgnoredError && tmpErr == nil { - return next(c) - } - return tmpErr - } - if lastValidatorErr != nil { // prioritize validator errors over extracting errors - return &echo.HTTPError{ - Code: http.StatusUnauthorized, - Message: "Unauthorized", - Internal: lastValidatorErr, - } - } - return echo.NewHTTPError(http.StatusBadRequest, err.Error()) - } - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/logger.go b/vendor/github.com/labstack/echo/v4/middleware/logger.go deleted file mode 100644 index 910fce8cf..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/logger.go +++ /dev/null @@ -1,244 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "bytes" - "encoding/json" - "io" - "strconv" - "strings" - "sync" - "time" - - "github.com/labstack/echo/v4" - "github.com/labstack/gommon/color" - "github.com/valyala/fasttemplate" -) - -// LoggerConfig defines the config for Logger middleware. -type LoggerConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Tags to construct the logger format. - // - // - time_unix - // - time_unix_milli - // - time_unix_micro - // - time_unix_nano - // - time_rfc3339 - // - time_rfc3339_nano - // - time_custom - // - id (Request ID) - // - remote_ip - // - uri - // - host - // - method - // - path - // - route - // - protocol - // - referer - // - user_agent - // - status - // - error - // - latency (In nanoseconds) - // - latency_human (Human readable) - // - bytes_in (Bytes received) - // - bytes_out (Bytes sent) - // - header: - // - query: - // - form: - // - custom (see CustomTagFunc field) - // - // Example "${remote_ip} ${status}" - // - // Optional. Default value DefaultLoggerConfig.Format. - Format string `yaml:"format"` - - // Optional. Default value DefaultLoggerConfig.CustomTimeFormat. - CustomTimeFormat string `yaml:"custom_time_format"` - - // CustomTagFunc is function called for `${custom}` tag to output user implemented text by writing it to buf. - // Make sure that outputted text creates valid JSON string with other logged tags. - // Optional. - CustomTagFunc func(c echo.Context, buf *bytes.Buffer) (int, error) - - // Output is a writer where logs in JSON format are written. - // Optional. Default value os.Stdout. - Output io.Writer - - template *fasttemplate.Template - colorer *color.Color - pool *sync.Pool -} - -// DefaultLoggerConfig is the default Logger middleware config. -var DefaultLoggerConfig = LoggerConfig{ - Skipper: DefaultSkipper, - Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}",` + - `"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}",` + - `"status":${status},"error":"${error}","latency":${latency},"latency_human":"${latency_human}"` + - `,"bytes_in":${bytes_in},"bytes_out":${bytes_out}}` + "\n", - CustomTimeFormat: "2006-01-02 15:04:05.00000", - colorer: color.New(), -} - -// Logger returns a middleware that logs HTTP requests. -func Logger() echo.MiddlewareFunc { - return LoggerWithConfig(DefaultLoggerConfig) -} - -// LoggerWithConfig returns a Logger middleware with config. -// See: `Logger()`. -func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultLoggerConfig.Skipper - } - if config.Format == "" { - config.Format = DefaultLoggerConfig.Format - } - if config.Output == nil { - config.Output = DefaultLoggerConfig.Output - } - - config.template = fasttemplate.New(config.Format, "${", "}") - config.colorer = color.New() - config.colorer.SetOutput(config.Output) - config.pool = &sync.Pool{ - New: func() interface{} { - return bytes.NewBuffer(make([]byte, 256)) - }, - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) (err error) { - if config.Skipper(c) { - return next(c) - } - - req := c.Request() - res := c.Response() - start := time.Now() - if err = next(c); err != nil { - c.Error(err) - } - stop := time.Now() - buf := config.pool.Get().(*bytes.Buffer) - buf.Reset() - defer config.pool.Put(buf) - - if _, err = config.template.ExecuteFunc(buf, func(w io.Writer, tag string) (int, error) { - switch tag { - case "custom": - if config.CustomTagFunc == nil { - return 0, nil - } - return config.CustomTagFunc(c, buf) - case "time_unix": - return buf.WriteString(strconv.FormatInt(time.Now().Unix(), 10)) - case "time_unix_milli": - // go 1.17 or later, it supports time#UnixMilli() - return buf.WriteString(strconv.FormatInt(time.Now().UnixNano()/1000000, 10)) - case "time_unix_micro": - // go 1.17 or later, it supports time#UnixMicro() - return buf.WriteString(strconv.FormatInt(time.Now().UnixNano()/1000, 10)) - case "time_unix_nano": - return buf.WriteString(strconv.FormatInt(time.Now().UnixNano(), 10)) - case "time_rfc3339": - return buf.WriteString(time.Now().Format(time.RFC3339)) - case "time_rfc3339_nano": - return buf.WriteString(time.Now().Format(time.RFC3339Nano)) - case "time_custom": - return buf.WriteString(time.Now().Format(config.CustomTimeFormat)) - case "id": - id := req.Header.Get(echo.HeaderXRequestID) - if id == "" { - id = res.Header().Get(echo.HeaderXRequestID) - } - return buf.WriteString(id) - case "remote_ip": - return buf.WriteString(c.RealIP()) - case "host": - return buf.WriteString(req.Host) - case "uri": - return buf.WriteString(req.RequestURI) - case "method": - return buf.WriteString(req.Method) - case "path": - p := req.URL.Path - if p == "" { - p = "/" - } - return buf.WriteString(p) - case "route": - return buf.WriteString(c.Path()) - case "protocol": - return buf.WriteString(req.Proto) - case "referer": - return buf.WriteString(req.Referer()) - case "user_agent": - return buf.WriteString(req.UserAgent()) - case "status": - n := res.Status - s := config.colorer.Green(n) - switch { - case n >= 500: - s = config.colorer.Red(n) - case n >= 400: - s = config.colorer.Yellow(n) - case n >= 300: - s = config.colorer.Cyan(n) - } - return buf.WriteString(s) - case "error": - if err != nil { - // Error may contain invalid JSON e.g. `"` - b, _ := json.Marshal(err.Error()) - b = b[1 : len(b)-1] - return buf.Write(b) - } - case "latency": - l := stop.Sub(start) - return buf.WriteString(strconv.FormatInt(int64(l), 10)) - case "latency_human": - return buf.WriteString(stop.Sub(start).String()) - case "bytes_in": - cl := req.Header.Get(echo.HeaderContentLength) - if cl == "" { - cl = "0" - } - return buf.WriteString(cl) - case "bytes_out": - return buf.WriteString(strconv.FormatInt(res.Size, 10)) - default: - switch { - case strings.HasPrefix(tag, "header:"): - return buf.Write([]byte(c.Request().Header.Get(tag[7:]))) - case strings.HasPrefix(tag, "query:"): - return buf.Write([]byte(c.QueryParam(tag[6:]))) - case strings.HasPrefix(tag, "form:"): - return buf.Write([]byte(c.FormValue(tag[5:]))) - case strings.HasPrefix(tag, "cookie:"): - cookie, err := c.Cookie(tag[7:]) - if err == nil { - return buf.Write([]byte(cookie.Value)) - } - } - } - return 0, nil - }); err != nil { - return - } - - if config.Output == nil { - _, err = c.Logger().Output().Write(buf.Bytes()) - return - } - _, err = config.Output.Write(buf.Bytes()) - return - } - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/method_override.go b/vendor/github.com/labstack/echo/v4/middleware/method_override.go deleted file mode 100644 index 3991e1029..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/method_override.go +++ /dev/null @@ -1,91 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "net/http" - - "github.com/labstack/echo/v4" -) - -// MethodOverrideConfig defines the config for MethodOverride middleware. -type MethodOverrideConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Getter is a function that gets overridden method from the request. - // Optional. Default values MethodFromHeader(echo.HeaderXHTTPMethodOverride). - Getter MethodOverrideGetter -} - -// MethodOverrideGetter is a function that gets overridden method from the request -type MethodOverrideGetter func(echo.Context) string - -// DefaultMethodOverrideConfig is the default MethodOverride middleware config. -var DefaultMethodOverrideConfig = MethodOverrideConfig{ - Skipper: DefaultSkipper, - Getter: MethodFromHeader(echo.HeaderXHTTPMethodOverride), -} - -// MethodOverride returns a MethodOverride middleware. -// MethodOverride middleware checks for the overridden method from the request and -// uses it instead of the original method. -// -// For security reasons, only `POST` method can be overridden. -func MethodOverride() echo.MiddlewareFunc { - return MethodOverrideWithConfig(DefaultMethodOverrideConfig) -} - -// MethodOverrideWithConfig returns a MethodOverride middleware with config. -// See: `MethodOverride()`. -func MethodOverrideWithConfig(config MethodOverrideConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultMethodOverrideConfig.Skipper - } - if config.Getter == nil { - config.Getter = DefaultMethodOverrideConfig.Getter - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - req := c.Request() - if req.Method == http.MethodPost { - m := config.Getter(c) - if m != "" { - req.Method = m - } - } - return next(c) - } - } -} - -// MethodFromHeader is a `MethodOverrideGetter` that gets overridden method from -// the request header. -func MethodFromHeader(header string) MethodOverrideGetter { - return func(c echo.Context) string { - return c.Request().Header.Get(header) - } -} - -// MethodFromForm is a `MethodOverrideGetter` that gets overridden method from the -// form parameter. -func MethodFromForm(param string) MethodOverrideGetter { - return func(c echo.Context) string { - return c.FormValue(param) - } -} - -// MethodFromQuery is a `MethodOverrideGetter` that gets overridden method from -// the query parameter. -func MethodFromQuery(param string) MethodOverrideGetter { - return func(c echo.Context) string { - return c.QueryParam(param) - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/middleware.go b/vendor/github.com/labstack/echo/v4/middleware/middleware.go deleted file mode 100644 index 6f33cc5c1..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/middleware.go +++ /dev/null @@ -1,90 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/labstack/echo/v4" -) - -// Skipper defines a function to skip middleware. Returning true skips processing -// the middleware. -type Skipper func(c echo.Context) bool - -// BeforeFunc defines a function which is executed just before the middleware. -type BeforeFunc func(c echo.Context) - -func captureTokens(pattern *regexp.Regexp, input string) *strings.Replacer { - groups := pattern.FindAllStringSubmatch(input, -1) - if groups == nil { - return nil - } - values := groups[0][1:] - replace := make([]string, 2*len(values)) - for i, v := range values { - j := 2 * i - replace[j] = "$" + strconv.Itoa(i+1) - replace[j+1] = v - } - return strings.NewReplacer(replace...) -} - -func rewriteRulesRegex(rewrite map[string]string) map[*regexp.Regexp]string { - // Initialize - rulesRegex := map[*regexp.Regexp]string{} - for k, v := range rewrite { - k = regexp.QuoteMeta(k) - k = strings.ReplaceAll(k, `\*`, "(.*?)") - if strings.HasPrefix(k, `\^`) { - k = strings.ReplaceAll(k, `\^`, "^") - } - k = k + "$" - rulesRegex[regexp.MustCompile(k)] = v - } - return rulesRegex -} - -func rewriteURL(rewriteRegex map[*regexp.Regexp]string, req *http.Request) error { - if len(rewriteRegex) == 0 { - return nil - } - - // Depending on how HTTP request is sent RequestURI could contain Scheme://Host/path or be just /path. - // We only want to use path part for rewriting and therefore trim prefix if it exists - rawURI := req.RequestURI - if rawURI != "" && rawURI[0] != '/' { - prefix := "" - if req.URL.Scheme != "" { - prefix = req.URL.Scheme + "://" - } - if req.URL.Host != "" { - prefix += req.URL.Host // host or host:port - } - if prefix != "" { - rawURI = strings.TrimPrefix(rawURI, prefix) - } - } - - for k, v := range rewriteRegex { - if replacer := captureTokens(k, rawURI); replacer != nil { - url, err := req.URL.Parse(replacer.Replace(v)) - if err != nil { - return err - } - req.URL = url - - return nil // rewrite only once - } - } - return nil -} - -// DefaultSkipper returns false which processes the middleware. -func DefaultSkipper(echo.Context) bool { - return false -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/proxy.go b/vendor/github.com/labstack/echo/v4/middleware/proxy.go deleted file mode 100644 index 495970aca..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/proxy.go +++ /dev/null @@ -1,421 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "context" - "fmt" - "io" - "math/rand" - "net" - "net/http" - "net/http/httputil" - "net/url" - "regexp" - "strings" - "sync" - "time" - - "github.com/labstack/echo/v4" -) - -// TODO: Handle TLS proxy - -// ProxyConfig defines the config for Proxy middleware. -type ProxyConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Balancer defines a load balancing technique. - // Required. - Balancer ProxyBalancer - - // RetryCount defines the number of times a failed proxied request should be retried - // using the next available ProxyTarget. Defaults to 0, meaning requests are never retried. - RetryCount int - - // RetryFilter defines a function used to determine if a failed request to a - // ProxyTarget should be retried. The RetryFilter will only be called when the number - // of previous retries is less than RetryCount. If the function returns true, the - // request will be retried. The provided error indicates the reason for the request - // failure. When the ProxyTarget is unavailable, the error will be an instance of - // echo.HTTPError with a Code of http.StatusBadGateway. In all other cases, the error - // will indicate an internal error in the Proxy middleware. When a RetryFilter is not - // specified, all requests that fail with http.StatusBadGateway will be retried. A custom - // RetryFilter can be provided to only retry specific requests. Note that RetryFilter is - // only called when the request to the target fails, or an internal error in the Proxy - // middleware has occurred. Successful requests that return a non-200 response code cannot - // be retried. - RetryFilter func(c echo.Context, e error) bool - - // ErrorHandler defines a function which can be used to return custom errors from - // the Proxy middleware. ErrorHandler is only invoked when there has been - // either an internal error in the Proxy middleware or the ProxyTarget is - // unavailable. Due to the way requests are proxied, ErrorHandler is not invoked - // when a ProxyTarget returns a non-200 response. In these cases, the response - // is already written so errors cannot be modified. ErrorHandler is only - // invoked after all retry attempts have been exhausted. - ErrorHandler func(c echo.Context, err error) error - - // Rewrite defines URL path rewrite rules. The values captured in asterisk can be - // retrieved by index e.g. $1, $2 and so on. - // Examples: - // "/old": "/new", - // "/api/*": "/$1", - // "/js/*": "/public/javascripts/$1", - // "/users/*/orders/*": "/user/$1/order/$2", - Rewrite map[string]string - - // RegexRewrite defines rewrite rules using regexp.Rexexp with captures - // Every capture group in the values can be retrieved by index e.g. $1, $2 and so on. - // Example: - // "^/old/[0.9]+/": "/new", - // "^/api/.+?/(.*)": "/v2/$1", - RegexRewrite map[*regexp.Regexp]string - - // Context key to store selected ProxyTarget into context. - // Optional. Default value "target". - ContextKey string - - // To customize the transport to remote. - // Examples: If custom TLS certificates are required. - Transport http.RoundTripper - - // ModifyResponse defines function to modify response from ProxyTarget. - ModifyResponse func(*http.Response) error -} - -// ProxyTarget defines the upstream target. -type ProxyTarget struct { - Name string - URL *url.URL - Meta echo.Map -} - -// ProxyBalancer defines an interface to implement a load balancing technique. -type ProxyBalancer interface { - AddTarget(*ProxyTarget) bool - RemoveTarget(string) bool - Next(echo.Context) *ProxyTarget -} - -// TargetProvider defines an interface that gives the opportunity for balancer -// to return custom errors when selecting target. -type TargetProvider interface { - NextTarget(echo.Context) (*ProxyTarget, error) -} - -type commonBalancer struct { - targets []*ProxyTarget - mutex sync.Mutex -} - -// RandomBalancer implements a random load balancing technique. -type randomBalancer struct { - commonBalancer - random *rand.Rand -} - -// RoundRobinBalancer implements a round-robin load balancing technique. -type roundRobinBalancer struct { - commonBalancer - // tracking the index on `targets` slice for the next `*ProxyTarget` to be used - i int -} - -// DefaultProxyConfig is the default Proxy middleware config. -var DefaultProxyConfig = ProxyConfig{ - Skipper: DefaultSkipper, - ContextKey: "target", -} - -func proxyRaw(t *ProxyTarget, c echo.Context) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - in, _, err := c.Response().Hijack() - if err != nil { - c.Set("_error", fmt.Errorf("proxy raw, hijack error=%w, url=%s", err, t.URL)) - return - } - defer in.Close() - - out, err := net.Dial("tcp", t.URL.Host) - if err != nil { - c.Set("_error", echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("proxy raw, dial error=%v, url=%s", err, t.URL))) - return - } - defer out.Close() - - // Write header - err = r.Write(out) - if err != nil { - c.Set("_error", echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("proxy raw, request header copy error=%v, url=%s", err, t.URL))) - return - } - - errCh := make(chan error, 2) - cp := func(dst io.Writer, src io.Reader) { - _, err = io.Copy(dst, src) - errCh <- err - } - - go cp(out, in) - go cp(in, out) - err = <-errCh - if err != nil && err != io.EOF { - c.Set("_error", fmt.Errorf("proxy raw, copy body error=%w, url=%s", err, t.URL)) - } - }) -} - -// NewRandomBalancer returns a random proxy balancer. -func NewRandomBalancer(targets []*ProxyTarget) ProxyBalancer { - b := randomBalancer{} - b.targets = targets - b.random = rand.New(rand.NewSource(int64(time.Now().Nanosecond()))) - return &b -} - -// NewRoundRobinBalancer returns a round-robin proxy balancer. -func NewRoundRobinBalancer(targets []*ProxyTarget) ProxyBalancer { - b := roundRobinBalancer{} - b.targets = targets - return &b -} - -// AddTarget adds an upstream target to the list and returns `true`. -// -// However, if a target with the same name already exists then the operation is aborted returning `false`. -func (b *commonBalancer) AddTarget(target *ProxyTarget) bool { - b.mutex.Lock() - defer b.mutex.Unlock() - for _, t := range b.targets { - if t.Name == target.Name { - return false - } - } - b.targets = append(b.targets, target) - return true -} - -// RemoveTarget removes an upstream target from the list by name. -// -// Returns `true` on success, `false` if no target with the name is found. -func (b *commonBalancer) RemoveTarget(name string) bool { - b.mutex.Lock() - defer b.mutex.Unlock() - for i, t := range b.targets { - if t.Name == name { - b.targets = append(b.targets[:i], b.targets[i+1:]...) - return true - } - } - return false -} - -// Next randomly returns an upstream target. -// -// Note: `nil` is returned in case upstream target list is empty. -func (b *randomBalancer) Next(c echo.Context) *ProxyTarget { - b.mutex.Lock() - defer b.mutex.Unlock() - if len(b.targets) == 0 { - return nil - } else if len(b.targets) == 1 { - return b.targets[0] - } - return b.targets[b.random.Intn(len(b.targets))] -} - -// Next returns an upstream target using round-robin technique. In the case -// where a previously failed request is being retried, the round-robin -// balancer will attempt to use the next target relative to the original -// request. If the list of targets held by the balancer is modified while a -// failed request is being retried, it is possible that the balancer will -// return the original failed target. -// -// Note: `nil` is returned in case upstream target list is empty. -func (b *roundRobinBalancer) Next(c echo.Context) *ProxyTarget { - b.mutex.Lock() - defer b.mutex.Unlock() - if len(b.targets) == 0 { - return nil - } else if len(b.targets) == 1 { - return b.targets[0] - } - - var i int - const lastIdxKey = "_round_robin_last_index" - // This request is a retry, start from the index of the previous - // target to ensure we don't attempt to retry the request with - // the same failed target - if c.Get(lastIdxKey) != nil { - i = c.Get(lastIdxKey).(int) - i++ - if i >= len(b.targets) { - i = 0 - } - } else { - // This is a first time request, use the global index - if b.i >= len(b.targets) { - b.i = 0 - } - i = b.i - b.i++ - } - - c.Set(lastIdxKey, i) - return b.targets[i] -} - -// Proxy returns a Proxy middleware. -// -// Proxy middleware forwards the request to upstream server using a configured load balancing technique. -func Proxy(balancer ProxyBalancer) echo.MiddlewareFunc { - c := DefaultProxyConfig - c.Balancer = balancer - return ProxyWithConfig(c) -} - -// ProxyWithConfig returns a Proxy middleware with config. -// See: `Proxy()` -func ProxyWithConfig(config ProxyConfig) echo.MiddlewareFunc { - if config.Balancer == nil { - panic("echo: proxy middleware requires balancer") - } - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultProxyConfig.Skipper - } - if config.RetryFilter == nil { - config.RetryFilter = func(c echo.Context, e error) bool { - if httpErr, ok := e.(*echo.HTTPError); ok { - return httpErr.Code == http.StatusBadGateway - } - return false - } - } - if config.ErrorHandler == nil { - config.ErrorHandler = func(c echo.Context, err error) error { - return err - } - } - if config.Rewrite != nil { - if config.RegexRewrite == nil { - config.RegexRewrite = make(map[*regexp.Regexp]string) - } - for k, v := range rewriteRulesRegex(config.Rewrite) { - config.RegexRewrite[k] = v - } - } - - provider, isTargetProvider := config.Balancer.(TargetProvider) - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - req := c.Request() - res := c.Response() - if err := rewriteURL(config.RegexRewrite, req); err != nil { - return config.ErrorHandler(c, err) - } - - // Fix header - // Basically it's not good practice to unconditionally pass incoming x-real-ip header to upstream. - // However, for backward compatibility, legacy behavior is preserved unless you configure Echo#IPExtractor. - if req.Header.Get(echo.HeaderXRealIP) == "" || c.Echo().IPExtractor != nil { - req.Header.Set(echo.HeaderXRealIP, c.RealIP()) - } - if req.Header.Get(echo.HeaderXForwardedProto) == "" { - req.Header.Set(echo.HeaderXForwardedProto, c.Scheme()) - } - if c.IsWebSocket() && req.Header.Get(echo.HeaderXForwardedFor) == "" { // For HTTP, it is automatically set by Go HTTP reverse proxy. - req.Header.Set(echo.HeaderXForwardedFor, c.RealIP()) - } - - retries := config.RetryCount - for { - var tgt *ProxyTarget - var err error - if isTargetProvider { - tgt, err = provider.NextTarget(c) - if err != nil { - return config.ErrorHandler(c, err) - } - } else { - tgt = config.Balancer.Next(c) - } - - c.Set(config.ContextKey, tgt) - - //If retrying a failed request, clear any previous errors from - //context here so that balancers have the option to check for - //errors that occurred using previous target - if retries < config.RetryCount { - c.Set("_error", nil) - } - - // This is needed for ProxyConfig.ModifyResponse and/or ProxyConfig.Transport to be able to process the Request - // that Balancer may have replaced with c.SetRequest. - req = c.Request() - - // Proxy - switch { - case c.IsWebSocket(): - proxyRaw(tgt, c).ServeHTTP(res, req) - default: // even SSE requests - proxyHTTP(tgt, c, config).ServeHTTP(res, req) - } - - err, hasError := c.Get("_error").(error) - if !hasError { - return nil - } - - retry := retries > 0 && config.RetryFilter(c, err) - if !retry { - return config.ErrorHandler(c, err) - } - - retries-- - } - } - } -} - -// StatusCodeContextCanceled is a custom HTTP status code for situations -// where a client unexpectedly closed the connection to the server. -// As there is no standard error code for "client closed connection", but -// various well-known HTTP clients and server implement this HTTP code we use -// 499 too instead of the more problematic 5xx, which does not allow to detect this situation -const StatusCodeContextCanceled = 499 - -func proxyHTTP(tgt *ProxyTarget, c echo.Context, config ProxyConfig) http.Handler { - proxy := httputil.NewSingleHostReverseProxy(tgt.URL) - proxy.ErrorHandler = func(resp http.ResponseWriter, req *http.Request, err error) { - desc := tgt.URL.String() - if tgt.Name != "" { - desc = fmt.Sprintf("%s(%s)", tgt.Name, tgt.URL.String()) - } - // If the client canceled the request (usually by closing the connection), we can report a - // client error (4xx) instead of a server error (5xx) to correctly identify the situation. - // The Go standard library (at of late 2020) wraps the exported, standard - // context.Canceled error with unexported garbage value requiring a substring check, see - // https://github.com/golang/go/blob/6965b01ea248cabb70c3749fd218b36089a21efb/src/net/net.go#L416-L430 - if err == context.Canceled || strings.Contains(err.Error(), "operation was canceled") { - httpError := echo.NewHTTPError(StatusCodeContextCanceled, fmt.Sprintf("client closed connection: %v", err)) - httpError.Internal = err - c.Set("_error", httpError) - } else { - httpError := echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("remote %s unreachable, could not forward: %v", desc, err)) - httpError.Internal = err - c.Set("_error", httpError) - } - } - proxy.Transport = config.Transport - proxy.ModifyResponse = config.ModifyResponse - return proxy -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/rate_limiter.go b/vendor/github.com/labstack/echo/v4/middleware/rate_limiter.go deleted file mode 100644 index d4724fd2a..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/rate_limiter.go +++ /dev/null @@ -1,267 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "net/http" - "sync" - "time" - - "github.com/labstack/echo/v4" - "golang.org/x/time/rate" -) - -// RateLimiterStore is the interface to be implemented by custom stores. -type RateLimiterStore interface { - // Stores for the rate limiter have to implement the Allow method - Allow(identifier string) (bool, error) -} - -// RateLimiterConfig defines the configuration for the rate limiter -type RateLimiterConfig struct { - Skipper Skipper - BeforeFunc BeforeFunc - // IdentifierExtractor uses echo.Context to extract the identifier for a visitor - IdentifierExtractor Extractor - // Store defines a store for the rate limiter - Store RateLimiterStore - // ErrorHandler provides a handler to be called when IdentifierExtractor returns an error - ErrorHandler func(context echo.Context, err error) error - // DenyHandler provides a handler to be called when RateLimiter denies access - DenyHandler func(context echo.Context, identifier string, err error) error -} - -// Extractor is used to extract data from echo.Context -type Extractor func(context echo.Context) (string, error) - -// ErrRateLimitExceeded denotes an error raised when rate limit is exceeded -var ErrRateLimitExceeded = echo.NewHTTPError(http.StatusTooManyRequests, "rate limit exceeded") - -// ErrExtractorError denotes an error raised when extractor function is unsuccessful -var ErrExtractorError = echo.NewHTTPError(http.StatusForbidden, "error while extracting identifier") - -// DefaultRateLimiterConfig defines default values for RateLimiterConfig -var DefaultRateLimiterConfig = RateLimiterConfig{ - Skipper: DefaultSkipper, - IdentifierExtractor: func(ctx echo.Context) (string, error) { - id := ctx.RealIP() - return id, nil - }, - ErrorHandler: func(context echo.Context, err error) error { - return &echo.HTTPError{ - Code: ErrExtractorError.Code, - Message: ErrExtractorError.Message, - Internal: err, - } - }, - DenyHandler: func(context echo.Context, identifier string, err error) error { - return &echo.HTTPError{ - Code: ErrRateLimitExceeded.Code, - Message: ErrRateLimitExceeded.Message, - Internal: err, - } - }, -} - -/* -RateLimiter returns a rate limiting middleware - - e := echo.New() - - limiterStore := middleware.NewRateLimiterMemoryStore(20) - - e.GET("/rate-limited", func(c echo.Context) error { - return c.String(http.StatusOK, "test") - }, RateLimiter(limiterStore)) -*/ -func RateLimiter(store RateLimiterStore) echo.MiddlewareFunc { - config := DefaultRateLimiterConfig - config.Store = store - - return RateLimiterWithConfig(config) -} - -/* -RateLimiterWithConfig returns a rate limiting middleware - - e := echo.New() - - config := middleware.RateLimiterConfig{ - Skipper: DefaultSkipper, - Store: middleware.NewRateLimiterMemoryStore( - middleware.RateLimiterMemoryStoreConfig{Rate: 10, Burst: 30, ExpiresIn: 3 * time.Minute} - ) - IdentifierExtractor: func(ctx echo.Context) (string, error) { - id := ctx.RealIP() - return id, nil - }, - ErrorHandler: func(context echo.Context, err error) error { - return context.JSON(http.StatusTooManyRequests, nil) - }, - DenyHandler: func(context echo.Context, identifier string) error { - return context.JSON(http.StatusForbidden, nil) - }, - } - - e.GET("/rate-limited", func(c echo.Context) error { - return c.String(http.StatusOK, "test") - }, middleware.RateLimiterWithConfig(config)) -*/ -func RateLimiterWithConfig(config RateLimiterConfig) echo.MiddlewareFunc { - if config.Skipper == nil { - config.Skipper = DefaultRateLimiterConfig.Skipper - } - if config.IdentifierExtractor == nil { - config.IdentifierExtractor = DefaultRateLimiterConfig.IdentifierExtractor - } - if config.ErrorHandler == nil { - config.ErrorHandler = DefaultRateLimiterConfig.ErrorHandler - } - if config.DenyHandler == nil { - config.DenyHandler = DefaultRateLimiterConfig.DenyHandler - } - if config.Store == nil { - panic("Store configuration must be provided") - } - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - if config.BeforeFunc != nil { - config.BeforeFunc(c) - } - - identifier, err := config.IdentifierExtractor(c) - if err != nil { - c.Error(config.ErrorHandler(c, err)) - return nil - } - - if allow, err := config.Store.Allow(identifier); !allow { - c.Error(config.DenyHandler(c, identifier, err)) - return nil - } - return next(c) - } - } -} - -// RateLimiterMemoryStore is the built-in store implementation for RateLimiter -type RateLimiterMemoryStore struct { - visitors map[string]*Visitor - mutex sync.Mutex - rate rate.Limit // for more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit. - - burst int - expiresIn time.Duration - lastCleanup time.Time - - timeNow func() time.Time -} - -// Visitor signifies a unique user's limiter details -type Visitor struct { - *rate.Limiter - lastSeen time.Time -} - -/* -NewRateLimiterMemoryStore returns an instance of RateLimiterMemoryStore with -the provided rate (as req/s). -for more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit. - -Burst and ExpiresIn will be set to default values. - -Note that if the provided rate is a float number and Burst is zero, Burst will be treated as the rounded down value of the rate. - -Example (with 20 requests/sec): - - limiterStore := middleware.NewRateLimiterMemoryStore(20) -*/ -func NewRateLimiterMemoryStore(rate rate.Limit) (store *RateLimiterMemoryStore) { - return NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{ - Rate: rate, - }) -} - -/* -NewRateLimiterMemoryStoreWithConfig returns an instance of RateLimiterMemoryStore -with the provided configuration. Rate must be provided. Burst will be set to the rounded down value of -the configured rate if not provided or set to 0. - -The build-in memory store is usually capable for modest loads. For higher loads other -store implementations should be considered. - -Characteristics: -* Concurrency above 100 parallel requests may causes measurable lock contention -* A high number of different IP addresses (above 16000) may be impacted by the internally used Go map -* A high number of requests from a single IP address may cause lock contention - -Example: - - limiterStore := middleware.NewRateLimiterMemoryStoreWithConfig( - middleware.RateLimiterMemoryStoreConfig{Rate: 50, Burst: 200, ExpiresIn: 5 * time.Minute}, - ) -*/ -func NewRateLimiterMemoryStoreWithConfig(config RateLimiterMemoryStoreConfig) (store *RateLimiterMemoryStore) { - store = &RateLimiterMemoryStore{} - - store.rate = config.Rate - store.burst = config.Burst - store.expiresIn = config.ExpiresIn - if config.ExpiresIn == 0 { - store.expiresIn = DefaultRateLimiterMemoryStoreConfig.ExpiresIn - } - if config.Burst == 0 { - store.burst = int(config.Rate) - } - store.visitors = make(map[string]*Visitor) - store.timeNow = time.Now - store.lastCleanup = store.timeNow() - return -} - -// RateLimiterMemoryStoreConfig represents configuration for RateLimiterMemoryStore -type RateLimiterMemoryStoreConfig struct { - Rate rate.Limit // Rate of requests allowed to pass as req/s. For more info check out Limiter docs - https://pkg.go.dev/golang.org/x/time/rate#Limit. - Burst int // Burst is maximum number of requests to pass at the same moment. It additionally allows a number of requests to pass when rate limit is reached. - ExpiresIn time.Duration // ExpiresIn is the duration after that a rate limiter is cleaned up -} - -// DefaultRateLimiterMemoryStoreConfig provides default configuration values for RateLimiterMemoryStore -var DefaultRateLimiterMemoryStoreConfig = RateLimiterMemoryStoreConfig{ - ExpiresIn: 3 * time.Minute, -} - -// Allow implements RateLimiterStore.Allow -func (store *RateLimiterMemoryStore) Allow(identifier string) (bool, error) { - store.mutex.Lock() - limiter, exists := store.visitors[identifier] - if !exists { - limiter = new(Visitor) - limiter.Limiter = rate.NewLimiter(store.rate, store.burst) - store.visitors[identifier] = limiter - } - now := store.timeNow() - limiter.lastSeen = now - if now.Sub(store.lastCleanup) > store.expiresIn { - store.cleanupStaleVisitors() - } - store.mutex.Unlock() - return limiter.AllowN(store.timeNow(), 1), nil -} - -/* -cleanupStaleVisitors helps manage the size of the visitors map by removing stale records -of users who haven't visited again after the configured expiry time has elapsed -*/ -func (store *RateLimiterMemoryStore) cleanupStaleVisitors() { - for id, visitor := range store.visitors { - if store.timeNow().Sub(visitor.lastSeen) > store.expiresIn { - delete(store.visitors, id) - } - } - store.lastCleanup = store.timeNow() -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/recover.go b/vendor/github.com/labstack/echo/v4/middleware/recover.go deleted file mode 100644 index e6a5940e4..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/recover.go +++ /dev/null @@ -1,133 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "fmt" - "net/http" - "runtime" - - "github.com/labstack/echo/v4" - "github.com/labstack/gommon/log" -) - -// LogErrorFunc defines a function for custom logging in the middleware. -type LogErrorFunc func(c echo.Context, err error, stack []byte) error - -// RecoverConfig defines the config for Recover middleware. -type RecoverConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Size of the stack to be printed. - // Optional. Default value 4KB. - StackSize int `yaml:"stack_size"` - - // DisableStackAll disables formatting stack traces of all other goroutines - // into buffer after the trace for the current goroutine. - // Optional. Default value false. - DisableStackAll bool `yaml:"disable_stack_all"` - - // DisablePrintStack disables printing stack trace. - // Optional. Default value as false. - DisablePrintStack bool `yaml:"disable_print_stack"` - - // LogLevel is log level to printing stack trace. - // Optional. Default value 0 (Print). - LogLevel log.Lvl - - // LogErrorFunc defines a function for custom logging in the middleware. - // If it's set you don't need to provide LogLevel for config. - // If this function returns nil, the centralized HTTPErrorHandler will not be called. - LogErrorFunc LogErrorFunc - - // DisableErrorHandler disables the call to centralized HTTPErrorHandler. - // The recovered error is then passed back to upstream middleware, instead of swallowing the error. - // Optional. Default value false. - DisableErrorHandler bool `yaml:"disable_error_handler"` -} - -// DefaultRecoverConfig is the default Recover middleware config. -var DefaultRecoverConfig = RecoverConfig{ - Skipper: DefaultSkipper, - StackSize: 4 << 10, // 4 KB - DisableStackAll: false, - DisablePrintStack: false, - LogLevel: 0, - LogErrorFunc: nil, - DisableErrorHandler: false, -} - -// Recover returns a middleware which recovers from panics anywhere in the chain -// and handles the control to the centralized HTTPErrorHandler. -func Recover() echo.MiddlewareFunc { - return RecoverWithConfig(DefaultRecoverConfig) -} - -// RecoverWithConfig returns a Recover middleware with config. -// See: `Recover()`. -func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultRecoverConfig.Skipper - } - if config.StackSize == 0 { - config.StackSize = DefaultRecoverConfig.StackSize - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) (returnErr error) { - if config.Skipper(c) { - return next(c) - } - - defer func() { - if r := recover(); r != nil { - if r == http.ErrAbortHandler { - panic(r) - } - err, ok := r.(error) - if !ok { - err = fmt.Errorf("%v", r) - } - var stack []byte - var length int - - if !config.DisablePrintStack { - stack = make([]byte, config.StackSize) - length = runtime.Stack(stack, !config.DisableStackAll) - stack = stack[:length] - } - - if config.LogErrorFunc != nil { - err = config.LogErrorFunc(c, err, stack) - } else if !config.DisablePrintStack { - msg := fmt.Sprintf("[PANIC RECOVER] %v %s\n", err, stack[:length]) - switch config.LogLevel { - case log.DEBUG: - c.Logger().Debug(msg) - case log.INFO: - c.Logger().Info(msg) - case log.WARN: - c.Logger().Warn(msg) - case log.ERROR: - c.Logger().Error(msg) - case log.OFF: - // None. - default: - c.Logger().Print(msg) - } - } - - if err != nil && !config.DisableErrorHandler { - c.Error(err) - } else { - returnErr = err - } - } - }() - return next(c) - } - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/redirect.go b/vendor/github.com/labstack/echo/v4/middleware/redirect.go deleted file mode 100644 index b772ac131..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/redirect.go +++ /dev/null @@ -1,155 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "net/http" - "strings" - - "github.com/labstack/echo/v4" -) - -// RedirectConfig defines the config for Redirect middleware. -type RedirectConfig struct { - // Skipper defines a function to skip middleware. - Skipper - - // Status code to be used when redirecting the request. - // Optional. Default value http.StatusMovedPermanently. - Code int `yaml:"code"` -} - -// redirectLogic represents a function that given a scheme, host and uri -// can both: 1) determine if redirect is needed (will set ok accordingly) and -// 2) return the appropriate redirect url. -type redirectLogic func(scheme, host, uri string) (ok bool, url string) - -const www = "www." - -// DefaultRedirectConfig is the default Redirect middleware config. -var DefaultRedirectConfig = RedirectConfig{ - Skipper: DefaultSkipper, - Code: http.StatusMovedPermanently, -} - -// HTTPSRedirect redirects http requests to https. -// For example, http://labstack.com will be redirect to https://labstack.com. -// -// Usage `Echo#Pre(HTTPSRedirect())` -func HTTPSRedirect() echo.MiddlewareFunc { - return HTTPSRedirectWithConfig(DefaultRedirectConfig) -} - -// HTTPSRedirectWithConfig returns an HTTPSRedirect middleware with config. -// See `HTTPSRedirect()`. -func HTTPSRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { - return redirect(config, func(scheme, host, uri string) (bool, string) { - if scheme != "https" { - return true, "https://" + host + uri - } - return false, "" - }) -} - -// HTTPSWWWRedirect redirects http requests to https www. -// For example, http://labstack.com will be redirect to https://www.labstack.com. -// -// Usage `Echo#Pre(HTTPSWWWRedirect())` -func HTTPSWWWRedirect() echo.MiddlewareFunc { - return HTTPSWWWRedirectWithConfig(DefaultRedirectConfig) -} - -// HTTPSWWWRedirectWithConfig returns an HTTPSRedirect middleware with config. -// See `HTTPSWWWRedirect()`. -func HTTPSWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { - return redirect(config, func(scheme, host, uri string) (bool, string) { - if scheme != "https" && !strings.HasPrefix(host, www) { - return true, "https://www." + host + uri - } - return false, "" - }) -} - -// HTTPSNonWWWRedirect redirects http requests to https non www. -// For example, http://www.labstack.com will be redirect to https://labstack.com. -// -// Usage `Echo#Pre(HTTPSNonWWWRedirect())` -func HTTPSNonWWWRedirect() echo.MiddlewareFunc { - return HTTPSNonWWWRedirectWithConfig(DefaultRedirectConfig) -} - -// HTTPSNonWWWRedirectWithConfig returns an HTTPSRedirect middleware with config. -// See `HTTPSNonWWWRedirect()`. -func HTTPSNonWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { - return redirect(config, func(scheme, host, uri string) (ok bool, url string) { - if scheme != "https" { - host = strings.TrimPrefix(host, www) - return true, "https://" + host + uri - } - return false, "" - }) -} - -// WWWRedirect redirects non www requests to www. -// For example, http://labstack.com will be redirect to http://www.labstack.com. -// -// Usage `Echo#Pre(WWWRedirect())` -func WWWRedirect() echo.MiddlewareFunc { - return WWWRedirectWithConfig(DefaultRedirectConfig) -} - -// WWWRedirectWithConfig returns an HTTPSRedirect middleware with config. -// See `WWWRedirect()`. -func WWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { - return redirect(config, func(scheme, host, uri string) (bool, string) { - if !strings.HasPrefix(host, www) { - return true, scheme + "://www." + host + uri - } - return false, "" - }) -} - -// NonWWWRedirect redirects www requests to non www. -// For example, http://www.labstack.com will be redirect to http://labstack.com. -// -// Usage `Echo#Pre(NonWWWRedirect())` -func NonWWWRedirect() echo.MiddlewareFunc { - return NonWWWRedirectWithConfig(DefaultRedirectConfig) -} - -// NonWWWRedirectWithConfig returns an HTTPSRedirect middleware with config. -// See `NonWWWRedirect()`. -func NonWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { - return redirect(config, func(scheme, host, uri string) (bool, string) { - if strings.HasPrefix(host, www) { - return true, scheme + "://" + host[4:] + uri - } - return false, "" - }) -} - -func redirect(config RedirectConfig, cb redirectLogic) echo.MiddlewareFunc { - if config.Skipper == nil { - config.Skipper = DefaultRedirectConfig.Skipper - } - if config.Code == 0 { - config.Code = DefaultRedirectConfig.Code - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - req, scheme := c.Request(), c.Scheme() - host := req.Host - if ok, url := cb(scheme, host, req.RequestURI); ok { - return c.Redirect(config.Code, url) - } - - return next(c) - } - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/request_id.go b/vendor/github.com/labstack/echo/v4/middleware/request_id.go deleted file mode 100644 index 14bd4fd15..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/request_id.go +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "github.com/labstack/echo/v4" -) - -// RequestIDConfig defines the config for RequestID middleware. -type RequestIDConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Generator defines a function to generate an ID. - // Optional. Defaults to generator for random string of length 32. - Generator func() string - - // RequestIDHandler defines a function which is executed for a request id. - RequestIDHandler func(echo.Context, string) - - // TargetHeader defines what header to look for to populate the id - TargetHeader string -} - -// DefaultRequestIDConfig is the default RequestID middleware config. -var DefaultRequestIDConfig = RequestIDConfig{ - Skipper: DefaultSkipper, - Generator: generator, - TargetHeader: echo.HeaderXRequestID, -} - -// RequestID returns a X-Request-ID middleware. -func RequestID() echo.MiddlewareFunc { - return RequestIDWithConfig(DefaultRequestIDConfig) -} - -// RequestIDWithConfig returns a X-Request-ID middleware with config. -func RequestIDWithConfig(config RequestIDConfig) echo.MiddlewareFunc { - // Defaults - if config.Skipper == nil { - config.Skipper = DefaultRequestIDConfig.Skipper - } - if config.Generator == nil { - config.Generator = generator - } - if config.TargetHeader == "" { - config.TargetHeader = echo.HeaderXRequestID - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - req := c.Request() - res := c.Response() - rid := req.Header.Get(config.TargetHeader) - if rid == "" { - rid = config.Generator() - } - res.Header().Set(config.TargetHeader, rid) - if config.RequestIDHandler != nil { - config.RequestIDHandler(c, rid) - } - - return next(c) - } - } -} - -func generator() string { - return randomString(32) -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/request_logger.go b/vendor/github.com/labstack/echo/v4/middleware/request_logger.go deleted file mode 100644 index 7c18200b0..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/request_logger.go +++ /dev/null @@ -1,391 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "errors" - "net/http" - "time" - - "github.com/labstack/echo/v4" -) - -// Example for `slog` https://pkg.go.dev/log/slog -// logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) -// e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ -// LogStatus: true, -// LogURI: true, -// LogError: true, -// HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code -// LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { -// if v.Error == nil { -// logger.LogAttrs(context.Background(), slog.LevelInfo, "REQUEST", -// slog.String("uri", v.URI), -// slog.Int("status", v.Status), -// ) -// } else { -// logger.LogAttrs(context.Background(), slog.LevelError, "REQUEST_ERROR", -// slog.String("uri", v.URI), -// slog.Int("status", v.Status), -// slog.String("err", v.Error.Error()), -// ) -// } -// return nil -// }, -// })) -// -// Example for `fmt.Printf` -// e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ -// LogStatus: true, -// LogURI: true, -// LogError: true, -// HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code -// LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { -// if v.Error == nil { -// fmt.Printf("REQUEST: uri: %v, status: %v\n", v.URI, v.Status) -// } else { -// fmt.Printf("REQUEST_ERROR: uri: %v, status: %v, err: %v\n", v.URI, v.Status, v.Error) -// } -// return nil -// }, -// })) -// -// Example for Zerolog (https://github.com/rs/zerolog) -// logger := zerolog.New(os.Stdout) -// e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ -// LogURI: true, -// LogStatus: true, -// LogError: true, -// HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code -// LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { -// if v.Error == nil { -// logger.Info(). -// Str("URI", v.URI). -// Int("status", v.Status). -// Msg("request") -// } else { -// logger.Error(). -// Err(v.Error). -// Str("URI", v.URI). -// Int("status", v.Status). -// Msg("request error") -// } -// return nil -// }, -// })) -// -// Example for Zap (https://github.com/uber-go/zap) -// logger, _ := zap.NewProduction() -// e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ -// LogURI: true, -// LogStatus: true, -// LogError: true, -// HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code -// LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { -// if v.Error == nil { -// logger.Info("request", -// zap.String("URI", v.URI), -// zap.Int("status", v.Status), -// ) -// } else { -// logger.Error("request error", -// zap.String("URI", v.URI), -// zap.Int("status", v.Status), -// zap.Error(v.Error), -// ) -// } -// return nil -// }, -// })) -// -// Example for Logrus (https://github.com/sirupsen/logrus) -// log := logrus.New() -// e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ -// LogURI: true, -// LogStatus: true, -// LogError: true, -// HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code -// LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { -// if v.Error == nil { -// log.WithFields(logrus.Fields{ -// "URI": v.URI, -// "status": v.Status, -// }).Info("request") -// } else { -// log.WithFields(logrus.Fields{ -// "URI": v.URI, -// "status": v.Status, -// "error": v.Error, -// }).Error("request error") -// } -// return nil -// }, -// })) - -// RequestLoggerConfig is configuration for Request Logger middleware. -type RequestLoggerConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // BeforeNextFunc defines a function that is called before next middleware or handler is called in chain. - BeforeNextFunc func(c echo.Context) - // LogValuesFunc defines a function that is called with values extracted by logger from request/response. - // Mandatory. - LogValuesFunc func(c echo.Context, v RequestLoggerValues) error - - // HandleError instructs logger to call global error handler when next middleware/handler returns an error. - // This is useful when you have custom error handler that can decide to use different status codes. - // - // A side-effect of calling global error handler is that now Response has been committed and sent to the client - // and middlewares up in chain can not change Response status code or response body. - HandleError bool - - // LogLatency instructs logger to record duration it took to execute rest of the handler chain (next(c) call). - LogLatency bool - // LogProtocol instructs logger to extract request protocol (i.e. `HTTP/1.1` or `HTTP/2`) - LogProtocol bool - // LogRemoteIP instructs logger to extract request remote IP. See `echo.Context.RealIP()` for implementation details. - LogRemoteIP bool - // LogHost instructs logger to extract request host value (i.e. `example.com`) - LogHost bool - // LogMethod instructs logger to extract request method value (i.e. `GET` etc) - LogMethod bool - // LogURI instructs logger to extract request URI (i.e. `/list?lang=en&page=1`) - LogURI bool - // LogURIPath instructs logger to extract request URI path part (i.e. `/list`) - LogURIPath bool - // LogRoutePath instructs logger to extract route path part to which request was matched to (i.e. `/user/:id`) - LogRoutePath bool - // LogRequestID instructs logger to extract request ID from request `X-Request-ID` header or response if request did not have value. - LogRequestID bool - // LogReferer instructs logger to extract request referer values. - LogReferer bool - // LogUserAgent instructs logger to extract request user agent values. - LogUserAgent bool - // LogStatus instructs logger to extract response status code. If handler chain returns an echo.HTTPError, - // the status code is extracted from the echo.HTTPError returned - LogStatus bool - // LogError instructs logger to extract error returned from executed handler chain. - LogError bool - // LogContentLength instructs logger to extract content length header value. Note: this value could be different from - // actual request body size as it could be spoofed etc. - LogContentLength bool - // LogResponseSize instructs logger to extract response content length value. Note: when used with Gzip middleware - // this value may not be always correct. - LogResponseSize bool - // LogHeaders instructs logger to extract given list of headers from request. Note: request can contain more than - // one header with same value so slice of values is been logger for each given header. - // - // Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header - // names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding". - LogHeaders []string - // LogQueryParams instructs logger to extract given list of query parameters from request URI. Note: request can - // contain more than one query parameter with same name so slice of values is been logger for each given query param name. - LogQueryParams []string - // LogFormValues instructs logger to extract given list of form values from request body+URI. Note: request can - // contain more than one form value with same name so slice of values is been logger for each given form value name. - LogFormValues []string - - timeNow func() time.Time -} - -// RequestLoggerValues contains extracted values from logger. -type RequestLoggerValues struct { - // StartTime is time recorded before next middleware/handler is executed. - StartTime time.Time - // Latency is duration it took to execute rest of the handler chain (next(c) call). - Latency time.Duration - // Protocol is request protocol (i.e. `HTTP/1.1` or `HTTP/2`) - Protocol string - // RemoteIP is request remote IP. See `echo.Context.RealIP()` for implementation details. - RemoteIP string - // Host is request host value (i.e. `example.com`) - Host string - // Method is request method value (i.e. `GET` etc) - Method string - // URI is request URI (i.e. `/list?lang=en&page=1`) - URI string - // URIPath is request URI path part (i.e. `/list`) - URIPath string - // RoutePath is route path part to which request was matched to (i.e. `/user/:id`) - RoutePath string - // RequestID is request ID from request `X-Request-ID` header or response if request did not have value. - RequestID string - // Referer is request referer values. - Referer string - // UserAgent is request user agent values. - UserAgent string - // Status is response status code. Then handler returns an echo.HTTPError then code from there. - Status int - // Error is error returned from executed handler chain. - Error error - // ContentLength is content length header value. Note: this value could be different from actual request body size - // as it could be spoofed etc. - ContentLength string - // ResponseSize is response content length value. Note: when used with Gzip middleware this value may not be always correct. - ResponseSize int64 - // Headers are list of headers from request. Note: request can contain more than one header with same value so slice - // of values is been logger for each given header. - // Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header - // names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding". - Headers map[string][]string - // QueryParams are list of query parameters from request URI. Note: request can contain more than one query parameter - // with same name so slice of values is been logger for each given query param name. - QueryParams map[string][]string - // FormValues are list of form values from request body+URI. Note: request can contain more than one form value with - // same name so slice of values is been logger for each given form value name. - FormValues map[string][]string -} - -// RequestLoggerWithConfig returns a RequestLogger middleware with config. -func RequestLoggerWithConfig(config RequestLoggerConfig) echo.MiddlewareFunc { - mw, err := config.ToMiddleware() - if err != nil { - panic(err) - } - return mw -} - -// ToMiddleware converts RequestLoggerConfig into middleware or returns an error for invalid configuration. -func (config RequestLoggerConfig) ToMiddleware() (echo.MiddlewareFunc, error) { - if config.Skipper == nil { - config.Skipper = DefaultSkipper - } - now := time.Now - if config.timeNow != nil { - now = config.timeNow - } - - if config.LogValuesFunc == nil { - return nil, errors.New("missing LogValuesFunc callback function for request logger middleware") - } - - logHeaders := len(config.LogHeaders) > 0 - headers := append([]string(nil), config.LogHeaders...) - for i, v := range headers { - headers[i] = http.CanonicalHeaderKey(v) - } - - logQueryParams := len(config.LogQueryParams) > 0 - logFormValues := len(config.LogFormValues) > 0 - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - if config.Skipper(c) { - return next(c) - } - - req := c.Request() - res := c.Response() - start := now() - - if config.BeforeNextFunc != nil { - config.BeforeNextFunc(c) - } - err := next(c) - if err != nil && config.HandleError { - c.Error(err) - } - - v := RequestLoggerValues{ - StartTime: start, - } - if config.LogLatency { - v.Latency = now().Sub(start) - } - if config.LogProtocol { - v.Protocol = req.Proto - } - if config.LogRemoteIP { - v.RemoteIP = c.RealIP() - } - if config.LogHost { - v.Host = req.Host - } - if config.LogMethod { - v.Method = req.Method - } - if config.LogURI { - v.URI = req.RequestURI - } - if config.LogURIPath { - p := req.URL.Path - if p == "" { - p = "/" - } - v.URIPath = p - } - if config.LogRoutePath { - v.RoutePath = c.Path() - } - if config.LogRequestID { - id := req.Header.Get(echo.HeaderXRequestID) - if id == "" { - id = res.Header().Get(echo.HeaderXRequestID) - } - v.RequestID = id - } - if config.LogReferer { - v.Referer = req.Referer() - } - if config.LogUserAgent { - v.UserAgent = req.UserAgent() - } - if config.LogStatus { - v.Status = res.Status - if err != nil && !config.HandleError { - // this block should not be executed in case of HandleError=true as the global error handler will decide - // the status code. In that case status code could be different from what err contains. - var httpErr *echo.HTTPError - if errors.As(err, &httpErr) { - v.Status = httpErr.Code - } - } - } - if config.LogError && err != nil { - v.Error = err - } - if config.LogContentLength { - v.ContentLength = req.Header.Get(echo.HeaderContentLength) - } - if config.LogResponseSize { - v.ResponseSize = res.Size - } - if logHeaders { - v.Headers = map[string][]string{} - for _, header := range headers { - if values, ok := req.Header[header]; ok { - v.Headers[header] = values - } - } - } - if logQueryParams { - queryParams := c.QueryParams() - v.QueryParams = map[string][]string{} - for _, param := range config.LogQueryParams { - if values, ok := queryParams[param]; ok { - v.QueryParams[param] = values - } - } - } - if logFormValues { - v.FormValues = map[string][]string{} - for _, formValue := range config.LogFormValues { - if values, ok := req.Form[formValue]; ok { - v.FormValues[formValue] = values - } - } - } - - if errOnLog := config.LogValuesFunc(c, v); errOnLog != nil { - return errOnLog - } - - // in case of HandleError=true we are returning the error that we already have handled with global error handler - // this is deliberate as this error could be useful for upstream middlewares and default global error handler - // will ignore that error when it bubbles up in middleware chain. - return err - } - }, nil -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/rewrite.go b/vendor/github.com/labstack/echo/v4/middleware/rewrite.go deleted file mode 100644 index 4c19cc1cc..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/rewrite.go +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "regexp" - - "github.com/labstack/echo/v4" -) - -// RewriteConfig defines the config for Rewrite middleware. -type RewriteConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // Rules defines the URL path rewrite rules. The values captured in asterisk can be - // retrieved by index e.g. $1, $2 and so on. - // Example: - // "/old": "/new", - // "/api/*": "/$1", - // "/js/*": "/public/javascripts/$1", - // "/users/*/orders/*": "/user/$1/order/$2", - // Required. - Rules map[string]string `yaml:"rules"` - - // RegexRules defines the URL path rewrite rules using regexp.Rexexp with captures - // Every capture group in the values can be retrieved by index e.g. $1, $2 and so on. - // Example: - // "^/old/[0.9]+/": "/new", - // "^/api/.+?/(.*)": "/v2/$1", - RegexRules map[*regexp.Regexp]string `yaml:"-"` -} - -// DefaultRewriteConfig is the default Rewrite middleware config. -var DefaultRewriteConfig = RewriteConfig{ - Skipper: DefaultSkipper, -} - -// Rewrite returns a Rewrite middleware. -// -// Rewrite middleware rewrites the URL path based on the provided rules. -func Rewrite(rules map[string]string) echo.MiddlewareFunc { - c := DefaultRewriteConfig - c.Rules = rules - return RewriteWithConfig(c) -} - -// RewriteWithConfig returns a Rewrite middleware with config. -// See: `Rewrite()`. -func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc { - // Defaults - if config.Rules == nil && config.RegexRules == nil { - panic("echo: rewrite middleware requires url path rewrite rules or regex rules") - } - - if config.Skipper == nil { - config.Skipper = DefaultBodyDumpConfig.Skipper - } - - if config.RegexRules == nil { - config.RegexRules = make(map[*regexp.Regexp]string) - } - for k, v := range rewriteRulesRegex(config.Rules) { - config.RegexRules[k] = v - } - - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) (err error) { - if config.Skipper(c) { - return next(c) - } - - if err := rewriteURL(config.RegexRules, c.Request()); err != nil { - return err - } - return next(c) - } - } -} diff --git a/vendor/github.com/labstack/echo/v4/middleware/secure.go b/vendor/github.com/labstack/echo/v4/middleware/secure.go deleted file mode 100644 index c904abf1a..000000000 --- a/vendor/github.com/labstack/echo/v4/middleware/secure.go +++ /dev/null @@ -1,144 +0,0 @@ -// SPDX-License-Identifier: MIT -// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors - -package middleware - -import ( - "fmt" - - "github.com/labstack/echo/v4" -) - -// SecureConfig defines the config for Secure middleware. -type SecureConfig struct { - // Skipper defines a function to skip middleware. - Skipper Skipper - - // XSSProtection provides protection against cross-site scripting attack (XSS) - // by setting the `X-XSS-Protection` header. - // Optional. Default value "1; mode=block". - XSSProtection string `yaml:"xss_protection"` - - // ContentTypeNosniff provides protection against overriding Content-Type - // header by setting the `X-Content-Type-Options` header. - // Optional. Default value "nosniff". - ContentTypeNosniff string `yaml:"content_type_nosniff"` - - // XFrameOptions can be used to indicate whether or not a browser should - // be allowed to render a page in a ,